xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorizationLegality.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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 //
16 
17 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
18 #include "llvm/Analysis/Loads.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/Analysis/VectorUtils.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/PatternMatch.h"
25 #include "llvm/Transforms/Utils/SizeOpts.h"
26 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
27 
28 using namespace llvm;
29 using namespace PatternMatch;
30 
31 #define LV_NAME "loop-vectorize"
32 #define DEBUG_TYPE LV_NAME
33 
34 extern cl::opt<bool> EnableVPlanPredication;
35 
36 static cl::opt<bool>
37     EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
38                        cl::desc("Enable if-conversion during vectorization."));
39 
40 namespace llvm {
41 cl::opt<bool>
42     HintsAllowReordering("hints-allow-reordering", cl::init(true), cl::Hidden,
43                          cl::desc("Allow enabling loop hints to reorder "
44                                   "FP operations during vectorization."));
45 }
46 
47 // TODO: Move size-based thresholds out of legality checking, make cost based
48 // decisions instead of hard thresholds.
49 static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
50     "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
51     cl::desc("The maximum number of SCEV checks allowed."));
52 
53 static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
54     "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
55     cl::desc("The maximum number of SCEV checks allowed with a "
56              "vectorize(enable) pragma"));
57 
58 // FIXME: When scalable vectorization is stable enough, change the default
59 // to SK_PreferFixedWidth.
60 static cl::opt<LoopVectorizeHints::ScalableForceKind> ScalableVectorization(
61     "scalable-vectorization", cl::init(LoopVectorizeHints::SK_FixedWidthOnly),
62     cl::Hidden,
63     cl::desc("Control whether the compiler can use scalable vectors to "
64              "vectorize a loop"),
65     cl::values(
66         clEnumValN(LoopVectorizeHints::SK_FixedWidthOnly, "off",
67                    "Scalable vectorization is disabled."),
68         clEnumValN(LoopVectorizeHints::SK_PreferFixedWidth, "on",
69                    "Scalable vectorization is available, but favor fixed-width "
70                    "vectorization when the cost is inconclusive."),
71         clEnumValN(LoopVectorizeHints::SK_PreferScalable, "preferred",
72                    "Scalable vectorization is available and favored when the "
73                    "cost is inconclusive.")));
74 
75 /// Maximum vectorization interleave count.
76 static const unsigned MaxInterleaveFactor = 16;
77 
78 namespace llvm {
79 
80 bool LoopVectorizeHints::Hint::validate(unsigned Val) {
81   switch (Kind) {
82   case HK_WIDTH:
83     return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
84   case HK_INTERLEAVE:
85     return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
86   case HK_FORCE:
87     return (Val <= 1);
88   case HK_ISVECTORIZED:
89   case HK_PREDICATE:
90   case HK_SCALABLE:
91     return (Val == 0 || Val == 1);
92   }
93   return false;
94 }
95 
96 LoopVectorizeHints::LoopVectorizeHints(const Loop *L,
97                                        bool InterleaveOnlyWhenForced,
98                                        OptimizationRemarkEmitter &ORE)
99     : Width("vectorize.width", VectorizerParams::VectorizationFactor, HK_WIDTH),
100       Interleave("interleave.count", InterleaveOnlyWhenForced, HK_INTERLEAVE),
101       Force("vectorize.enable", FK_Undefined, HK_FORCE),
102       IsVectorized("isvectorized", 0, HK_ISVECTORIZED),
103       Predicate("vectorize.predicate.enable", FK_Undefined, HK_PREDICATE),
104       Scalable("vectorize.scalable.enable", SK_Unspecified, HK_SCALABLE),
105       TheLoop(L), ORE(ORE) {
106   // Populate values with existing loop metadata.
107   getHintsFromMetadata();
108 
109   // force-vector-interleave overrides DisableInterleaving.
110   if (VectorizerParams::isInterleaveForced())
111     Interleave.Value = VectorizerParams::VectorizationInterleave;
112 
113   if ((LoopVectorizeHints::ScalableForceKind)Scalable.Value == SK_Unspecified)
114     // If the width is set, but the metadata says nothing about the scalable
115     // property, then assume it concerns only a fixed-width UserVF.
116     // If width is not set, the flag takes precedence.
117     Scalable.Value = Width.Value ? SK_FixedWidthOnly : ScalableVectorization;
118   else if (ScalableVectorization == SK_FixedWidthOnly)
119     // If the flag is set to disable any use of scalable vectors, override the
120     // loop hint.
121     Scalable.Value = SK_FixedWidthOnly;
122 
123   if (IsVectorized.Value != 1)
124     // If the vectorization width and interleaving count are both 1 then
125     // consider the loop to have been already vectorized because there's
126     // nothing more that we can do.
127     IsVectorized.Value =
128         getWidth() == ElementCount::getFixed(1) && getInterleave() == 1;
129   LLVM_DEBUG(if (InterleaveOnlyWhenForced && getInterleave() == 1) dbgs()
130              << "LV: Interleaving disabled by the pass manager\n");
131 }
132 
133 void LoopVectorizeHints::setAlreadyVectorized() {
134   LLVMContext &Context = TheLoop->getHeader()->getContext();
135 
136   MDNode *IsVectorizedMD = MDNode::get(
137       Context,
138       {MDString::get(Context, "llvm.loop.isvectorized"),
139        ConstantAsMetadata::get(ConstantInt::get(Context, APInt(32, 1)))});
140   MDNode *LoopID = TheLoop->getLoopID();
141   MDNode *NewLoopID =
142       makePostTransformationMetadata(Context, LoopID,
143                                      {Twine(Prefix(), "vectorize.").str(),
144                                       Twine(Prefix(), "interleave.").str()},
145                                      {IsVectorizedMD});
146   TheLoop->setLoopID(NewLoopID);
147 
148   // Update internal cache.
149   IsVectorized.Value = 1;
150 }
151 
152 bool LoopVectorizeHints::allowVectorization(
153     Function *F, Loop *L, bool VectorizeOnlyWhenForced) const {
154   if (getForce() == LoopVectorizeHints::FK_Disabled) {
155     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
156     emitRemarkWithHints();
157     return false;
158   }
159 
160   if (VectorizeOnlyWhenForced && getForce() != LoopVectorizeHints::FK_Enabled) {
161     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
162     emitRemarkWithHints();
163     return false;
164   }
165 
166   if (getIsVectorized() == 1) {
167     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
168     // FIXME: Add interleave.disable metadata. This will allow
169     // vectorize.disable to be used without disabling the pass and errors
170     // to differentiate between disabled vectorization and a width of 1.
171     ORE.emit([&]() {
172       return OptimizationRemarkAnalysis(vectorizeAnalysisPassName(),
173                                         "AllDisabled", L->getStartLoc(),
174                                         L->getHeader())
175              << "loop not vectorized: vectorization and interleaving are "
176                 "explicitly disabled, or the loop has already been "
177                 "vectorized";
178     });
179     return false;
180   }
181 
182   return true;
183 }
184 
185 void LoopVectorizeHints::emitRemarkWithHints() const {
186   using namespace ore;
187 
188   ORE.emit([&]() {
189     if (Force.Value == LoopVectorizeHints::FK_Disabled)
190       return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
191                                       TheLoop->getStartLoc(),
192                                       TheLoop->getHeader())
193              << "loop not vectorized: vectorization is explicitly disabled";
194     else {
195       OptimizationRemarkMissed R(LV_NAME, "MissedDetails",
196                                  TheLoop->getStartLoc(), TheLoop->getHeader());
197       R << "loop not vectorized";
198       if (Force.Value == LoopVectorizeHints::FK_Enabled) {
199         R << " (Force=" << NV("Force", true);
200         if (Width.Value != 0)
201           R << ", Vector Width=" << NV("VectorWidth", getWidth());
202         if (getInterleave() != 0)
203           R << ", Interleave Count=" << NV("InterleaveCount", getInterleave());
204         R << ")";
205       }
206       return R;
207     }
208   });
209 }
210 
211 const char *LoopVectorizeHints::vectorizeAnalysisPassName() const {
212   if (getWidth() == ElementCount::getFixed(1))
213     return LV_NAME;
214   if (getForce() == LoopVectorizeHints::FK_Disabled)
215     return LV_NAME;
216   if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth().isZero())
217     return LV_NAME;
218   return OptimizationRemarkAnalysis::AlwaysPrint;
219 }
220 
221 bool LoopVectorizeHints::allowReordering() const {
222   // Allow the vectorizer to change the order of operations if enabling
223   // loop hints are provided
224   ElementCount EC = getWidth();
225   return HintsAllowReordering &&
226          (getForce() == LoopVectorizeHints::FK_Enabled ||
227           EC.getKnownMinValue() > 1);
228 }
229 
230 void LoopVectorizeHints::getHintsFromMetadata() {
231   MDNode *LoopID = TheLoop->getLoopID();
232   if (!LoopID)
233     return;
234 
235   // First operand should refer to the loop id itself.
236   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
237   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
238 
239   for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
240     const MDString *S = nullptr;
241     SmallVector<Metadata *, 4> Args;
242 
243     // The expected hint is either a MDString or a MDNode with the first
244     // operand a MDString.
245     if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
246       if (!MD || MD->getNumOperands() == 0)
247         continue;
248       S = dyn_cast<MDString>(MD->getOperand(0));
249       for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
250         Args.push_back(MD->getOperand(i));
251     } else {
252       S = dyn_cast<MDString>(LoopID->getOperand(i));
253       assert(Args.size() == 0 && "too many arguments for MDString");
254     }
255 
256     if (!S)
257       continue;
258 
259     // Check if the hint starts with the loop metadata prefix.
260     StringRef Name = S->getString();
261     if (Args.size() == 1)
262       setHint(Name, Args[0]);
263   }
264 }
265 
266 void LoopVectorizeHints::setHint(StringRef Name, Metadata *Arg) {
267   if (!Name.startswith(Prefix()))
268     return;
269   Name = Name.substr(Prefix().size(), StringRef::npos);
270 
271   const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
272   if (!C)
273     return;
274   unsigned Val = C->getZExtValue();
275 
276   Hint *Hints[] = {&Width,        &Interleave, &Force,
277                    &IsVectorized, &Predicate,  &Scalable};
278   for (auto H : Hints) {
279     if (Name == H->Name) {
280       if (H->validate(Val))
281         H->Value = Val;
282       else
283         LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
284       break;
285     }
286   }
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.
321   PHINode *IV = Lp->getCanonicalInductionVariable();
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.
373 static bool canIfConvertPHINodes(BasicBlock *BB) {
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 
383 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
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 
422 int LoopVectorizationLegality::isConsecutivePtr(Type *AccessTy,
423                                                 Value *Ptr) const {
424   const ValueToValueMap &Strides =
425       getSymbolicStrides() ? *getSymbolicStrides() : ValueToValueMap();
426 
427   Function *F = TheLoop->getHeader()->getParent();
428   bool OptForSize = F->hasOptSize() ||
429                     llvm::shouldOptimizeForSize(TheLoop->getHeader(), PSI, BFI,
430                                                 PGSOQueryType::IRPass);
431   bool CanAddPredicate = !OptForSize;
432   int Stride = getPtrStride(PSE, AccessTy, Ptr, TheLoop, Strides,
433                             CanAddPredicate, false);
434   if (Stride == 1 || Stride == -1)
435     return Stride;
436   return 0;
437 }
438 
439 bool LoopVectorizationLegality::isUniform(Value *V) {
440   return LAI->isUniform(V);
441 }
442 
443 bool LoopVectorizationLegality::canVectorizeOuterLoop() {
444   assert(!TheLoop->isInnermost() && "We are not vectorizing an outer loop.");
445   // Store the result and return it at the end instead of exiting early, in case
446   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
447   bool Result = true;
448   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
449 
450   for (BasicBlock *BB : TheLoop->blocks()) {
451     // Check whether the BB terminator is a BranchInst. Any other terminator is
452     // not supported yet.
453     auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
454     if (!Br) {
455       reportVectorizationFailure("Unsupported basic block terminator",
456           "loop control flow is not understood by vectorizer",
457           "CFGNotUnderstood", ORE, TheLoop);
458       if (DoExtraAnalysis)
459         Result = false;
460       else
461         return false;
462     }
463 
464     // Check whether the BranchInst is a supported one. Only unconditional
465     // branches, conditional branches with an outer loop invariant condition or
466     // backedges are supported.
467     // FIXME: We skip these checks when VPlan predication is enabled as we
468     // want to allow divergent branches. This whole check will be removed
469     // once VPlan predication is on by default.
470     if (!EnableVPlanPredication && Br && Br->isConditional() &&
471         !TheLoop->isLoopInvariant(Br->getCondition()) &&
472         !LI->isLoopHeader(Br->getSuccessor(0)) &&
473         !LI->isLoopHeader(Br->getSuccessor(1))) {
474       reportVectorizationFailure("Unsupported conditional branch",
475           "loop control flow is not understood by vectorizer",
476           "CFGNotUnderstood", ORE, TheLoop);
477       if (DoExtraAnalysis)
478         Result = false;
479       else
480         return false;
481     }
482   }
483 
484   // Check whether inner loops are uniform. At this point, we only support
485   // simple outer loops scenarios with uniform nested loops.
486   if (!isUniformLoopNest(TheLoop /*loop nest*/,
487                          TheLoop /*context outer loop*/)) {
488     reportVectorizationFailure("Outer loop contains divergent loops",
489         "loop control flow is not understood by vectorizer",
490         "CFGNotUnderstood", ORE, TheLoop);
491     if (DoExtraAnalysis)
492       Result = false;
493     else
494       return false;
495   }
496 
497   // Check whether we are able to set up outer loop induction.
498   if (!setupOuterLoopInductions()) {
499     reportVectorizationFailure("Unsupported outer loop Phi(s)",
500                                "Unsupported outer loop Phi(s)",
501                                "UnsupportedPhi", ORE, TheLoop);
502     if (DoExtraAnalysis)
503       Result = false;
504     else
505       return false;
506   }
507 
508   return Result;
509 }
510 
511 void LoopVectorizationLegality::addInductionPhi(
512     PHINode *Phi, const InductionDescriptor &ID,
513     SmallPtrSetImpl<Value *> &AllowedExit) {
514   Inductions[Phi] = ID;
515 
516   // In case this induction also comes with casts that we know we can ignore
517   // in the vectorized loop body, record them here. All casts could be recorded
518   // here for ignoring, but suffices to record only the first (as it is the
519   // only one that may bw used outside the cast sequence).
520   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
521   if (!Casts.empty())
522     InductionCastsToIgnore.insert(*Casts.begin());
523 
524   Type *PhiTy = Phi->getType();
525   const DataLayout &DL = Phi->getModule()->getDataLayout();
526 
527   // Get the widest type.
528   if (!PhiTy->isFloatingPointTy()) {
529     if (!WidestIndTy)
530       WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
531     else
532       WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
533   }
534 
535   // Int inductions are special because we only allow one IV.
536   if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
537       ID.getConstIntStepValue() && ID.getConstIntStepValue()->isOne() &&
538       isa<Constant>(ID.getStartValue()) &&
539       cast<Constant>(ID.getStartValue())->isNullValue()) {
540 
541     // Use the phi node with the widest type as induction. Use the last
542     // one if there are multiple (no good reason for doing this other
543     // than it is expedient). We've checked that it begins at zero and
544     // steps by one, so this is a canonical induction variable.
545     if (!PrimaryInduction || PhiTy == WidestIndTy)
546       PrimaryInduction = Phi;
547   }
548 
549   // Both the PHI node itself, and the "post-increment" value feeding
550   // back into the PHI node may have external users.
551   // We can allow those uses, except if the SCEVs we have for them rely
552   // on predicates that only hold within the loop, since allowing the exit
553   // currently means re-using this SCEV outside the loop (see PR33706 for more
554   // details).
555   if (PSE.getUnionPredicate().isAlwaysTrue()) {
556     AllowedExit.insert(Phi);
557     AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
558   }
559 
560   LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n");
561 }
562 
563 bool LoopVectorizationLegality::setupOuterLoopInductions() {
564   BasicBlock *Header = TheLoop->getHeader();
565 
566   // Returns true if a given Phi is a supported induction.
567   auto isSupportedPhi = [&](PHINode &Phi) -> bool {
568     InductionDescriptor ID;
569     if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) &&
570         ID.getKind() == InductionDescriptor::IK_IntInduction) {
571       addInductionPhi(&Phi, ID, AllowedExit);
572       return true;
573     } else {
574       // Bail out for any Phi in the outer loop header that is not a supported
575       // induction.
576       LLVM_DEBUG(
577           dbgs()
578           << "LV: Found unsupported PHI for outer loop vectorization.\n");
579       return false;
580     }
581   };
582 
583   if (llvm::all_of(Header->phis(), isSupportedPhi))
584     return true;
585   else
586     return false;
587 }
588 
589 /// Checks if a function is scalarizable according to the TLI, in
590 /// the sense that it should be vectorized and then expanded in
591 /// multiple scalar calls. This is represented in the
592 /// TLI via mappings that do not specify a vector name, as in the
593 /// following example:
594 ///
595 ///    const VecDesc VecIntrinsics[] = {
596 ///      {"llvm.phx.abs.i32", "", 4}
597 ///    };
598 static bool isTLIScalarize(const TargetLibraryInfo &TLI, const CallInst &CI) {
599   const StringRef ScalarName = CI.getCalledFunction()->getName();
600   bool Scalarize = TLI.isFunctionVectorizable(ScalarName);
601   // Check that all known VFs are not associated to a vector
602   // function, i.e. the vector name is emty.
603   if (Scalarize) {
604     ElementCount WidestFixedVF, WidestScalableVF;
605     TLI.getWidestVF(ScalarName, WidestFixedVF, WidestScalableVF);
606     for (ElementCount VF = ElementCount::getFixed(2);
607          ElementCount::isKnownLE(VF, WidestFixedVF); VF *= 2)
608       Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
609     for (ElementCount VF = ElementCount::getScalable(1);
610          ElementCount::isKnownLE(VF, WidestScalableVF); VF *= 2)
611       Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF);
612     assert((WidestScalableVF.isZero() || !Scalarize) &&
613            "Caller may decide to scalarize a variant using a scalable VF");
614   }
615   return Scalarize;
616 }
617 
618 bool LoopVectorizationLegality::canVectorizeInstrs() {
619   BasicBlock *Header = TheLoop->getHeader();
620 
621   // For each block in the loop.
622   for (BasicBlock *BB : TheLoop->blocks()) {
623     // Scan the instructions in the block and look for hazards.
624     for (Instruction &I : *BB) {
625       if (auto *Phi = dyn_cast<PHINode>(&I)) {
626         Type *PhiTy = Phi->getType();
627         // Check that this PHI type is allowed.
628         if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
629             !PhiTy->isPointerTy()) {
630           reportVectorizationFailure("Found a non-int non-pointer PHI",
631                                      "loop control flow is not understood by vectorizer",
632                                      "CFGNotUnderstood", ORE, TheLoop);
633           return false;
634         }
635 
636         // If this PHINode is not in the header block, then we know that we
637         // can convert it to select during if-conversion. No need to check if
638         // the PHIs in this block are induction or reduction variables.
639         if (BB != Header) {
640           // Non-header phi nodes that have outside uses can be vectorized. Add
641           // them to the list of allowed exits.
642           // Unsafe cyclic dependencies with header phis are identified during
643           // legalization for reduction, induction and first order
644           // recurrences.
645           AllowedExit.insert(&I);
646           continue;
647         }
648 
649         // We only allow if-converted PHIs with exactly two incoming values.
650         if (Phi->getNumIncomingValues() != 2) {
651           reportVectorizationFailure("Found an invalid PHI",
652               "loop control flow is not understood by vectorizer",
653               "CFGNotUnderstood", ORE, TheLoop, Phi);
654           return false;
655         }
656 
657         RecurrenceDescriptor RedDes;
658         if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC,
659                                                  DT)) {
660           Requirements->addExactFPMathInst(RedDes.getExactFPMathInst());
661           AllowedExit.insert(RedDes.getLoopExitInstr());
662           Reductions[Phi] = RedDes;
663           continue;
664         }
665 
666         // TODO: Instead of recording the AllowedExit, it would be good to record the
667         // complementary set: NotAllowedExit. These include (but may not be
668         // limited to):
669         // 1. Reduction phis as they represent the one-before-last value, which
670         // is not available when vectorized
671         // 2. Induction phis and increment when SCEV predicates cannot be used
672         // outside the loop - see addInductionPhi
673         // 3. Non-Phis with outside uses when SCEV predicates cannot be used
674         // outside the loop - see call to hasOutsideLoopUser in the non-phi
675         // handling below
676         // 4. FirstOrderRecurrence phis that can possibly be handled by
677         // extraction.
678         // By recording these, we can then reason about ways to vectorize each
679         // of these NotAllowedExit.
680         InductionDescriptor ID;
681         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
682           addInductionPhi(Phi, ID, AllowedExit);
683           Requirements->addExactFPMathInst(ID.getExactFPMathInst());
684           continue;
685         }
686 
687         if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop,
688                                                          SinkAfter, DT)) {
689           AllowedExit.insert(Phi);
690           FirstOrderRecurrences.insert(Phi);
691           continue;
692         }
693 
694         // As a last resort, coerce the PHI to a AddRec expression
695         // and re-try classifying it a an induction PHI.
696         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
697           addInductionPhi(Phi, ID, AllowedExit);
698           continue;
699         }
700 
701         reportVectorizationFailure("Found an unidentified PHI",
702             "value that could not be identified as "
703             "reduction is used outside the loop",
704             "NonReductionValueUsedOutsideLoop", ORE, TheLoop, Phi);
705         return false;
706       } // end of PHI handling
707 
708       // We handle calls that:
709       //   * Are debug info intrinsics.
710       //   * Have a mapping to an IR intrinsic.
711       //   * Have a vector version available.
712       auto *CI = dyn_cast<CallInst>(&I);
713 
714       if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
715           !isa<DbgInfoIntrinsic>(CI) &&
716           !(CI->getCalledFunction() && TLI &&
717             (!VFDatabase::getMappings(*CI).empty() ||
718              isTLIScalarize(*TLI, *CI)))) {
719         // If the call is a recognized math libary call, it is likely that
720         // we can vectorize it given loosened floating-point constraints.
721         LibFunc Func;
722         bool IsMathLibCall =
723             TLI && CI->getCalledFunction() &&
724             CI->getType()->isFloatingPointTy() &&
725             TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
726             TLI->hasOptimizedCodeGen(Func);
727 
728         if (IsMathLibCall) {
729           // TODO: Ideally, we should not use clang-specific language here,
730           // but it's hard to provide meaningful yet generic advice.
731           // Also, should this be guarded by allowExtraAnalysis() and/or be part
732           // of the returned info from isFunctionVectorizable()?
733           reportVectorizationFailure(
734               "Found a non-intrinsic callsite",
735               "library call cannot be vectorized. "
736               "Try compiling with -fno-math-errno, -ffast-math, "
737               "or similar flags",
738               "CantVectorizeLibcall", ORE, TheLoop, CI);
739         } else {
740           reportVectorizationFailure("Found a non-intrinsic callsite",
741                                      "call instruction cannot be vectorized",
742                                      "CantVectorizeLibcall", ORE, TheLoop, CI);
743         }
744         return false;
745       }
746 
747       // Some intrinsics have scalar arguments and should be same in order for
748       // them to be vectorized (i.e. loop invariant).
749       if (CI) {
750         auto *SE = PSE.getSE();
751         Intrinsic::ID IntrinID = getVectorIntrinsicIDForCall(CI, TLI);
752         for (unsigned i = 0, e = CI->arg_size(); i != e; ++i)
753           if (hasVectorInstrinsicScalarOpd(IntrinID, i)) {
754             if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(i)), TheLoop)) {
755               reportVectorizationFailure("Found unvectorizable intrinsic",
756                   "intrinsic instruction cannot be vectorized",
757                   "CantVectorizeIntrinsic", ORE, TheLoop, CI);
758               return false;
759             }
760           }
761       }
762 
763       // Check that the instruction return type is vectorizable.
764       // Also, we can't vectorize extractelement instructions.
765       if ((!VectorType::isValidElementType(I.getType()) &&
766            !I.getType()->isVoidTy()) ||
767           isa<ExtractElementInst>(I)) {
768         reportVectorizationFailure("Found unvectorizable type",
769             "instruction return type cannot be vectorized",
770             "CantVectorizeInstructionReturnType", ORE, TheLoop, &I);
771         return false;
772       }
773 
774       // Check that the stored type is vectorizable.
775       if (auto *ST = dyn_cast<StoreInst>(&I)) {
776         Type *T = ST->getValueOperand()->getType();
777         if (!VectorType::isValidElementType(T)) {
778           reportVectorizationFailure("Store instruction cannot be vectorized",
779                                      "store instruction cannot be vectorized",
780                                      "CantVectorizeStore", ORE, TheLoop, ST);
781           return false;
782         }
783 
784         // For nontemporal stores, check that a nontemporal vector version is
785         // supported on the target.
786         if (ST->getMetadata(LLVMContext::MD_nontemporal)) {
787           // Arbitrarily try a vector of 2 elements.
788           auto *VecTy = FixedVectorType::get(T, /*NumElts=*/2);
789           assert(VecTy && "did not find vectorized version of stored type");
790           if (!TTI->isLegalNTStore(VecTy, ST->getAlign())) {
791             reportVectorizationFailure(
792                 "nontemporal store instruction cannot be vectorized",
793                 "nontemporal store instruction cannot be vectorized",
794                 "CantVectorizeNontemporalStore", ORE, TheLoop, ST);
795             return false;
796           }
797         }
798 
799       } else if (auto *LD = dyn_cast<LoadInst>(&I)) {
800         if (LD->getMetadata(LLVMContext::MD_nontemporal)) {
801           // For nontemporal loads, check that a nontemporal vector version is
802           // supported on the target (arbitrarily try a vector of 2 elements).
803           auto *VecTy = FixedVectorType::get(I.getType(), /*NumElts=*/2);
804           assert(VecTy && "did not find vectorized version of load type");
805           if (!TTI->isLegalNTLoad(VecTy, LD->getAlign())) {
806             reportVectorizationFailure(
807                 "nontemporal load instruction cannot be vectorized",
808                 "nontemporal load instruction cannot be vectorized",
809                 "CantVectorizeNontemporalLoad", ORE, TheLoop, LD);
810             return false;
811           }
812         }
813 
814         // FP instructions can allow unsafe algebra, thus vectorizable by
815         // non-IEEE-754 compliant SIMD units.
816         // This applies to floating-point math operations and calls, not memory
817         // operations, shuffles, or casts, as they don't change precision or
818         // semantics.
819       } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
820                  !I.isFast()) {
821         LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
822         Hints->setPotentiallyUnsafe();
823       }
824 
825       // Reduction instructions are allowed to have exit users.
826       // All other instructions must not have external users.
827       if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
828         // We can safely vectorize loops where instructions within the loop are
829         // used outside the loop only if the SCEV predicates within the loop is
830         // same as outside the loop. Allowing the exit means reusing the SCEV
831         // outside the loop.
832         if (PSE.getUnionPredicate().isAlwaysTrue()) {
833           AllowedExit.insert(&I);
834           continue;
835         }
836         reportVectorizationFailure("Value cannot be used outside the loop",
837                                    "value cannot be used outside the loop",
838                                    "ValueUsedOutsideLoop", ORE, TheLoop, &I);
839         return false;
840       }
841     } // next instr.
842   }
843 
844   if (!PrimaryInduction) {
845     if (Inductions.empty()) {
846       reportVectorizationFailure("Did not find one integer induction var",
847           "loop induction variable could not be identified",
848           "NoInductionVariable", ORE, TheLoop);
849       return false;
850     } else if (!WidestIndTy) {
851       reportVectorizationFailure("Did not find one integer induction var",
852           "integer loop induction variable could not be identified",
853           "NoIntegerInductionVariable", ORE, TheLoop);
854       return false;
855     } else {
856       LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
857     }
858   }
859 
860   // For first order recurrences, we use the previous value (incoming value from
861   // the latch) to check if it dominates all users of the recurrence. Bail out
862   // if we have to sink such an instruction for another recurrence, as the
863   // dominance requirement may not hold after sinking.
864   BasicBlock *LoopLatch = TheLoop->getLoopLatch();
865   if (any_of(FirstOrderRecurrences, [LoopLatch, this](const PHINode *Phi) {
866         Instruction *V =
867             cast<Instruction>(Phi->getIncomingValueForBlock(LoopLatch));
868         return SinkAfter.find(V) != SinkAfter.end();
869       }))
870     return false;
871 
872   // Now we know the widest induction type, check if our found induction
873   // is the same size. If it's not, unset it here and InnerLoopVectorizer
874   // will create another.
875   if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
876     PrimaryInduction = nullptr;
877 
878   return true;
879 }
880 
881 bool LoopVectorizationLegality::canVectorizeMemory() {
882   LAI = &(*GetLAA)(*TheLoop);
883   const OptimizationRemarkAnalysis *LAR = LAI->getReport();
884   if (LAR) {
885     ORE->emit([&]() {
886       return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(),
887                                         "loop not vectorized: ", *LAR);
888     });
889   }
890 
891   if (!LAI->canVectorizeMemory())
892     return false;
893 
894   if (LAI->hasDependenceInvolvingLoopInvariantAddress()) {
895     reportVectorizationFailure("Stores to a uniform address",
896         "write to a loop invariant address could not be vectorized",
897         "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop);
898     return false;
899   }
900 
901   Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
902   PSE.addPredicate(LAI->getPSE().getUnionPredicate());
903   return true;
904 }
905 
906 bool LoopVectorizationLegality::canVectorizeFPMath(
907     bool EnableStrictReductions) {
908 
909   // First check if there is any ExactFP math or if we allow reassociations
910   if (!Requirements->getExactFPInst() || Hints->allowReordering())
911     return true;
912 
913   // If the above is false, we have ExactFPMath & do not allow reordering.
914   // If the EnableStrictReductions flag is set, first check if we have any
915   // Exact FP induction vars, which we cannot vectorize.
916   if (!EnableStrictReductions ||
917       any_of(getInductionVars(), [&](auto &Induction) -> bool {
918         InductionDescriptor IndDesc = Induction.second;
919         return IndDesc.getExactFPMathInst();
920       }))
921     return false;
922 
923   // We can now only vectorize if all reductions with Exact FP math also
924   // have the isOrdered flag set, which indicates that we can move the
925   // reduction operations in-loop.
926   return (all_of(getReductionVars(), [&](auto &Reduction) -> bool {
927     const RecurrenceDescriptor &RdxDesc = Reduction.second;
928     return !RdxDesc.hasExactFPMath() || RdxDesc.isOrdered();
929   }));
930 }
931 
932 bool LoopVectorizationLegality::isInductionPhi(const Value *V) {
933   Value *In0 = const_cast<Value *>(V);
934   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
935   if (!PN)
936     return false;
937 
938   return Inductions.count(PN);
939 }
940 
941 bool LoopVectorizationLegality::isCastedInductionVariable(const Value *V) {
942   auto *Inst = dyn_cast<Instruction>(V);
943   return (Inst && InductionCastsToIgnore.count(Inst));
944 }
945 
946 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
947   return isInductionPhi(V) || isCastedInductionVariable(V);
948 }
949 
950 bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) {
951   return FirstOrderRecurrences.count(Phi);
952 }
953 
954 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) const {
955   return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
956 }
957 
958 bool LoopVectorizationLegality::blockCanBePredicated(
959     BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs,
960     SmallPtrSetImpl<const Instruction *> &MaskedOp,
961     SmallPtrSetImpl<Instruction *> &ConditionalAssumes) const {
962   for (Instruction &I : *BB) {
963     // Check that we don't have a constant expression that can trap as operand.
964     for (Value *Operand : I.operands()) {
965       if (auto *C = dyn_cast<Constant>(Operand))
966         if (C->canTrap())
967           return false;
968     }
969 
970     // We can predicate blocks with calls to assume, as long as we drop them in
971     // case we flatten the CFG via predication.
972     if (match(&I, m_Intrinsic<Intrinsic::assume>())) {
973       ConditionalAssumes.insert(&I);
974       continue;
975     }
976 
977     // Do not let llvm.experimental.noalias.scope.decl block the vectorization.
978     // TODO: there might be cases that it should block the vectorization. Let's
979     // ignore those for now.
980     if (isa<NoAliasScopeDeclInst>(&I))
981       continue;
982 
983     // We might be able to hoist the load.
984     if (I.mayReadFromMemory()) {
985       auto *LI = dyn_cast<LoadInst>(&I);
986       if (!LI)
987         return false;
988       if (!SafePtrs.count(LI->getPointerOperand())) {
989         MaskedOp.insert(LI);
990         continue;
991       }
992     }
993 
994     if (I.mayWriteToMemory()) {
995       auto *SI = dyn_cast<StoreInst>(&I);
996       if (!SI)
997         return false;
998       // Predicated store requires some form of masking:
999       // 1) masked store HW instruction,
1000       // 2) emulation via load-blend-store (only if safe and legal to do so,
1001       //    be aware on the race conditions), or
1002       // 3) element-by-element predicate check and scalar store.
1003       MaskedOp.insert(SI);
1004       continue;
1005     }
1006     if (I.mayThrow())
1007       return false;
1008   }
1009 
1010   return true;
1011 }
1012 
1013 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1014   if (!EnableIfConversion) {
1015     reportVectorizationFailure("If-conversion is disabled",
1016                                "if-conversion is disabled",
1017                                "IfConversionDisabled",
1018                                ORE, TheLoop);
1019     return false;
1020   }
1021 
1022   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1023 
1024   // A list of pointers which are known to be dereferenceable within scope of
1025   // the loop body for each iteration of the loop which executes.  That is,
1026   // the memory pointed to can be dereferenced (with the access size implied by
1027   // the value's type) unconditionally within the loop header without
1028   // introducing a new fault.
1029   SmallPtrSet<Value *, 8> SafePointers;
1030 
1031   // Collect safe addresses.
1032   for (BasicBlock *BB : TheLoop->blocks()) {
1033     if (!blockNeedsPredication(BB)) {
1034       for (Instruction &I : *BB)
1035         if (auto *Ptr = getLoadStorePointerOperand(&I))
1036           SafePointers.insert(Ptr);
1037       continue;
1038     }
1039 
1040     // For a block which requires predication, a address may be safe to access
1041     // in the loop w/o predication if we can prove dereferenceability facts
1042     // sufficient to ensure it'll never fault within the loop. For the moment,
1043     // we restrict this to loads; stores are more complicated due to
1044     // concurrency restrictions.
1045     ScalarEvolution &SE = *PSE.getSE();
1046     for (Instruction &I : *BB) {
1047       LoadInst *LI = dyn_cast<LoadInst>(&I);
1048       if (LI && !LI->getType()->isVectorTy() && !mustSuppressSpeculation(*LI) &&
1049           isDereferenceableAndAlignedInLoop(LI, TheLoop, SE, *DT))
1050         SafePointers.insert(LI->getPointerOperand());
1051     }
1052   }
1053 
1054   // Collect the blocks that need predication.
1055   BasicBlock *Header = TheLoop->getHeader();
1056   for (BasicBlock *BB : TheLoop->blocks()) {
1057     // We don't support switch statements inside loops.
1058     if (!isa<BranchInst>(BB->getTerminator())) {
1059       reportVectorizationFailure("Loop contains a switch statement",
1060                                  "loop contains a switch statement",
1061                                  "LoopContainsSwitch", ORE, TheLoop,
1062                                  BB->getTerminator());
1063       return false;
1064     }
1065 
1066     // We must be able to predicate all blocks that need to be predicated.
1067     if (blockNeedsPredication(BB)) {
1068       if (!blockCanBePredicated(BB, SafePointers, MaskedOp,
1069                                 ConditionalAssumes)) {
1070         reportVectorizationFailure(
1071             "Control flow cannot be substituted for a select",
1072             "control flow cannot be substituted for a select",
1073             "NoCFGForSelect", ORE, TheLoop,
1074             BB->getTerminator());
1075         return false;
1076       }
1077     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
1078       reportVectorizationFailure(
1079           "Control flow cannot be substituted for a select",
1080           "control flow cannot be substituted for a select",
1081           "NoCFGForSelect", ORE, TheLoop,
1082           BB->getTerminator());
1083       return false;
1084     }
1085   }
1086 
1087   // We can if-convert this loop.
1088   return true;
1089 }
1090 
1091 // Helper function to canVectorizeLoopNestCFG.
1092 bool LoopVectorizationLegality::canVectorizeLoopCFG(Loop *Lp,
1093                                                     bool UseVPlanNativePath) {
1094   assert((UseVPlanNativePath || Lp->isInnermost()) &&
1095          "VPlan-native path is not enabled.");
1096 
1097   // TODO: ORE should be improved to show more accurate information when an
1098   // outer loop can't be vectorized because a nested loop is not understood or
1099   // legal. Something like: "outer_loop_location: loop not vectorized:
1100   // (inner_loop_location) loop control flow is not understood by vectorizer".
1101 
1102   // Store the result and return it at the end instead of exiting early, in case
1103   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1104   bool Result = true;
1105   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1106 
1107   // We must have a loop in canonical form. Loops with indirectbr in them cannot
1108   // be canonicalized.
1109   if (!Lp->getLoopPreheader()) {
1110     reportVectorizationFailure("Loop doesn't have a legal pre-header",
1111         "loop control flow is not understood by vectorizer",
1112         "CFGNotUnderstood", ORE, TheLoop);
1113     if (DoExtraAnalysis)
1114       Result = false;
1115     else
1116       return false;
1117   }
1118 
1119   // We must have a single backedge.
1120   if (Lp->getNumBackEdges() != 1) {
1121     reportVectorizationFailure("The loop must have a single backedge",
1122         "loop control flow is not understood by vectorizer",
1123         "CFGNotUnderstood", ORE, TheLoop);
1124     if (DoExtraAnalysis)
1125       Result = false;
1126     else
1127       return false;
1128   }
1129 
1130   return Result;
1131 }
1132 
1133 bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
1134     Loop *Lp, bool UseVPlanNativePath) {
1135   // Store the result and return it at the end instead of exiting early, in case
1136   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1137   bool Result = true;
1138   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1139   if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
1140     if (DoExtraAnalysis)
1141       Result = false;
1142     else
1143       return false;
1144   }
1145 
1146   // Recursively check whether the loop control flow of nested loops is
1147   // understood.
1148   for (Loop *SubLp : *Lp)
1149     if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
1150       if (DoExtraAnalysis)
1151         Result = false;
1152       else
1153         return false;
1154     }
1155 
1156   return Result;
1157 }
1158 
1159 bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
1160   // Store the result and return it at the end instead of exiting early, in case
1161   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
1162   bool Result = true;
1163 
1164   bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1165   // Check whether the loop-related control flow in the loop nest is expected by
1166   // vectorizer.
1167   if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
1168     if (DoExtraAnalysis)
1169       Result = false;
1170     else
1171       return false;
1172   }
1173 
1174   // We need to have a loop header.
1175   LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
1176                     << '\n');
1177 
1178   // Specific checks for outer loops. We skip the remaining legal checks at this
1179   // point because they don't support outer loops.
1180   if (!TheLoop->isInnermost()) {
1181     assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
1182 
1183     if (!canVectorizeOuterLoop()) {
1184       reportVectorizationFailure("Unsupported outer loop",
1185                                  "unsupported outer loop",
1186                                  "UnsupportedOuterLoop",
1187                                  ORE, TheLoop);
1188       // TODO: Implement DoExtraAnalysis when subsequent legal checks support
1189       // outer loops.
1190       return false;
1191     }
1192 
1193     LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
1194     return Result;
1195   }
1196 
1197   assert(TheLoop->isInnermost() && "Inner loop expected.");
1198   // Check if we can if-convert non-single-bb loops.
1199   unsigned NumBlocks = TheLoop->getNumBlocks();
1200   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1201     LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1202     if (DoExtraAnalysis)
1203       Result = false;
1204     else
1205       return false;
1206   }
1207 
1208   // Check if we can vectorize the instructions and CFG in this loop.
1209   if (!canVectorizeInstrs()) {
1210     LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1211     if (DoExtraAnalysis)
1212       Result = false;
1213     else
1214       return false;
1215   }
1216 
1217   // Go over each instruction and look at memory deps.
1218   if (!canVectorizeMemory()) {
1219     LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1220     if (DoExtraAnalysis)
1221       Result = false;
1222     else
1223       return false;
1224   }
1225 
1226   LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop"
1227                     << (LAI->getRuntimePointerChecking()->Need
1228                             ? " (with a runtime bound check)"
1229                             : "")
1230                     << "!\n");
1231 
1232   unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
1233   if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
1234     SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
1235 
1236   if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
1237     reportVectorizationFailure("Too many SCEV checks needed",
1238         "Too many SCEV assumptions need to be made and checked at runtime",
1239         "TooManySCEVRunTimeChecks", ORE, TheLoop);
1240     if (DoExtraAnalysis)
1241       Result = false;
1242     else
1243       return false;
1244   }
1245 
1246   // Okay! We've done all the tests. If any have failed, return false. Otherwise
1247   // we can vectorize, and at this point we don't have any other mem analysis
1248   // which may limit our maximum vectorization factor, so just return true with
1249   // no restrictions.
1250   return Result;
1251 }
1252 
1253 bool LoopVectorizationLegality::prepareToFoldTailByMasking() {
1254 
1255   LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
1256 
1257   SmallPtrSet<const Value *, 8> ReductionLiveOuts;
1258 
1259   for (auto &Reduction : getReductionVars())
1260     ReductionLiveOuts.insert(Reduction.second.getLoopExitInstr());
1261 
1262   // TODO: handle non-reduction outside users when tail is folded by masking.
1263   for (auto *AE : AllowedExit) {
1264     // Check that all users of allowed exit values are inside the loop or
1265     // are the live-out of a reduction.
1266     if (ReductionLiveOuts.count(AE))
1267       continue;
1268     for (User *U : AE->users()) {
1269       Instruction *UI = cast<Instruction>(U);
1270       if (TheLoop->contains(UI))
1271         continue;
1272       LLVM_DEBUG(
1273           dbgs()
1274           << "LV: Cannot fold tail by masking, loop has an outside user for "
1275           << *UI << "\n");
1276       return false;
1277     }
1278   }
1279 
1280   // The list of pointers that we can safely read and write to remains empty.
1281   SmallPtrSet<Value *, 8> SafePointers;
1282 
1283   SmallPtrSet<const Instruction *, 8> TmpMaskedOp;
1284   SmallPtrSet<Instruction *, 8> TmpConditionalAssumes;
1285 
1286   // Check and mark all blocks for predication, including those that ordinarily
1287   // do not need predication such as the header block.
1288   for (BasicBlock *BB : TheLoop->blocks()) {
1289     if (!blockCanBePredicated(BB, SafePointers, TmpMaskedOp,
1290                               TmpConditionalAssumes)) {
1291       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking as requested.\n");
1292       return false;
1293     }
1294   }
1295 
1296   LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
1297 
1298   MaskedOp.insert(TmpMaskedOp.begin(), TmpMaskedOp.end());
1299   ConditionalAssumes.insert(TmpConditionalAssumes.begin(),
1300                             TmpConditionalAssumes.end());
1301 
1302   return true;
1303 }
1304 
1305 } // namespace llvm
1306