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