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