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