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