https://github.com/chichunchen updated https://github.com/llvm/llvm-project/pull/233493
>From c894ab75c20b32b057504a5b8df3ca15a2b3e5a9 Mon Sep 17 00:00:00 2001 From: "Chi Chun, Chen" <[email protected]> Date: Fri, 13 Nov 2026 13:48:45 -0600 Subject: [PATCH 01/11] [OpenMP] Compare ISA names when a selector requires more traits isStrictSubset compared ISA names only when both selectors required the same number of traits. When the second selector required more, the first was a strict subset even if the second didn't require its ISA names, so with ``` #pragma omp metadirective when(device = {isa("sse")} : parallel) \ when(device = {isa("sse2")}, user = {condition(1)} : single) ``` both WHEN clauses score the same and SINGLE was selected, although neither selector is a subset of the other and the first one should win. Compare the ISA names before checking whether the count is strict. Co-authored-by: Copilot <[email protected]> --- .../metadirective_device_isa_codegen.cpp | 12 ++++++++ llvm/lib/Frontend/OpenMP/OMPContext.cpp | 13 +++++---- llvm/unittests/Frontend/OpenMPContextTest.cpp | 28 +++++++++++++++++++ 3 files changed, 48 insertions(+), 5 deletions(-) diff --git a/clang/test/OpenMP/metadirective_device_isa_codegen.cpp b/clang/test/OpenMP/metadirective_device_isa_codegen.cpp index 1d098063101d7..7f19bb7fa87ce 100644 --- a/clang/test/OpenMP/metadirective_device_isa_codegen.cpp +++ b/clang/test/OpenMP/metadirective_device_isa_codegen.cpp @@ -29,4 +29,16 @@ void x86_64_device_isa_not_selected() { // CHECK: @_Z3barv // CHECK: call void @__kmpc_end_single // CHECK: ret void + +// Both WHEN clauses score the same. The second requires more traits, but not +// the "sse" ISA name, so the first one is not a strict subset and wins. +void x86_64_device_isa_names_differ() { +#pragma omp metadirective when(device = {isa("sse")} : parallel) \ + when(device = {isa("sse2")}, user = {condition(1)} : single) + bar(); +} +// CHECK-LABEL: void @_Z30x86_64_device_isa_names_differv() +// CHECK-NOT: __kmpc_single +// CHECK: ...) @__kmpc_fork_call{{.*}}@_Z30x86_64_device_isa_names_differv.omp_outlined +// CHECK: ret void #endif diff --git a/llvm/lib/Frontend/OpenMP/OMPContext.cpp b/llvm/lib/Frontend/OpenMP/OMPContext.cpp index 9ea59a6803625..87392f752493d 100644 --- a/llvm/lib/Frontend/OpenMP/OMPContext.cpp +++ b/llvm/lib/Frontend/OpenMP/OMPContext.cpp @@ -170,6 +170,12 @@ static bool isStrictSubset(const VariantMatchInfo &VMI0, for (unsigned Bit : VMI0.RequiredTraits.set_bits()) if (!VMI1.RequiredTraits.test(Bit)) return false; + // Different ISA names share a trait, so compare them as well. + if (!llvm::all_of(VMI0.ISATraits, + [&](const VariantMatchInfo::ISATrait &Trait) { + return llvm::is_contained(VMI1.ISATraits, Trait); + })) + return false; if (!isOrderedSubset<TraitProperty>(VMI0.ConstructTraits, VMI1.ConstructTraits)) return false; @@ -178,16 +184,13 @@ static bool isStrictSubset(const VariantMatchInfo &VMI0, // With the same traits, only a repeated construct makes VMI0 strict. if (VMI0.ConstructTraits.size() == VMI1.ConstructTraits.size()) return false; - // Different conditions or ISA names share a trait, so they can't be compared. + // Different conditions share a trait, so they can't be compared. for (TraitProperty Property : {TraitProperty::user_condition_true, TraitProperty::user_condition_false, TraitProperty::user_condition_unknown}) if (VMI0.RequiredTraits.test(unsigned(Property))) return false; - return llvm::all_of(VMI0.ISATraits, - [&](const VariantMatchInfo::ISATrait &Trait) { - return llvm::is_contained(VMI1.ISATraits, Trait); - }); + return true; } static int diff --git a/llvm/unittests/Frontend/OpenMPContextTest.cpp b/llvm/unittests/Frontend/OpenMPContextTest.cpp index 833f627fd9a6c..4372f8bde5219 100644 --- a/llvm/unittests/Frontend/OpenMPContextTest.cpp +++ b/llvm/unittests/Frontend/OpenMPContextTest.cpp @@ -803,4 +803,32 @@ TEST_F(OpenMPContextTest, StrictSubsetsOfAlternatingTiedSupersets) { EXPECT_EQ(Best({Host, CPU, Host, HostSuperset}), 1); } +TEST_F(OpenMPContextTest, ISANamesInStrictSubset) { + struct ISAContext : OMPContext { + using OMPContext::OMPContext; + bool matchesISATrait(StringRef) const override { return true; } + } Context(false, Triple("x86_64-unknown-linux"), Triple(), -1); + APInt Three(64, 3), Four(64, 4); + VariantMatchInfo SSE, AVX; + SSE.addTrait(TraitProperty::device_isa___ANY, "sse"); + SSE.addTrait(TraitProperty::implementation_vendor_llvm, "", &Four); + AVX.addTrait(TraitProperty::device_isa___ANY, "avx"); + AVX.addTrait(TraitProperty::implementation_vendor_llvm, "", &Three); + AVX.addTrait(TraitProperty::device_kind_host, ""); + auto Best = [&](const VariantMatchInfo &First, + const VariantMatchInfo &Second) { + return getBestVariantMatchForContext( + SmallVector<VariantMatchInfo, 2>{First, Second}, Context); + }; + + // Both score 9. AVX requires more traits, but not the `sse` ISA name. + EXPECT_EQ(Best(SSE, AVX), 0); + EXPECT_EQ(Best(AVX, SSE), 0); + + // With all of SSE's ISA names, AVX is a strict superset. + AVX.addTrait(TraitProperty::device_isa___ANY, "sse"); + EXPECT_EQ(Best(SSE, AVX), 1); + EXPECT_EQ(Best(AVX, SSE), 0); +} + } // namespace >From 7c92b1fd04ecc1ec8c21375360a94f13c1f7ca83 Mon Sep 17 00:00:00 2001 From: "Chi Chun, Chen" <[email protected]> Date: Sat, 17 Oct 2026 22:32:07 -0500 Subject: [PATCH 02/11] [flang][OpenMP] Don't treat different runtime conditions as subsets When two METADIRECTIVE candidates have the same score and one selector is a strict subset of the other, the superset wins. Flang ranks every runtime condition with the same property, so isStrictSubset saw different conditions as the same: !$omp metadirective & !$omp& when(user={condition(a)}, & !$omp& implementation={vendor(score(4): llvm)}: taskyield) & !$omp& when(user={condition(b)}, device={kind(host)}, & !$omp& implementation={vendor(score(3): llvm)}: taskwait) Both candidates score 5, and `b` was tested first, so TASKWAIT ran when both conditions were true. Neither selector is a subset of the other, so clause order should decide. This patch adds a UserCondition key to VariantMatchInfo, and isStrictSubset requires equal keys when the first selector has a condition. Flang gives each distinct runtime condition of a METADIRECTIVE its own key. It compares the conditions the same way as the existing check for repeated conditions, so condition(a) and condition((a)) still form a strict subset. Like that check, it treats different names for the same entity as different conditions. Ranking also sees conditions with function calls, which that check rejects, so the comparison now also collects the symbols in the length of a character array constructor. Conditions that fold to a constant of any kind, including all of Clang's, leave the key empty and are still compared by truth value. A constant condition and a runtime condition are now different. Fixes #233038. Assisted-by: GitHub Copilot (Claude Opus 5.5) --- flang/lib/Semantics/openmp-utils.cpp | 44 +++- .../test/Lower/OpenMP/metadirective-user.f90 | 224 ++++++++++++++++++ .../include/llvm/Frontend/OpenMP/OMPContext.h | 4 + llvm/lib/Frontend/OpenMP/OMPContext.cpp | 7 + llvm/unittests/Frontend/OpenMPContextTest.cpp | 37 +++ 5 files changed, 313 insertions(+), 3 deletions(-) diff --git a/flang/lib/Semantics/openmp-utils.cpp b/flang/lib/Semantics/openmp-utils.cpp index cde42c9238763..7f7a027c307a4 100644 --- a/flang/lib/Semantics/openmp-utils.cpp +++ b/flang/lib/Semantics/openmp-utils.cpp @@ -2493,6 +2493,12 @@ static void AppendConstructTraitsForDirective( add(llvm::omp::TraitProperty::construct_dispatch_dispatch); } +static SomeExpr NormalizeMetadirectiveCondition(const SomeExpr &expr); +namespace { +template <typename T> +bool AreSameMetadirectiveCondition(const T &left, const T &right); +} // namespace + static void AddTraitPropertiesFromSelector(llvm::omp::TraitSet set, const parser::OmpTraitSelector &selector, llvm::omp::VariantMatchInfo &vmi, SemanticsContext &semaCtx, @@ -2616,6 +2622,24 @@ std::optional<MetadirectiveCandidateSet> BuildMetadirectiveCandidateSet( : std::make_pair(nullptr, false); }; + // Identify each distinct runtime condition, so that different conditions + // are not strict subsets of each other. + llvm::SmallVector<SomeExpr, 4> runtimeConditions; + auto getConditionKey = [&](const DynamicUserCondition &condition) { + const SomeExpr *expr{GetExpr(context, *condition.expr)}; + if (!expr || + evaluate::IsActuallyConstant( + evaluate::Fold(context.foldingContext(), common::Clone(*expr)))) + return std::string{}; + SomeExpr normalized{NormalizeMetadirectiveCondition(*expr)}; + auto *it{llvm::find_if(runtimeConditions, [&](const SomeExpr &condition) { + return AreSameMetadirectiveCondition(condition, normalized); + })}; + if (it == runtimeConditions.end()) + it = &runtimeConditions.emplace_back(std::move(normalized)); + return std::to_string(it - runtimeConditions.begin() + 1); + }; + for (const parser::OmpClause &clause : clauses.v) { if (clause.Id() == llvm::omp::Clause::OMPC_when) { const auto *ctxSel{GetContextSelector(clause)}; @@ -2629,6 +2653,8 @@ std::optional<MetadirectiveCandidateSet> BuildMetadirectiveCandidateSet( llvm::omp::VariantMatchInfo rawVMI; std::optional<DynamicUserCondition> dynamicCondition{ MakeVariantMatchInfo(rawVMI, *ctxSel, context)}; + if (dynamicCondition) + rawVMI.UserCondition = getConditionKey(*dynamicCondition); if (llvm::any_of( rawVMI.ConstructTraits, [](llvm::omp::TraitProperty property) { return llvm::omp::getOpenMPContextTraitSetForProperty( @@ -2787,6 +2813,13 @@ struct ConditionSymbols : evaluate::Traverse<ConditionSymbols, bool, false> { symbols.push_back(&symbol); return true; } + // Expr equality compares the length, but Traverse doesn't visit it. + bool operator()(const evaluate::ArrayConstructor< + evaluate::Type<common::TypeCategory::Character>> &x) const { + if (const auto *len{x.LEN()}) + (*this)(*len); + return Base::operator()(x); + } std::vector<const Symbol *> &symbols; }; @@ -2839,6 +2872,12 @@ bool isRepeatableMetadirectiveCondition(const SomeExpr &expr) { } } // namespace +static SomeExpr NormalizeMetadirectiveCondition(const SomeExpr &expr) { + MetadirectiveConditionNormalizer normalizer; + evaluate::rewrite::Mutator normalize{normalizer}; + return normalize(expr); +} + bool IsRepeatableMetadirectiveCondition( const parser::ScalarExpr &condition, SemanticsContext &context) { const SomeExpr *expr{GetExpr(context, condition)}; @@ -2854,10 +2893,9 @@ bool AreSameRepeatableMetadirectiveCondition(const parser::ScalarExpr &left, !isRepeatableMetadirectiveCondition(*rightExpr)) return false; - MetadirectiveConditionNormalizer normalizer; - evaluate::rewrite::Mutator normalize{normalizer}; return AreSameMetadirectiveCondition( - normalize(*leftExpr), normalize(*rightExpr)); + NormalizeMetadirectiveCondition(*leftExpr), + NormalizeMetadirectiveCondition(*rightExpr)); } llvm::SmallVector<unsigned, 4> GetMetadirectiveElsePathCandidates( diff --git a/flang/test/Lower/OpenMP/metadirective-user.f90 b/flang/test/Lower/OpenMP/metadirective-user.f90 index 9ec0818ce602e..3eced767c75b4 100644 --- a/flang/test/Lower/OpenMP/metadirective-user.f90 +++ b/flang/test/Lower/OpenMP/metadirective-user.f90 @@ -648,3 +648,227 @@ subroutine test_multi_dynamic_multi_static(a, b) !$omp & default(nothing) #endif end subroutine + +! Both candidates score 5. The conditions differ, so neither selector is a +! subset of the other and `a` is tested first. +! CHECK-LABEL: func.func @_QPtest_distinct_conditions( +! CHECK-SAME: %[[ARG0:[^,]*]]: !fir.ref<!fir.logical<4>> +! CHECK-SAME: %[[ARG1:.*]]: !fir.ref<!fir.logical<4>> +! CHECK: %[[DECLA:.*]]:2 = hlfir.declare %[[ARG0]] +! CHECK: %[[DECLB:.*]]:2 = hlfir.declare %[[ARG1]] +! CHECK: %[[LOADA:.*]] = fir.load %[[DECLA]]#0 +! CHECK: %[[CONDA:.*]] = fir.convert %[[LOADA]] : (!fir.logical<4>) -> i1 +! CHECK: fir.if %[[CONDA]] { +! CHECK-NEXT: omp.taskyield +! CHECK-NEXT: } else { +! CHECK: %[[LOADB:.*]] = fir.load %[[DECLB]]#0 +! CHECK: %[[CONDB:.*]] = fir.convert %[[LOADB]] : (!fir.logical<4>) -> i1 +! CHECK: fir.if %[[CONDB]] { +! CHECK-NEXT: omp.taskwait +! CHECK: return +subroutine test_distinct_conditions(a, b) + logical, intent(in) :: a, b + !$omp metadirective & + !$omp & when(user={condition(a)}, & + !$omp & implementation={vendor(score(4): llvm)}: taskyield) & + !$omp & when(user={condition(b)}, device={kind(host)}, & + !$omp & implementation={vendor(score(3): llvm)}: taskwait) +end subroutine + +! With the same condition, the first selector is a strict subset of the second. +! CHECK-LABEL: func.func @_QPtest_same_condition( +! CHECK: fir.if +! CHECK-NEXT: omp.taskwait +! CHECK-NOT: omp.taskyield +! CHECK: return +subroutine test_same_condition(a) + logical, intent(in) :: a + !$omp metadirective & + !$omp & when(user={condition(a)}, & + !$omp & implementation={vendor(score(4): llvm)}: taskyield) & + !$omp & when(user={condition(a)}, device={kind(host)}, & + !$omp & implementation={vendor(score(3): llvm)}: taskwait) +end subroutine + +! Outer parentheses don't change the condition. +! CHECK-LABEL: func.func @_QPtest_parenthesized_condition( +! CHECK: fir.if +! CHECK-NEXT: omp.taskwait +! CHECK-NOT: omp.taskyield +! CHECK: return +subroutine test_parenthesized_condition(a) + logical, intent(in) :: a + !$omp metadirective & + !$omp & when(user={condition((a))}, & + !$omp & implementation={vendor(score(4): llvm)}: taskyield) & + !$omp & when(user={condition(a)}, device={kind(host)}, & + !$omp & implementation={vendor(score(3): llvm)}: taskwait) +end subroutine + +! Under match_none, both candidates score 3 and `a` is tested first. +! CHECK-LABEL: func.func @_QPtest_distinct_conditions_match_none( +! CHECK-SAME: %[[ARG0:[^,]*]]: !fir.ref<!fir.logical<4>> +! CHECK: %[[DECLA:.*]]:2 = hlfir.declare %[[ARG0]] +! CHECK: %[[LOADA:.*]] = fir.load %[[DECLA]]#0 +! CHECK: %[[CONDA:.*]] = fir.convert %[[LOADA]] : (!fir.logical<4>) -> i1 +! CHECK: %[[NOTA:.*]] = arith.xori %[[CONDA]] +! CHECK: fir.if %[[NOTA]] { +! CHECK-NEXT: omp.taskyield +! CHECK-NEXT: } else { +! CHECK: omp.taskwait +! CHECK: return +subroutine test_distinct_conditions_match_none(a, b) + logical, intent(in) :: a, b + !$omp metadirective & + !$omp & when(user={condition(score(2): a)}, & + !$omp & implementation={extension(match_none)}: taskyield) & + !$omp & when(user={condition(b)}, device={arch(nvptx)}, & + !$omp & implementation={extension(match_none)}: taskwait) +end subroutine + +! Constant conditions are compared by truth value, whatever their kind. +! CHECK-LABEL: func.func @_QPtest_constant_condition_kinds( +! CHECK-NOT: omp.taskyield +! CHECK: omp.taskwait +! CHECK-NOT: omp.taskyield +! CHECK: return +subroutine test_constant_condition_kinds() + !$omp metadirective & + !$omp & when(user={condition(.true._8)}, & + !$omp & implementation={vendor(score(4): llvm)}: taskyield) & + !$omp & when(user={condition(.true._4)}, device={kind(host)}, & + !$omp & implementation={vendor(score(3): llvm)}: taskwait) +end subroutine + +! Calls to intrinsics without arguments are evaluated at runtime. +! CHECK-LABEL: func.func @_QPtest_intrinsic_call_conditions( +! CHECK: arith.cmpi sgt, %{{.*}}, %c0 +! CHECK: fir.if +! CHECK-NEXT: omp.taskyield +! CHECK-NEXT: } else { +! CHECK: arith.cmpi sgt, %{{.*}}, %c1 +! CHECK: fir.if +! CHECK-NEXT: omp.taskwait +! CHECK: return +subroutine test_intrinsic_call_conditions() + !$omp metadirective & + !$omp & when(user={condition(command_argument_count() > 0)}, & + !$omp & implementation={vendor(score(4): llvm)}: taskyield) & + !$omp & when(user={condition(command_argument_count() > 1)}, & + !$omp & device={kind(host)}, & + !$omp & implementation={vendor(score(3): llvm)}: taskwait) +end subroutine + +module metadirective_user_a +contains + logical function predicate() + predicate = .true. + end function + logical function invoke(p) + interface + logical function p() + end function + end interface + invoke = p() + end function +end module + +module metadirective_user_b +contains + logical function predicate() + predicate = .false. + end function +end module + +! The conditions pass different procedures with the same name, so `a` is +! tested first. +! CHECK-LABEL: func.func @_QPtest_same_name_conditions( +! CHECK: fir.address_of(@_QMmetadirective_user_aPpredicate) +! CHECK: fir.if +! CHECK-NEXT: omp.taskyield +! CHECK-NEXT: } else { +! CHECK: fir.address_of(@_QMmetadirective_user_bPpredicate) +! CHECK: fir.if +! CHECK-NEXT: omp.taskwait +! CHECK: return +subroutine test_same_name_conditions() + use metadirective_user_a, only: a => predicate, invoke + use metadirective_user_b, only: b => predicate + !$omp metadirective & + !$omp & when(user={condition(invoke(a))}, & + !$omp & implementation={vendor(score(4): llvm)}: taskyield) & + !$omp & when(user={condition(invoke(b))}, device={kind(host)}, & + !$omp & implementation={vendor(score(3): llvm)}: taskwait) +end subroutine + +! `a` and `b` are the first dummy arguments of different procedures, but they +! are different variables, so `a` is tested first. +! CHECK-LABEL: func.func private @_QFtest_host_dummy_conditionsPinner( +! CHECK-SAME: %[[ARG0:[^,]*]]: !fir.ref<!fir.logical<4>> +! CHECK: %[[A:.*]]:2 = hlfir.declare {{.*}}"_QFtest_host_dummy_conditionsEa" +! CHECK: %[[B:.*]]:2 = hlfir.declare %[[ARG0]] {{.*}}"_QFtest_host_dummy_conditionsFinnerEb" +! CHECK: %[[LOADA:.*]] = fir.load %[[A]]#0 +! CHECK: %[[CONDA:.*]] = fir.convert %[[LOADA]] +! CHECK: fir.if %[[CONDA]] { +! CHECK-NEXT: omp.taskyield +! CHECK-NEXT: } else { +! CHECK: fir.load %[[B]]#0 +! CHECK: omp.taskwait +! CHECK: return +subroutine test_host_dummy_conditions(a) + logical, intent(in) :: a + call inner(a) +contains + subroutine inner(b) + logical, intent(in) :: b + !$omp metadirective & + !$omp & when(user={condition(a)}, & + !$omp & implementation={vendor(score(4): llvm)}: taskyield) & + !$omp & when(user={condition(b)}, device={kind(host)}, & + !$omp & implementation={vendor(score(3): llvm)}: taskwait) + end subroutine +end subroutine + +! `a .and. b` is not the same condition as `a`, so it is tested first. +! CHECK-LABEL: func.func private @_QFtest_host_dummy_and_conditionPinner( +! CHECK: fir.logical_and +! CHECK: fir.if +! CHECK-NEXT: omp.taskyield +! CHECK-NEXT: } else { +! CHECK: omp.taskwait +! CHECK: return +subroutine test_host_dummy_and_condition(a) + logical, intent(in) :: a + call inner(a) +contains + subroutine inner(b) + logical, intent(in) :: b + !$omp metadirective & + !$omp & when(user={condition(a .and. b)}, & + !$omp & implementation={vendor(score(4): llvm)}: taskyield) & + !$omp & when(user={condition(a)}, device={kind(host)}, & + !$omp & implementation={vendor(score(3): llvm)}: taskwait) + end subroutine +end subroutine + +! The array constructors have lengths from different dummy arguments. +! CHECK-LABEL: func.func private @_QFtest_host_dummy_lengthsPinner( +! CHECK: fir.if +! CHECK-NEXT: omp.taskyield +! CHECK-NEXT: } else { +! CHECK: omp.taskwait +! CHECK: return +subroutine test_host_dummy_lengths(n) + integer, intent(in) :: n + call inner(n) +contains + subroutine inner(m) + integer, intent(in) :: m + !$omp metadirective & + !$omp & when(user={condition(maxval([character(len=n)::]) == '')}, & + !$omp & implementation={vendor(score(4): llvm)}: taskyield) & + !$omp & when(user={condition(maxval([character(len=m)::]) == '')}, & + !$omp & device={kind(host)}, & + !$omp & implementation={vendor(score(3): llvm)}: taskwait) + end subroutine +end subroutine diff --git a/llvm/include/llvm/Frontend/OpenMP/OMPContext.h b/llvm/include/llvm/Frontend/OpenMP/OMPContext.h index f76a323a335a4..550c86007b9bf 100644 --- a/llvm/include/llvm/Frontend/OpenMP/OMPContext.h +++ b/llvm/include/llvm/Frontend/OpenMP/OMPContext.h @@ -22,6 +22,8 @@ #include "llvm/Frontend/OpenMP/OMPConstants.h" #include "llvm/Support/Compiler.h" +#include <string> + namespace llvm { class Triple; namespace omp { @@ -164,6 +166,8 @@ struct VariantMatchInfo { SmallVector<ISATrait, 8> ISATraits; SmallVector<TraitProperty, 8> ConstructTraits; SmallDenseMap<TraitProperty, APInt> ScoreMap; + /// Identifies a runtime user condition; empty for a constant condition. + std::string UserCondition; }; /// The context for a source location is made up of active property traits, diff --git a/llvm/lib/Frontend/OpenMP/OMPContext.cpp b/llvm/lib/Frontend/OpenMP/OMPContext.cpp index 87392f752493d..a9638ecd01d67 100644 --- a/llvm/lib/Frontend/OpenMP/OMPContext.cpp +++ b/llvm/lib/Frontend/OpenMP/OMPContext.cpp @@ -170,6 +170,13 @@ static bool isStrictSubset(const VariantMatchInfo &VMI0, for (unsigned Bit : VMI0.RequiredTraits.set_bits()) if (!VMI1.RequiredTraits.test(Bit)) return false; + // Different runtime conditions share a trait, so compare them as well. + for (TraitProperty Property : + {TraitProperty::user_condition_true, TraitProperty::user_condition_false, + TraitProperty::user_condition_unknown}) + if (VMI0.RequiredTraits.test(unsigned(Property)) && + VMI0.UserCondition != VMI1.UserCondition) + return false; // Different ISA names share a trait, so compare them as well. if (!llvm::all_of(VMI0.ISATraits, [&](const VariantMatchInfo::ISATrait &Trait) { diff --git a/llvm/unittests/Frontend/OpenMPContextTest.cpp b/llvm/unittests/Frontend/OpenMPContextTest.cpp index 4372f8bde5219..63ce15c59033c 100644 --- a/llvm/unittests/Frontend/OpenMPContextTest.cpp +++ b/llvm/unittests/Frontend/OpenMPContextTest.cpp @@ -803,6 +803,43 @@ TEST_F(OpenMPContextTest, StrictSubsetsOfAlternatingTiedSupersets) { EXPECT_EQ(Best({Host, CPU, Host, HostSuperset}), 1); } +TEST_F(OpenMPContextTest, UserConditionInStrictSubset) { + OMPContext Context(false, Triple("x86_64-unknown-linux"), Triple(), -1); + APInt Three(64, 3), Four(64, 4), Five(64, 5); + VariantMatchInfo A, B; + A.addTrait(TraitProperty::user_condition_true, ""); + A.addTrait(TraitProperty::implementation_vendor_llvm, "", &Four); + B.addTrait(TraitProperty::user_condition_true, ""); + B.addTrait(TraitProperty::implementation_vendor_llvm, "", &Three); + B.addTrait(TraitProperty::device_kind_host, ""); + auto Best = [&](const VariantMatchInfo &First, + const VariantMatchInfo &Second) { + return getBestVariantMatchForContext( + SmallVector<VariantMatchInfo, 2>{First, Second}, Context); + }; + + // Both score 5. Constant conditions are compared by their trait alone. + EXPECT_EQ(Best(A, B), 1); + EXPECT_EQ(Best(B, A), 0); + + // Different runtime conditions keep clause order. + A.UserCondition = "a"; + B.UserCondition = "b"; + EXPECT_EQ(Best(A, B), 0); + EXPECT_EQ(Best(B, A), 0); + + // The same runtime condition still makes A a strict subset of B. + B.UserCondition = "a"; + EXPECT_EQ(Best(A, B), 1); + EXPECT_EQ(Best(B, A), 0); + + // A higher score wins regardless of the conditions. + B.UserCondition = "b"; + A.ScoreMap[TraitProperty::implementation_vendor_llvm] = Five; + EXPECT_EQ(Best(A, B), 0); + EXPECT_EQ(Best(B, A), 1); +} + TEST_F(OpenMPContextTest, ISANamesInStrictSubset) { struct ISAContext : OMPContext { using OMPContext::OMPContext; >From db28595762083a9a5b65f83eeba9a7876ff168d6 Mon Sep 17 00:00:00 2001 From: "Chi Chun, Chen" <[email protected]> Date: Mon, 19 Oct 2026 23:49:38 -0500 Subject: [PATCH 03/11] Compare the condition of an unguarded match_any candidate A match_any WHEN clause with a runtime condition also gets a candidate without the condition, since its other traits can still match. That candidate has no condition trait, so isStrictSubset skipped the key check, and it became a subset of a WHEN clause with a different condition. The key is now compared whenever it is set. --- .../test/Lower/OpenMP/metadirective-user.f90 | 35 +++++++++++++++++++ llvm/lib/Frontend/OpenMP/OMPContext.cpp | 3 ++ llvm/unittests/Frontend/OpenMPContextTest.cpp | 14 ++++++++ 3 files changed, 52 insertions(+) diff --git a/flang/test/Lower/OpenMP/metadirective-user.f90 b/flang/test/Lower/OpenMP/metadirective-user.f90 index 3eced767c75b4..f8e2ffc459c4e 100644 --- a/flang/test/Lower/OpenMP/metadirective-user.f90 +++ b/flang/test/Lower/OpenMP/metadirective-user.f90 @@ -726,6 +726,41 @@ subroutine test_distinct_conditions_match_none(a, b) !$omp & implementation={extension(match_none)}: taskwait) end subroutine +! Under match_any, the first WHEN also matches through `vendor(llvm)` when `a` is +! false. Both score 3 and the conditions differ, so TASKYIELD is always selected. +! CHECK-LABEL: func.func @_QPtest_distinct_conditions_match_any( +! CHECK-NOT: omp.taskwait +! CHECK: omp.taskyield +! CHECK-NOT: omp.taskwait +! CHECK: return +subroutine test_distinct_conditions_match_any(a, b) + logical, intent(in) :: a, b + !$omp metadirective & + !$omp & when(user={condition(a)}, & + !$omp & implementation={vendor(score(2): llvm), extension(match_any)}: & + !$omp & taskyield) & + !$omp & when(user={condition(b)}, device={kind(host)}, & + !$omp & implementation={vendor(score(1): llvm), extension(match_any)}: & + !$omp & taskwait) +end subroutine + +! A constant condition is different from a runtime condition. +! CHECK-LABEL: func.func @_QPtest_constant_and_runtime_conditions_match_any( +! CHECK-NOT: omp.taskwait +! CHECK: omp.taskyield +! CHECK-NOT: omp.taskwait +! CHECK: return +subroutine test_constant_and_runtime_conditions_match_any(b) + logical, intent(in) :: b + !$omp metadirective & + !$omp & when(user={condition(.true.)}, & + !$omp & implementation={vendor(score(2): llvm), extension(match_any)}: & + !$omp & taskyield) & + !$omp & when(user={condition(b)}, device={kind(host)}, & + !$omp & implementation={vendor(score(1): llvm), extension(match_any)}: & + !$omp & taskwait) +end subroutine + ! Constant conditions are compared by truth value, whatever their kind. ! CHECK-LABEL: func.func @_QPtest_constant_condition_kinds( ! CHECK-NOT: omp.taskyield diff --git a/llvm/lib/Frontend/OpenMP/OMPContext.cpp b/llvm/lib/Frontend/OpenMP/OMPContext.cpp index a9638ecd01d67..11e3996972b7b 100644 --- a/llvm/lib/Frontend/OpenMP/OMPContext.cpp +++ b/llvm/lib/Frontend/OpenMP/OMPContext.cpp @@ -171,6 +171,9 @@ static bool isStrictSubset(const VariantMatchInfo &VMI0, if (!VMI1.RequiredTraits.test(Bit)) return false; // Different runtime conditions share a trait, so compare them as well. + // A runtime condition can be left out of the traits but keep its key. + if (!VMI0.UserCondition.empty() && VMI0.UserCondition != VMI1.UserCondition) + return false; for (TraitProperty Property : {TraitProperty::user_condition_true, TraitProperty::user_condition_false, TraitProperty::user_condition_unknown}) diff --git a/llvm/unittests/Frontend/OpenMPContextTest.cpp b/llvm/unittests/Frontend/OpenMPContextTest.cpp index 63ce15c59033c..a3f3f81e03eed 100644 --- a/llvm/unittests/Frontend/OpenMPContextTest.cpp +++ b/llvm/unittests/Frontend/OpenMPContextTest.cpp @@ -838,6 +838,20 @@ TEST_F(OpenMPContextTest, UserConditionInStrictSubset) { A.ScoreMap[TraitProperty::implementation_vendor_llvm] = Five; EXPECT_EQ(Best(A, B), 0); EXPECT_EQ(Best(B, A), 1); + + // A runtime condition left out of the traits is still compared by its key. + VariantMatchInfo C; + C.addTrait(TraitProperty::implementation_vendor_llvm, "", &Four); + C.UserCondition = "a"; + EXPECT_EQ(Best(C, B), 0); + EXPECT_EQ(Best(B, C), 0); + C.UserCondition = "b"; + EXPECT_EQ(Best(C, B), 1); + + // A constant condition is different from a runtime condition. + C.UserCondition = ""; + C.addTrait(TraitProperty::user_condition_true, ""); + EXPECT_EQ(Best(C, B), 0); } TEST_F(OpenMPContextTest, ISANamesInStrictSubset) { >From 8c766df3ec939bdd0e33c599b8d1d7ba1ce8cb4e Mon Sep 17 00:00:00 2001 From: "Chi Chun, Chen" <[email protected]> Date: Tue, 20 Oct 2026 12:36:55 -0500 Subject: [PATCH 04/11] Add a three-way runtime condition tie to the tests The first WHEN clause is a strict subset of the third, which ties with the second. Clause order then tests `b` first, and TASKYIELD is never selected. --- .../test/Lower/OpenMP/metadirective-user.f90 | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/flang/test/Lower/OpenMP/metadirective-user.f90 b/flang/test/Lower/OpenMP/metadirective-user.f90 index f8e2ffc459c4e..543a1fb577220 100644 --- a/flang/test/Lower/OpenMP/metadirective-user.f90 +++ b/flang/test/Lower/OpenMP/metadirective-user.f90 @@ -675,6 +675,35 @@ subroutine test_distinct_conditions(a, b) !$omp & implementation={vendor(score(3): llvm)}: taskwait) end subroutine +! All three score 5. The first is a strict subset of the third, which ties with +! the second, so `b` is tested first and TASKYIELD is never selected. +! CHECK-LABEL: func.func @_QPtest_distinct_conditions_three_way( +! CHECK-SAME: %[[ARG0:[^,]*]]: !fir.ref<!fir.logical<4>> +! CHECK-SAME: %[[ARG1:.*]]: !fir.ref<!fir.logical<4>> +! CHECK: %[[DECLA:.*]]:2 = hlfir.declare %[[ARG0]] +! CHECK: %[[DECLB:.*]]:2 = hlfir.declare %[[ARG1]] +! CHECK: %[[LOADB:.*]] = fir.load %[[DECLB]]#0 +! CHECK: %[[CONDB:.*]] = fir.convert %[[LOADB]] : (!fir.logical<4>) -> i1 +! CHECK: fir.if %[[CONDB]] { +! CHECK-NEXT: omp.taskwait +! CHECK-NEXT: } else { +! CHECK: %[[LOADA:.*]] = fir.load %[[DECLA]]#0 +! CHECK: %[[CONDA:.*]] = fir.convert %[[LOADA]] : (!fir.logical<4>) -> i1 +! CHECK: fir.if %[[CONDA]] { +! CHECK-NEXT: omp.barrier +! CHECK-NOT: omp.taskyield +! CHECK: return +subroutine test_distinct_conditions_three_way(a, b) + logical, intent(in) :: a, b + !$omp metadirective & + !$omp & when(user={condition(a)}, & + !$omp & implementation={vendor(score(4): llvm)}: taskyield) & + !$omp & when(user={condition(b)}, device={kind(host)}, & + !$omp & implementation={vendor(score(3): llvm)}: taskwait) & + !$omp & when(user={condition(a)}, device={kind(host)}, & + !$omp & implementation={vendor(score(3): llvm)}: barrier) +end subroutine + ! With the same condition, the first selector is a strict subset of the second. ! CHECK-LABEL: func.func @_QPtest_same_condition( ! CHECK: fir.if >From 43db794bb19d6eacf8af8c7fa71c20aba0692b46 Mon Sep 17 00:00:00 2001 From: "Chi Chun, Chen" <[email protected]> Date: Tue, 20 Oct 2026 22:15:43 -0500 Subject: [PATCH 05/11] Fold logical user conditions of any kind EvaluateUserCondition only folded default-kind logicals, so a condition like .false._8 stayed a runtime check. getConditionKey folded it on its own and gave it the empty key of a constant, so the WHEN clause was ranked like a true constant although it can never apply. EvaluateUserCondition now folds logical constants of any kind, and getConditionKey only sees runtime conditions. The tests that expected a constant of another kind to stay a runtime check now expect it to be resolved statically. --- flang/lib/Semantics/openmp-utils.cpp | 7 +- .../test/Lower/OpenMP/metadirective-user.f90 | 71 ++++++++++--------- 2 files changed, 41 insertions(+), 37 deletions(-) diff --git a/flang/lib/Semantics/openmp-utils.cpp b/flang/lib/Semantics/openmp-utils.cpp index 7f7a027c307a4..58a21ae833229 100644 --- a/flang/lib/Semantics/openmp-utils.cpp +++ b/flang/lib/Semantics/openmp-utils.cpp @@ -2372,8 +2372,7 @@ std::optional<bool> EvaluateUserCondition( return *constVal != 0; if (auto logicalVal = - evaluate::GetScalarConstantValue<evaluate::LogicalResult>( - evaluate::LogicalResultKind, foldedExpr)) + evaluate::GetScalarConstantValue<evaluate::LogicalResult>(foldedExpr)) return logicalVal->IsTrue(); return std::nullopt; @@ -2627,9 +2626,7 @@ std::optional<MetadirectiveCandidateSet> BuildMetadirectiveCandidateSet( llvm::SmallVector<SomeExpr, 4> runtimeConditions; auto getConditionKey = [&](const DynamicUserCondition &condition) { const SomeExpr *expr{GetExpr(context, *condition.expr)}; - if (!expr || - evaluate::IsActuallyConstant( - evaluate::Fold(context.foldingContext(), common::Clone(*expr)))) + if (!expr) return std::string{}; SomeExpr normalized{NormalizeMetadirectiveCondition(*expr)}; auto *it{llvm::find_if(runtimeConditions, [&](const SomeExpr &condition) { diff --git a/flang/test/Lower/OpenMP/metadirective-user.f90 b/flang/test/Lower/OpenMP/metadirective-user.f90 index 543a1fb577220..c181af00593bb 100644 --- a/flang/test/Lower/OpenMP/metadirective-user.f90 +++ b/flang/test/Lower/OpenMP/metadirective-user.f90 @@ -105,16 +105,13 @@ subroutine test_begin_condition_false() !$omp end metadirective end subroutine -! Only constant conditions of default LOGICAL kind are resolved statically. -! Other kinds are lowered as a runtime fir.if on a constant. +! Constant conditions of any LOGICAL kind are resolved statically. ! CHECK-LABEL: func.func @_QPtest_condition_true_kind8() -! CHECK: %[[TRUE:.*]] = arith.constant true -! CHECK-NEXT: fir.if %[[TRUE]] { -! CHECK-NEXT: omp.taskyield -! CHECK-NEXT: } else { -! CHECK-NEXT: } -! CHECK-NEXT: return +! CHECK-NOT: fir.if +! CHECK: omp.taskyield +! CHECK-NOT: fir.if +! CHECK: return subroutine test_condition_true_kind8() !$omp metadirective & !$omp & when(user={condition(.true._8)}: taskyield) & @@ -126,12 +123,9 @@ subroutine test_condition_true_kind8() end subroutine ! CHECK-LABEL: func.func @_QPtest_condition_false_kind8() -! CHECK: %[[FALSE:.*]] = arith.constant false -! CHECK-NEXT: fir.if %[[FALSE]] { -! CHECK-NEXT: omp.taskwait -! CHECK-NEXT: } else { -! CHECK-NEXT: } -! CHECK-NEXT: return +! CHECK-NOT: omp.taskwait +! CHECK-NOT: fir.if +! CHECK: return subroutine test_condition_false_kind8() !$omp metadirective & !$omp & when(user={condition(.false._8)}: taskwait) & @@ -143,12 +137,10 @@ subroutine test_condition_false_kind8() end subroutine ! CHECK-LABEL: func.func @_QPtest_condition_true_kind1() -! CHECK: %[[TRUE:.*]] = arith.constant true -! CHECK-NEXT: fir.if %[[TRUE]] { -! CHECK-NEXT: omp.taskyield -! CHECK-NEXT: } else { -! CHECK-NEXT: } -! CHECK-NEXT: return +! CHECK-NOT: fir.if +! CHECK: omp.taskyield +! CHECK-NOT: fir.if +! CHECK: return subroutine test_condition_true_kind1() !$omp metadirective & !$omp & when(user={condition(.true._1)}: taskyield) & @@ -160,12 +152,10 @@ subroutine test_condition_true_kind1() end subroutine ! CHECK-LABEL: func.func @_QPtest_condition_true_kind2() -! CHECK: %[[TRUE:.*]] = arith.constant true -! CHECK-NEXT: fir.if %[[TRUE]] { -! CHECK-NEXT: omp.taskyield -! CHECK-NEXT: } else { -! CHECK-NEXT: } -! CHECK-NEXT: return +! CHECK-NOT: fir.if +! CHECK: omp.taskyield +! CHECK-NOT: fir.if +! CHECK: return subroutine test_condition_true_kind2() !$omp metadirective & !$omp & when(user={condition(.true._2)}: taskyield) & @@ -177,12 +167,11 @@ subroutine test_condition_true_kind2() end subroutine ! CHECK-LABEL: func.func @_QPtest_condition_score_kind8() -! CHECK: %[[TRUE:.*]] = arith.constant true -! CHECK-NEXT: fir.if %[[TRUE]] { -! CHECK-NEXT: omp.taskwait -! CHECK-NEXT: } else { -! CHECK-NEXT: } -! CHECK-NEXT: return +! CHECK-NOT: omp.taskyield +! CHECK-NOT: fir.if +! CHECK: omp.taskwait +! CHECK-NOT: fir.if +! CHECK: return subroutine test_condition_score_kind8() !$omp metadirective & !$omp & when(user={condition(.true._8)}: taskyield) & @@ -804,6 +793,24 @@ subroutine test_constant_condition_kinds() !$omp & implementation={vendor(score(3): llvm)}: taskwait) end subroutine +! A false constant of any kind makes the third WHEN clause inapplicable, so the +! first two tie and TASKYIELD is selected. +! CHECK-LABEL: func.func @_QPtest_false_constant_condition_kind( +! CHECK-NOT: {{fir.if|omp.taskwait|omp.barrier}} +! CHECK: omp.taskyield +! CHECK-NOT: {{fir.if|omp.taskwait|omp.barrier}} +! CHECK: return +subroutine test_false_constant_condition_kind(b) + logical, intent(in) :: b + !$omp metadirective & + !$omp & when(device={kind(host)}, implementation={vendor(score(3): llvm)}: & + !$omp & taskyield) & + !$omp & when(user={condition(b)}, implementation={vendor(score(4): llvm)}: & + !$omp & taskwait) & + !$omp & when(user={condition(.false._8)}, device={kind(host)}, & + !$omp & implementation={vendor(score(3): llvm)}: barrier) +end subroutine + ! Calls to intrinsics without arguments are evaluated at runtime. ! CHECK-LABEL: func.func @_QPtest_intrinsic_call_conditions( ! CHECK: arith.cmpi sgt, %{{.*}}, %c0 >From cc20476cc23354fc14ddea6d499dbeaf8676d2ec Mon Sep 17 00:00:00 2001 From: "Chi Chun, Chen" <[email protected]> Date: Tue, 20 Oct 2026 22:23:18 -0500 Subject: [PATCH 06/11] Count a retained runtime condition in the strict-subset check The unguarded candidate of a match_any WHEN clause keeps its condition key but not the condition trait, so it had one trait fewer than an identical guarded candidate and counted as its strict subset. A key without a trait now counts as a trait. A WHEN clause with an omitted directive is ranked without its condition, so it no longer gets a key. --- flang/lib/Semantics/openmp-utils.cpp | 3 +- .../test/Lower/OpenMP/metadirective-user.f90 | 20 ++++++++++ llvm/lib/Frontend/OpenMP/OMPContext.cpp | 37 +++++++++++-------- llvm/unittests/Frontend/OpenMPContextTest.cpp | 11 ++++++ 4 files changed, 54 insertions(+), 17 deletions(-) diff --git a/flang/lib/Semantics/openmp-utils.cpp b/flang/lib/Semantics/openmp-utils.cpp index 58a21ae833229..5421e3e64bb22 100644 --- a/flang/lib/Semantics/openmp-utils.cpp +++ b/flang/lib/Semantics/openmp-utils.cpp @@ -2650,7 +2650,8 @@ std::optional<MetadirectiveCandidateSet> BuildMetadirectiveCandidateSet( llvm::omp::VariantMatchInfo rawVMI; std::optional<DynamicUserCondition> dynamicCondition{ MakeVariantMatchInfo(rawVMI, *ctxSel, context)}; - if (dynamicCondition) + // An omitted directive is ranked without its condition. + if (dynamicCondition && isExplicit) rawVMI.UserCondition = getConditionKey(*dynamicCondition); if (llvm::any_of( rawVMI.ConstructTraits, [](llvm::omp::TraitProperty property) { diff --git a/flang/test/Lower/OpenMP/metadirective-user.f90 b/flang/test/Lower/OpenMP/metadirective-user.f90 index c181af00593bb..e3386ac0eb0b7 100644 --- a/flang/test/Lower/OpenMP/metadirective-user.f90 +++ b/flang/test/Lower/OpenMP/metadirective-user.f90 @@ -779,6 +779,26 @@ subroutine test_constant_and_runtime_conditions_match_any(b) !$omp & taskwait) end subroutine +! The first and third WHEN clauses are identical, so the first wins the tie, also +! through `vendor(llvm)` when `a` is false. +! CHECK-LABEL: func.func @_QPtest_same_condition_match_any( +! CHECK-NOT: {{fir.if|omp.taskwait|omp.barrier}} +! CHECK: omp.taskyield +! CHECK-NOT: {{fir.if|omp.taskwait|omp.barrier}} +! CHECK: return +subroutine test_same_condition_match_any(a) + logical, intent(in) :: a + !$omp metadirective & + !$omp & when(user={condition(a)}, & + !$omp & implementation={vendor(score(2): llvm), extension(match_any)}: & + !$omp & taskyield) & + !$omp & when(user={condition(command_argument_count() > 0)}, & + !$omp & implementation={vendor(score(2): llvm)}: taskwait) & + !$omp & when(user={condition(a)}, & + !$omp & implementation={vendor(score(2): llvm), extension(match_any)}: & + !$omp & barrier) +end subroutine + ! Constant conditions are compared by truth value, whatever their kind. ! CHECK-LABEL: func.func @_QPtest_constant_condition_kinds( ! CHECK-NOT: omp.taskyield diff --git a/llvm/lib/Frontend/OpenMP/OMPContext.cpp b/llvm/lib/Frontend/OpenMP/OMPContext.cpp index 11e3996972b7b..e512bb678c1db 100644 --- a/llvm/lib/Frontend/OpenMP/OMPContext.cpp +++ b/llvm/lib/Frontend/OpenMP/OMPContext.cpp @@ -160,26 +160,36 @@ static bool isOrderedSubset(ArrayRef<T> C0, ArrayRef<T> C1) { return true; } +static bool hasUserConditionTrait(const VariantMatchInfo &VMI) { + for (TraitProperty Property : + {TraitProperty::user_condition_true, TraitProperty::user_condition_false, + TraitProperty::user_condition_unknown}) + if (VMI.RequiredTraits.test(unsigned(Property))) + return true; + return false; +} + +// A runtime condition can be left out of the traits but keep its key, so count +// it as a trait. +static unsigned countTraits(const VariantMatchInfo &VMI) { + return VMI.RequiredTraits.count() + + (!VMI.UserCondition.empty() && !hasUserConditionTrait(VMI)); +} + static bool isStrictSubset(const VariantMatchInfo &VMI0, const VariantMatchInfo &VMI1) { // VMI0 is a strict subset if its required traits are a subset of VMI1's, its // construct traits are an ordered subsequence of VMI1's, and either relation // is strict. - if (VMI0.RequiredTraits.count() > VMI1.RequiredTraits.count()) + if (countTraits(VMI0) > countTraits(VMI1)) return false; for (unsigned Bit : VMI0.RequiredTraits.set_bits()) if (!VMI1.RequiredTraits.test(Bit)) return false; // Different runtime conditions share a trait, so compare them as well. - // A runtime condition can be left out of the traits but keep its key. - if (!VMI0.UserCondition.empty() && VMI0.UserCondition != VMI1.UserCondition) + if ((!VMI0.UserCondition.empty() || hasUserConditionTrait(VMI0)) && + VMI0.UserCondition != VMI1.UserCondition) return false; - for (TraitProperty Property : - {TraitProperty::user_condition_true, TraitProperty::user_condition_false, - TraitProperty::user_condition_unknown}) - if (VMI0.RequiredTraits.test(unsigned(Property)) && - VMI0.UserCondition != VMI1.UserCondition) - return false; // Different ISA names share a trait, so compare them as well. if (!llvm::all_of(VMI0.ISATraits, [&](const VariantMatchInfo::ISATrait &Trait) { @@ -189,18 +199,13 @@ static bool isStrictSubset(const VariantMatchInfo &VMI0, if (!isOrderedSubset<TraitProperty>(VMI0.ConstructTraits, VMI1.ConstructTraits)) return false; - if (VMI0.RequiredTraits.count() < VMI1.RequiredTraits.count()) + if (countTraits(VMI0) < countTraits(VMI1)) return true; // With the same traits, only a repeated construct makes VMI0 strict. if (VMI0.ConstructTraits.size() == VMI1.ConstructTraits.size()) return false; // Different conditions share a trait, so they can't be compared. - for (TraitProperty Property : - {TraitProperty::user_condition_true, TraitProperty::user_condition_false, - TraitProperty::user_condition_unknown}) - if (VMI0.RequiredTraits.test(unsigned(Property))) - return false; - return true; + return !hasUserConditionTrait(VMI0); } static int diff --git a/llvm/unittests/Frontend/OpenMPContextTest.cpp b/llvm/unittests/Frontend/OpenMPContextTest.cpp index a3f3f81e03eed..14cc015979b06 100644 --- a/llvm/unittests/Frontend/OpenMPContextTest.cpp +++ b/llvm/unittests/Frontend/OpenMPContextTest.cpp @@ -852,6 +852,17 @@ TEST_F(OpenMPContextTest, UserConditionInStrictSubset) { C.UserCondition = ""; C.addTrait(TraitProperty::user_condition_true, ""); EXPECT_EQ(Best(C, B), 0); + + // A condition left out of the traits still counts as one, so D, which only + // has the key, is not a strict subset of E, which also has the trait. + VariantMatchInfo D, E; + D.addTrait(TraitProperty::implementation_vendor_llvm, "", &Four); + D.UserCondition = "a"; + E.addTrait(TraitProperty::user_condition_true, ""); + E.addTrait(TraitProperty::implementation_vendor_llvm, "", &Four); + E.UserCondition = "a"; + EXPECT_EQ(Best(D, E), 0); + EXPECT_EQ(Best(E, D), 0); } TEST_F(OpenMPContextTest, ISANamesInStrictSubset) { >From 5629f85b5d8c88661d68e37d5836c2b6208f84e1 Mon Sep 17 00:00:00 2001 From: "Chi Chun, Chen" <[email protected]> Date: Tue, 20 Oct 2026 22:25:10 -0500 Subject: [PATCH 07/11] Check that TASKYIELD is unconditional in the match_any tests --- flang/test/Lower/OpenMP/metadirective-user.f90 | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/flang/test/Lower/OpenMP/metadirective-user.f90 b/flang/test/Lower/OpenMP/metadirective-user.f90 index e3386ac0eb0b7..c8eb049ff2d0a 100644 --- a/flang/test/Lower/OpenMP/metadirective-user.f90 +++ b/flang/test/Lower/OpenMP/metadirective-user.f90 @@ -747,9 +747,9 @@ subroutine test_distinct_conditions_match_none(a, b) ! Under match_any, the first WHEN also matches through `vendor(llvm)` when `a` is ! false. Both score 3 and the conditions differ, so TASKYIELD is always selected. ! CHECK-LABEL: func.func @_QPtest_distinct_conditions_match_any( -! CHECK-NOT: omp.taskwait +! CHECK-NOT: {{fir.if|omp.taskwait}} ! CHECK: omp.taskyield -! CHECK-NOT: omp.taskwait +! CHECK-NOT: {{fir.if|omp.taskwait}} ! CHECK: return subroutine test_distinct_conditions_match_any(a, b) logical, intent(in) :: a, b @@ -764,9 +764,9 @@ subroutine test_distinct_conditions_match_any(a, b) ! A constant condition is different from a runtime condition. ! CHECK-LABEL: func.func @_QPtest_constant_and_runtime_conditions_match_any( -! CHECK-NOT: omp.taskwait +! CHECK-NOT: {{fir.if|omp.taskwait}} ! CHECK: omp.taskyield -! CHECK-NOT: omp.taskwait +! CHECK-NOT: {{fir.if|omp.taskwait}} ! CHECK: return subroutine test_constant_and_runtime_conditions_match_any(b) logical, intent(in) :: b >From f77663c3270b713c289caceec1fd6c3a3877464f Mon Sep 17 00:00:00 2001 From: "Chi Chun, Chen" <[email protected]> Date: Mon, 9 Nov 2026 12:12:10 -0600 Subject: [PATCH 08/11] Keep the condition key when a match_any WHEN clause omits its directive The unguarded candidate of a match_any WHEN clause keeps its condition key when the clause has a directive, but not when it omits one. A selector with a key is then never a strict subset of one without, so with ``` !$omp metadirective & !$omp& when(user={condition(a)}, & !$omp& implementation={vendor(score(4): llvm), extension(match_any)}: & !$omp& taskwait) & !$omp& when(user={condition(a)}, device={kind(host)}, & !$omp& implementation={vendor(score(3): llvm), extension(match_any)}:) ``` TASKWAIT was also selected when `a` is false. Give both unguarded candidates the key, so the first is again a strict subset of the second and nothing is selected when `a` is false. When `a` is true, TASKWAIT is still selected, as before this PR. The key also makes the omitted directive's selector include its condition when it's compared with a selector without one. Under match_any, an omitted directive with a condition now wins a tie against an explicit directive with the same static traits, as an explicit NOTHING already does. Without match_any, an omitted directive is still ranked without its condition. --- flang/lib/Semantics/openmp-utils.cpp | 10 +++- .../test/Lower/OpenMP/metadirective-user.f90 | 60 +++++++++++++++++++ 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/flang/lib/Semantics/openmp-utils.cpp b/flang/lib/Semantics/openmp-utils.cpp index 5421e3e64bb22..20fad978af746 100644 --- a/flang/lib/Semantics/openmp-utils.cpp +++ b/flang/lib/Semantics/openmp-utils.cpp @@ -2650,7 +2650,8 @@ std::optional<MetadirectiveCandidateSet> BuildMetadirectiveCandidateSet( llvm::omp::VariantMatchInfo rawVMI; std::optional<DynamicUserCondition> dynamicCondition{ MakeVariantMatchInfo(rawVMI, *ctxSel, context)}; - // An omitted directive is ranked without its condition. + // An omitted directive is ranked without its condition, except for its + // unguarded match_any candidate below. if (dynamicCondition && isExplicit) rawVMI.UserCondition = getConditionKey(*dynamicCondition); if (llvm::any_of( @@ -2718,12 +2719,17 @@ std::optional<MetadirectiveCandidateSet> BuildMetadirectiveCandidateSet( // Represent both outcomes: a guarded candidate with the condition's // score and an unguarded candidate with only the static traits. If // the WHEN clause omits its directive, only add the unguarded - // candidate. + // candidate. Either way, the unguarded candidate keeps the + // condition's key, so the strict-subset check still sees the + // condition. if (isExplicit) { llvm::omp::VariantMatchInfo conditionTrueVMI{staticVMI}; addConditionTraitForRanking(conditionTrueVMI); result.candidates.push_back({spec, std::move(conditionTrueVMI), isExplicit, dynamicCondition}); + } else { + // The key was only set above for an explicit directive. + staticVMI.UserCondition = getConditionKey(*dynamicCondition); } result.candidates.push_back({spec, std::move(staticVMI), isExplicit}); continue; diff --git a/flang/test/Lower/OpenMP/metadirective-user.f90 b/flang/test/Lower/OpenMP/metadirective-user.f90 index c8eb049ff2d0a..87e199c2a80f2 100644 --- a/flang/test/Lower/OpenMP/metadirective-user.f90 +++ b/flang/test/Lower/OpenMP/metadirective-user.f90 @@ -799,6 +799,66 @@ subroutine test_same_condition_match_any(a) !$omp & barrier) end subroutine +! Both WHEN clauses score 3. The second also matches through `vendor(llvm)` when +! `a` is false, and its selector still includes the condition, so the first is +! its strict subset and TASKYIELD is always selected. +! CHECK-LABEL: func.func @_QPtest_unconditional_and_runtime_condition_match_any( +! CHECK-NOT: {{fir.if|omp.taskwait}} +! CHECK: omp.taskyield +! CHECK-NOT: {{fir.if|omp.taskwait}} +! CHECK: return +subroutine test_unconditional_and_runtime_condition_match_any(a) + logical, intent(in) :: a + !$omp metadirective & + !$omp & when(implementation={vendor(score(2): llvm), extension(match_any)}: & + !$omp & taskwait) & + !$omp & when(user={condition(a)}, & + !$omp & implementation={vendor(score(2): llvm), extension(match_any)}: & + !$omp & taskyield) +end subroutine + +! Both WHEN clauses score 5, and the second adds `kind(host)` to the same +! condition but omits its directive. When `a` is false, the first still matches +! through `vendor(llvm)`, but it's a strict subset of the second, so nothing is +! selected. When `a` is true, TASKWAIT is still selected, although the first +! selector is a strict subset of the second there as well. #231676 ranks the +! original selectors and would select nothing in both cases. +! CHECK-LABEL: func.func @_QPtest_omitted_directive_match_any( +! CHECK-SAME: %[[ARG0:.*]]: !fir.ref<!fir.logical<4>> +! CHECK: %[[DECLA:.*]]:2 = hlfir.declare %[[ARG0]] +! CHECK: %[[LOADA:.*]] = fir.load %[[DECLA]]#0 +! CHECK: %[[CONDA:.*]] = fir.convert %[[LOADA]] : (!fir.logical<4>) -> i1 +! CHECK: fir.if %[[CONDA]] { +! CHECK-NEXT: omp.taskwait +! CHECK-NEXT: } else { +! CHECK-NEXT: } +! CHECK-NEXT: return +subroutine test_omitted_directive_match_any(a) + logical, intent(in) :: a + !$omp metadirective & + !$omp & when(user={condition(a)}, & + !$omp & implementation={vendor(score(4): llvm), extension(match_any)}: & + !$omp & taskwait) & + !$omp & when(user={condition(a)}, device={kind(host)}, & + !$omp & implementation={vendor(score(3): llvm), extension(match_any)}:) +end subroutine + +! Under match_any, the omitted directive's selector includes its condition, so +! the BARRIER selector is a strict subset of it and nothing is selected, as with +! an explicit NOTHING. Without match_any, an omitted directive is ranked without +! its condition, and BARRIER wins the tie (see +! test_dynamic_implicit_nothing_tie_break). +! CHECK-LABEL: func.func @_QPtest_omitted_directive_match_any_unconditional( +! CHECK-NOT: {{fir.if|omp.barrier}} +! CHECK: return +subroutine test_omitted_directive_match_any_unconditional(flag) + logical, intent(in) :: flag + !$omp metadirective & + !$omp & when(implementation={vendor(llvm), extension(match_any)}, & + !$omp & user={condition(flag)}:) & + !$omp & when(implementation={vendor(llvm), extension(match_any)}: barrier) +end subroutine + ! Constant conditions are compared by truth value, whatever their kind. ! CHECK-LABEL: func.func @_QPtest_constant_condition_kinds( ! CHECK-NOT: omp.taskyield >From 304f7be0122b3e2ed817af76ddcb6e1d4bbcd934 Mon Sep 17 00:00:00 2001 From: "Chi Chun, Chen" <[email protected]> Date: Fri, 13 Nov 2026 13:50:27 -0600 Subject: [PATCH 09/11] Test ISA names against a retained condition key A retained condition key counts as a trait, so it can make a selector require more traits than one with different ISA names. isStrictSubset now compares the ISA names in that case too, so with ``` !$omp metadirective & !$omp& when(device={isa("sse4")}, & !$omp& implementation={vendor(llvm), extension(match_any)}: taskwait) & !$omp& when(user={condition(a)}, device={isa("avx")}, & !$omp& implementation={vendor(llvm), extension(match_any)}: taskyield) ``` TASKWAIT is always selected, as when `a` is true. Test this case. Co-authored-by: Copilot <[email protected]> --- flang/test/Lower/OpenMP/metadirective-user.f90 | 17 +++++++++++++++++ llvm/unittests/Frontend/OpenMPContextTest.cpp | 9 +++++++++ 2 files changed, 26 insertions(+) diff --git a/flang/test/Lower/OpenMP/metadirective-user.f90 b/flang/test/Lower/OpenMP/metadirective-user.f90 index 87e199c2a80f2..2fc48aabaccde 100644 --- a/flang/test/Lower/OpenMP/metadirective-user.f90 +++ b/flang/test/Lower/OpenMP/metadirective-user.f90 @@ -859,6 +859,23 @@ subroutine test_omitted_directive_match_any_unconditional(flag) !$omp & when(implementation={vendor(llvm), extension(match_any)}: barrier) end subroutine +! Both WHEN clauses score 5, and the second also matches through `vendor(llvm)` +! when `a` is false. The ISA names differ, so neither selector is a strict +! subset of the other and TASKWAIT is always selected. +! CHECK-LABEL: func.func @_QPtest_isa_names_match_any( +! CHECK-NOT: {{fir.if|omp.taskyield}} +! CHECK: omp.taskwait +! CHECK-NOT: {{fir.if|omp.taskyield}} +! CHECK: return +subroutine test_isa_names_match_any(a) + logical, intent(in) :: a + !$omp metadirective & + !$omp & when(device={isa("sse4")}, & + !$omp & implementation={vendor(llvm), extension(match_any)}: taskwait) & + !$omp & when(user={condition(a)}, device={isa("avx")}, & + !$omp & implementation={vendor(llvm), extension(match_any)}: taskyield) +end subroutine + ! Constant conditions are compared by truth value, whatever their kind. ! CHECK-LABEL: func.func @_QPtest_constant_condition_kinds( ! CHECK-NOT: omp.taskyield diff --git a/llvm/unittests/Frontend/OpenMPContextTest.cpp b/llvm/unittests/Frontend/OpenMPContextTest.cpp index 14cc015979b06..0a146f3f05753 100644 --- a/llvm/unittests/Frontend/OpenMPContextTest.cpp +++ b/llvm/unittests/Frontend/OpenMPContextTest.cpp @@ -887,6 +887,15 @@ TEST_F(OpenMPContextTest, ISANamesInStrictSubset) { EXPECT_EQ(Best(SSE, AVX), 0); EXPECT_EQ(Best(AVX, SSE), 0); + // A runtime condition left out of the traits is counted the same way. + VariantMatchInfo AVXWithCondition; + AVXWithCondition.addTrait(TraitProperty::device_isa___ANY, "avx"); + AVXWithCondition.addTrait(TraitProperty::implementation_vendor_llvm, "", + &Four); + AVXWithCondition.UserCondition = "a"; + EXPECT_EQ(Best(SSE, AVXWithCondition), 0); + EXPECT_EQ(Best(AVXWithCondition, SSE), 0); + // With all of SSE's ISA names, AVX is a strict superset. AVX.addTrait(TraitProperty::device_isa___ANY, "sse"); EXPECT_EQ(Best(SSE, AVX), 1); >From 4c37437c45080d6da991f99d361dce0c3d33afc8 Mon Sep 17 00:00:00 2001 From: "Chi Chun, Chen" <[email protected]> Date: Fri, 13 Nov 2026 13:18:05 -0600 Subject: [PATCH 10/11] Keep the condition key when a WHEN clause omits its directive A WHEN clause that omits its directive is ranked without its condition, and only its match_any unguarded candidate kept the condition's key. Otherwise its selector lost the condition, so with ``` !$omp metadirective when(user={condition(b)}: taskyield) & !$omp& when(user={condition(.true.)}, implementation={vendor(llvm)}: taskwait) & !$omp& when(user={condition(b)}, implementation={vendor(llvm)}:) ``` the first selector wasn't a strict subset of the third, and TASKYIELD was selected when `b` is true. Keep the key whenever the static traits match, and let the key stand for the condition trait when it was left out of the other selector's traits. The first selector then scores zero, the explicit TASKWAIT wins the tie with the implicit NOTHING, and TASKWAIT is always selected, as with an explicit NOTHING. An omitted directive now ranks as an explicit NOTHING in these ties: - test_dynamic_implicit_nothing_tie_break selects nothing when `flag` is true instead of BARRIER. - test_omitted_directive_match_any selects nothing when `a` is true instead of TASKWAIT, as #231676 does. Co-authored-by: Copilot <[email protected]> --- flang/lib/Semantics/openmp-utils.cpp | 12 ++-- .../test/Lower/OpenMP/metadirective-user.f90 | 61 +++++++++++-------- llvm/lib/Frontend/OpenMP/OMPContext.cpp | 18 ++++-- llvm/unittests/Frontend/OpenMPContextTest.cpp | 11 ++++ 4 files changed, 67 insertions(+), 35 deletions(-) diff --git a/flang/lib/Semantics/openmp-utils.cpp b/flang/lib/Semantics/openmp-utils.cpp index 20fad978af746..480cb99b10add 100644 --- a/flang/lib/Semantics/openmp-utils.cpp +++ b/flang/lib/Semantics/openmp-utils.cpp @@ -2650,9 +2650,7 @@ std::optional<MetadirectiveCandidateSet> BuildMetadirectiveCandidateSet( llvm::omp::VariantMatchInfo rawVMI; std::optional<DynamicUserCondition> dynamicCondition{ MakeVariantMatchInfo(rawVMI, *ctxSel, context)}; - // An omitted directive is ranked without its condition, except for its - // unguarded match_any candidate below. - if (dynamicCondition && isExplicit) + if (dynamicCondition) rawVMI.UserCondition = getConditionKey(*dynamicCondition); if (llvm::any_of( rawVMI.ConstructTraits, [](llvm::omp::TraitProperty property) { @@ -2727,9 +2725,6 @@ std::optional<MetadirectiveCandidateSet> BuildMetadirectiveCandidateSet( addConditionTraitForRanking(conditionTrueVMI); result.candidates.push_back({spec, std::move(conditionTrueVMI), isExplicit, dynamicCondition}); - } else { - // The key was only set above for an explicit directive. - staticVMI.UserCondition = getConditionKey(*dynamicCondition); } result.candidates.push_back({spec, std::move(staticVMI), isExplicit}); continue; @@ -2737,7 +2732,10 @@ std::optional<MetadirectiveCandidateSet> BuildMetadirectiveCandidateSet( llvm::omp::VariantMatchInfo rankingVMI{staticVMI}; // Preserve the existing lowering behavior for an omitted directive: - // do not let its runtime condition raise the implicit NOTHING rank. + // do not let its runtime condition raise the implicit NOTHING rank. If + // its static traits match, it keeps the condition's key, so the + // strict-subset check still sees the condition, as for an explicit + // NOTHING. if (!isExplicit && hasMatchAny && !isStaticVMIApplicable) rankingVMI = llvm::omp::VariantMatchInfo(); else if (isExplicit) diff --git a/flang/test/Lower/OpenMP/metadirective-user.f90 b/flang/test/Lower/OpenMP/metadirective-user.f90 index 2fc48aabaccde..765e35240edf4 100644 --- a/flang/test/Lower/OpenMP/metadirective-user.f90 +++ b/flang/test/Lower/OpenMP/metadirective-user.f90 @@ -518,12 +518,19 @@ subroutine test_dynamic_user_match_any_static_score(flag) #endif end subroutine -! The explicit directive variant wins this tie over the earlier implicit -! nothing candidate. +! The omitted directive's selector includes its condition, so the BARRIER +! selector is a strict subset of it and nothing is selected when `flag` is true, +! as with an explicit NOTHING. ! CHECK-LABEL: func.func @_QPtest_dynamic_implicit_nothing_tie_break( -! CHECK-NOT: fir.if -! CHECK: omp.barrier -! CHECK: return +! CHECK-SAME: %[[ARG0:.*]]: !fir.ref<!fir.logical<4>> +! CHECK: %[[DECL:.*]]:2 = hlfir.declare %[[ARG0]] +! CHECK: %[[LOAD:.*]] = fir.load %[[DECL]]#0 +! CHECK: %[[COND:.*]] = fir.convert %[[LOAD]] : (!fir.logical<4>) -> i1 +! CHECK: fir.if %[[COND]] { +! CHECK-NEXT: } else { +! CHECK-NEXT: omp.barrier +! CHECK-NEXT: } +! CHECK-NEXT: return subroutine test_dynamic_implicit_nothing_tie_break(flag) logical, intent(in) :: flag !$omp metadirective & @@ -818,21 +825,12 @@ subroutine test_unconditional_and_runtime_condition_match_any(a) end subroutine ! Both WHEN clauses score 5, and the second adds `kind(host)` to the same -! condition but omits its directive. When `a` is false, the first still matches -! through `vendor(llvm)`, but it's a strict subset of the second, so nothing is -! selected. When `a` is true, TASKWAIT is still selected, although the first -! selector is a strict subset of the second there as well. #231676 ranks the -! original selectors and would select nothing in both cases. +! condition but omits its directive. The first selector is a strict subset of +! the second whether `a` is true or false, when the first still matches through +! `vendor(llvm)`, so nothing is selected. ! CHECK-LABEL: func.func @_QPtest_omitted_directive_match_any( -! CHECK-SAME: %[[ARG0:.*]]: !fir.ref<!fir.logical<4>> -! CHECK: %[[DECLA:.*]]:2 = hlfir.declare %[[ARG0]] -! CHECK: %[[LOADA:.*]] = fir.load %[[DECLA]]#0 -! CHECK: %[[CONDA:.*]] = fir.convert %[[LOADA]] : (!fir.logical<4>) -> i1 -! CHECK: fir.if %[[CONDA]] { -! CHECK-NEXT: omp.taskwait -! CHECK-NEXT: } else { -! CHECK-NEXT: } -! CHECK-NEXT: return +! CHECK-NOT: {{fir.if|omp.taskwait}} +! CHECK: return subroutine test_omitted_directive_match_any(a) logical, intent(in) :: a !$omp metadirective & @@ -843,11 +841,9 @@ subroutine test_omitted_directive_match_any(a) !$omp & implementation={vendor(score(3): llvm), extension(match_any)}:) end subroutine -! Under match_any, the omitted directive's selector includes its condition, so -! the BARRIER selector is a strict subset of it and nothing is selected, as with -! an explicit NOTHING. Without match_any, an omitted directive is ranked without -! its condition, and BARRIER wins the tie (see -! test_dynamic_implicit_nothing_tie_break). +! Under match_any, the first WHEN clause also matches through `vendor(llvm)` when +! `flag` is false. Its selector includes the condition, so the BARRIER selector +! is a strict subset of it and nothing is selected, as with an explicit NOTHING. ! CHECK-LABEL: func.func @_QPtest_omitted_directive_match_any_unconditional( ! CHECK-NOT: {{fir.if|omp.barrier}} ! CHECK: return @@ -859,6 +855,23 @@ subroutine test_omitted_directive_match_any_unconditional(flag) !$omp & when(implementation={vendor(llvm), extension(match_any)}: barrier) end subroutine +! All three WHEN clauses score 1. The third omits its directive but keeps its +! condition, so the first selector is a strict subset of it. The second is +! explicit, so it wins the tie with the third, and TASKWAIT is always selected. +! CHECK-LABEL: func.func @_QPtest_omitted_directive_keeps_condition( +! CHECK-NOT: {{fir.if|omp.taskyield}} +! CHECK: omp.taskwait +! CHECK-NOT: {{fir.if|omp.taskyield}} +! CHECK: return +subroutine test_omitted_directive_keeps_condition(b) + logical, intent(in) :: b + !$omp metadirective & + !$omp & when(user={condition(b)}: taskyield) & + !$omp & when(user={condition(.true.)}, implementation={vendor(llvm)}: & + !$omp & taskwait) & + !$omp & when(user={condition(b)}, implementation={vendor(llvm)}:) +end subroutine + ! Both WHEN clauses score 5, and the second also matches through `vendor(llvm)` ! when `a` is false. The ISA names differ, so neither selector is a strict ! subset of the other and TASKWAIT is always selected. diff --git a/llvm/lib/Frontend/OpenMP/OMPContext.cpp b/llvm/lib/Frontend/OpenMP/OMPContext.cpp index e512bb678c1db..fe6145a225a16 100644 --- a/llvm/lib/Frontend/OpenMP/OMPContext.cpp +++ b/llvm/lib/Frontend/OpenMP/OMPContext.cpp @@ -160,6 +160,12 @@ static bool isOrderedSubset(ArrayRef<T> C0, ArrayRef<T> C1) { return true; } +static bool isUserConditionTrait(TraitProperty Property) { + return Property == TraitProperty::user_condition_true || + Property == TraitProperty::user_condition_false || + Property == TraitProperty::user_condition_unknown; +} + static bool hasUserConditionTrait(const VariantMatchInfo &VMI) { for (TraitProperty Property : {TraitProperty::user_condition_true, TraitProperty::user_condition_false, @@ -183,13 +189,17 @@ static bool isStrictSubset(const VariantMatchInfo &VMI0, // is strict. if (countTraits(VMI0) > countTraits(VMI1)) return false; - for (unsigned Bit : VMI0.RequiredTraits.set_bits()) - if (!VMI1.RequiredTraits.test(Bit)) - return false; // Different runtime conditions share a trait, so compare them as well. - if ((!VMI0.UserCondition.empty() || hasUserConditionTrait(VMI0)) && + bool HasRuntimeCondition = !VMI0.UserCondition.empty(); + if ((HasRuntimeCondition || hasUserConditionTrait(VMI0)) && VMI0.UserCondition != VMI1.UserCondition) return false; + // The same key also stands for a condition left out of VMI1's traits. + bool IsConditionLeftOut = HasRuntimeCondition && !hasUserConditionTrait(VMI1); + for (unsigned Bit : VMI0.RequiredTraits.set_bits()) + if (!VMI1.RequiredTraits.test(Bit) && + !(IsConditionLeftOut && isUserConditionTrait(TraitProperty(Bit)))) + return false; // Different ISA names share a trait, so compare them as well. if (!llvm::all_of(VMI0.ISATraits, [&](const VariantMatchInfo::ISATrait &Trait) { diff --git a/llvm/unittests/Frontend/OpenMPContextTest.cpp b/llvm/unittests/Frontend/OpenMPContextTest.cpp index 0a146f3f05753..f8a44b34877bc 100644 --- a/llvm/unittests/Frontend/OpenMPContextTest.cpp +++ b/llvm/unittests/Frontend/OpenMPContextTest.cpp @@ -863,6 +863,17 @@ TEST_F(OpenMPContextTest, UserConditionInStrictSubset) { E.UserCondition = "a"; EXPECT_EQ(Best(D, E), 0); EXPECT_EQ(Best(E, D), 0); + + // The key also stands for a condition left out of a superset's traits, as + // for a WHEN clause that omits its directive. + VariantMatchInfo F; + F.addTrait(TraitProperty::implementation_vendor_llvm, "", &Three); + F.addTrait(TraitProperty::device_kind_host, ""); + F.UserCondition = "a"; + EXPECT_EQ(Best(E, F), 1); + EXPECT_EQ(Best(F, E), 0); + F.UserCondition = "b"; + EXPECT_EQ(Best(E, F), 0); } TEST_F(OpenMPContextTest, ISANamesInStrictSubset) { >From ad2a7c38d460dfa863ea990c52621c64a1bc44cf Mon Sep 17 00:00:00 2001 From: "Chi Chun, Chen" <[email protected]> Date: Fri, 13 Nov 2026 13:19:54 -0600 Subject: [PATCH 11/11] Only compare tied variants that share a runtime condition Each tied variant was compared with every other tied variant until a strict superset was found, trying the supersets found so far first. When each superset has a different runtime condition, the cache never hits, so a selection is quadratic in the number of tied variants, and Flang selects repeatedly to build the ELSE chain. With 160 TASKYIELD clauses with conditions `x(i)` followed by 160 TASKWAIT clauses with the same conditions and `kind(cpu)`, MLIR generation took 3.3s instead of 0.5s before this PR. A variant with a runtime condition can only be a strict subset of one with the same condition, so group the tied variants by condition and scan only that group, keeping the cache per group. A variant without a runtime condition still scans every tied variant. The example now takes 0.64s. Co-authored-by: Copilot <[email protected]> --- llvm/lib/Frontend/OpenMP/OMPContext.cpp | 34 +++++++++++++------ llvm/unittests/Frontend/OpenMPContextTest.cpp | 7 ++++ 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/llvm/lib/Frontend/OpenMP/OMPContext.cpp b/llvm/lib/Frontend/OpenMP/OMPContext.cpp index fe6145a225a16..aac6cfbdedfb5 100644 --- a/llvm/lib/Frontend/OpenMP/OMPContext.cpp +++ b/llvm/lib/Frontend/OpenMP/OMPContext.cpp @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// #include "llvm/Frontend/OpenMP/OMPContext.h" +#include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" @@ -470,21 +471,32 @@ int llvm::omp::getBestVariantMatchForContext( } // A strict subset of another tied variant is never best; otherwise the first - // one wins. Tied variants often share a few supersets, so try the ones found - // so far before scanning all of them. - SmallVector<const VariantMatchInfo *, 4> Supersets; + // one wins. A variant with a runtime condition can only be a subset of one + // with the same condition, so only those are scanned. Tied variants often + // share a few supersets, so try the ones found so far for the same condition + // first. + struct TiedGroup { + SmallVector<unsigned, 4> Idxs; + SmallVector<unsigned, 1> Supersets; + }; + DenseMap<StringRef, TiedGroup> Groups; + for (unsigned Idx : BestVMIIdxs) + Groups[VMIs[Idx].UserCondition].Idxs.push_back(Idx); for (unsigned Idx : BestVMIIdxs) { const VariantMatchInfo &VMI = VMIs[Idx]; - if (llvm::any_of(Supersets, [&](const VariantMatchInfo *Superset) { - return isStrictSubset(VMI, *Superset); - })) - continue; - auto *It = llvm::find_if(BestVMIIdxs, [&](unsigned OtherIdx) { + auto IsStrictSubsetOf = [&](unsigned OtherIdx) { return isStrictSubset(VMI, VMIs[OtherIdx]); - }); - if (It == BestVMIIdxs.end()) + }; + TiedGroup &Group = Groups[VMI.UserCondition]; + if (llvm::any_of(Group.Supersets, IsStrictSubsetOf)) + continue; + // A variant without a runtime condition can be a subset of any of them. + ArrayRef<unsigned> Others = + VMI.UserCondition.empty() ? BestVMIIdxs : Group.Idxs; + auto *It = llvm::find_if(Others, IsStrictSubsetOf); + if (It == Others.end()) return Idx; - Supersets.push_back(&VMIs[*It]); + Group.Supersets.push_back(*It); } return -1; } diff --git a/llvm/unittests/Frontend/OpenMPContextTest.cpp b/llvm/unittests/Frontend/OpenMPContextTest.cpp index f8a44b34877bc..937a24d38ba48 100644 --- a/llvm/unittests/Frontend/OpenMPContextTest.cpp +++ b/llvm/unittests/Frontend/OpenMPContextTest.cpp @@ -874,6 +874,13 @@ TEST_F(OpenMPContextTest, UserConditionInStrictSubset) { EXPECT_EQ(Best(F, E), 0); F.UserCondition = "b"; EXPECT_EQ(Best(E, F), 0); + + // A selector without a condition can be a strict subset of one with a + // runtime condition. + VariantMatchInfo G; + G.addTrait(TraitProperty::implementation_vendor_llvm, "", &Four); + EXPECT_EQ(Best(G, B), 1); + EXPECT_EQ(Best(B, G), 0); } TEST_F(OpenMPContextTest, ISANamesInStrictSubset) { _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
