Skip to content

[libc++] Opt std::*set out of map key extraction optimization - #220452

Merged
gburgessiv merged 4 commits into
llvm:mainfrom
gburgessiv:libcxx-fix-tree-inference
Sep 9, 2026
Merged

gburgessiv merged 4 commits into
llvm:mainfrom
gburgessiv:libcxx-fix-tree-inference

Conversation

@gburgessiv

Copy link
Copy Markdown
Member

PR #154512 (relanded by #155565) removed __can_extract_map_key, which had a blanket opt-out for std::*sets. The new logic does not have that opt-out, leading to std::sets being incorrectly constructed.

The new regression tests demonstrate this, but essentially the idea is:

  1. Have std::set<T> foo;
  2. Call foo.emplace(some_t, arg_that_influences_comparisons_or_hashes);
  3. The emplace will internally search using some_t as the key, not T(some_t, arg_that_influences_comparisons_or_hashes);

This opts out std::*set from this optimization to match previous behavior.

Tests and fix were produced by an LLM. I reviewed them and they seem reasonable to me, though I don't have a strong background in libc++ testing conventions.

(Credit to Deva S, our partner who tracked this down. Unfortunately I don't know his GH handle)

Fixes #220451

@github-actions

github-actions Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

✅ With the latest revision this PR passed the C/C++ code formatter.

PR llvm#154512 (relanded by llvm#155565) removed `__can_extract_map_key`, which
had a blanket opt-out for `std::*set`s. The new logic does not have that
opt-out, leading to `std::set`s being incorrectly constructed.

The new regression tests demonstrate this, but essentially the idea is:
1. Have `std::set<T> foo;`
2. Call `foo.emplace(some_t,
    arg_that_influences_comparisons_or_hashes);`
3. The emplace will internally search using `some_t` as the key, *not*
    `T(some_t, arg_that_influences_comparisons_or_hashes);`

This opts out `std::*set` from this optimization to match previous
behavior.

Tests and fix were produced by an LLM. I reviewed them and they seem
reasonable to me, though I don't have a strong background in libc++
testing conventions.

Fixes llvm#220451
@gburgessiv
gburgessiv force-pushed the libcxx-fix-tree-inference branch from 852d609 to 6716e09 Compare September 2, 2026 01:45
gcc-16 failed with -std=c++26 because `error: non-constant condition for
static assertion`. Try exempting new test from constant evaluation,
since that's not really relevant here
@nickdesaulniers

Copy link
Copy Markdown
Member

cc @llvm/android-maintainers

@gburgessiv

Copy link
Copy Markdown
Member Author

CI is ~65% green, and the remainder is pending. Good enough to start the review IMO.

@gburgessiv
gburgessiv marked this pull request as ready for review September 2, 2026 17:39
@gburgessiv
gburgessiv requested a review from a team as a code owner September 2, 2026 17:39
@llvmorg-github-actions llvmorg-github-actions Bot added the libc++ libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi. label Sep 2, 2026
@llvmorg-github-actions

Copy link
Copy Markdown

@llvm/pr-subscribers-libcxx

Author: George Burgess IV (gburgessiv)

Changes

PR #154512 (relanded by #155565) removed __can_extract_map_key, which had a blanket opt-out for std::*sets. The new logic does not have that opt-out, leading to std::sets being incorrectly constructed.

The new regression tests demonstrate this, but essentially the idea is:

  1. Have std::set&lt;T&gt; foo;
  2. Call foo.emplace(some_t, arg_that_influences_comparisons_or_hashes);
  3. The emplace will internally search using some_t as the key, not T(some_t, arg_that_influences_comparisons_or_hashes);

This opts out std::*set from this optimization to match previous behavior.

Tests and fix were produced by an LLM. I reviewed them and they seem reasonable to me, though I don't have a strong background in libc++ testing conventions.

(Credit to Deva S, our partner who tracked this down. Unfortunately I don't know his GH handle)

Fixes #220451


Full diff: https://github.com/llvm/llvm-project/pull/220452.diff

5 Files Affected:

  • (modified) libcxx/include/__hash_table (+1-1)
  • (modified) libcxx/include/__tree (+3-3)
  • (modified) libcxx/include/__utility/try_key_extraction.h (+11-6)
  • (modified) libcxx/test/std/containers/associative/set/emplace.pass.cpp (+11)
  • (modified) libcxx/test/std/containers/unord/unord.set/emplace.pass.cpp (+10)
diff --git a/libcxx/include/__hash_table b/libcxx/include/__hash_table
index ed58789378bc1..4874e4e084c38 100644
--- a/libcxx/include/__hash_table
+++ b/libcxx/include/__hash_table
@@ -788,7 +788,7 @@ public:
 
   template <class... _Args>
   _LIBCPP_HIDE_FROM_ABI pair<iterator, bool> __emplace_unique(_Args&&... __args) {
-    return std::__try_key_extraction<key_type>(
+    return std::__try_key_extraction<key_type, value_type>(
         [this](const key_type& __key, _Args&&... __args2) {
           size_t __hash   = hash_function()(__key);
           size_type __bc  = bucket_count();
diff --git a/libcxx/include/__tree b/libcxx/include/__tree
index 7c9a65ac3fbda..7cfa8e86fdc02 100644
--- a/libcxx/include/__tree
+++ b/libcxx/include/__tree
@@ -1074,7 +1074,7 @@ public:
 
   template <class... _Args>
   _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX26 pair<iterator, bool> __emplace_unique(_Args&&... __args) {
-    return std::__try_key_extraction<key_type>(
+    return std::__try_key_extraction<key_type, value_type>(
         [this](const key_type& __key, _Args&&... __args2) {
           auto [__parent, __child] = __find_equal(__key);
           __node_pointer __r       = std::__static_fancy_pointer_cast<__node_pointer>(__child);
@@ -1105,7 +1105,7 @@ public:
   template <class... _Args>
   _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX26 pair<iterator, bool>
   __emplace_hint_unique(const_iterator __p, _Args&&... __args) {
-    return std::__try_key_extraction<key_type>(
+    return std::__try_key_extraction<key_type, value_type>(
         [this, __p](const key_type& __key, _Args&&... __args2) {
           __node_base_pointer __dummy;
           auto [__parent, __child] = __find_equal(__p, __dummy, __key);
@@ -1182,7 +1182,7 @@ public:
     using __reference = decltype(*__first);
 
     for (; __first != __last; ++__first) {
-      std::__try_key_extraction<key_type>(
+      std::__try_key_extraction<key_type, value_type>(
           [this, &__max_node](const key_type& __key, __reference&& __val) {
             if (value_comp()(__max_node->__get_value(), __key)) { // __key > __max_node
               __node_holder __nd = __construct_node(std::forward<__reference>(__val));
diff --git a/libcxx/include/__utility/try_key_extraction.h b/libcxx/include/__utility/try_key_extraction.h
index 3423d746dee7f..d56a953f28ce2 100644
--- a/libcxx/include/__utility/try_key_extraction.h
+++ b/libcxx/include/__utility/try_key_extraction.h
@@ -27,13 +27,14 @@
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-template <class _KeyT, class _Ret, class _WithKey, class _WithoutKey, class... _Args>
+template <class _KeyT, class _ValT, class _Ret, class _WithKey, class _WithoutKey, class... _Args>
 _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX26 _Ret
 __try_key_extraction_impl(__priority_tag<0>, _WithKey, _WithoutKey __without_key, _Args&&... __args) {
   return __without_key(std::forward<_Args>(__args)...);
 }
 
 template <class _KeyT,
+          class _ValT,
           class _Ret,
           class _WithKey,
           class _WithoutKey,
@@ -45,11 +46,12 @@ __try_key_extraction_impl(__priority_tag<1>, _WithKey __with_key, _WithoutKey, _
 }
 
 template <class _KeyT,
+          class _ValT,
           class _Ret,
           class _WithKey,
           class _WithoutKey,
           class _Arg,
-          __enable_if_t<__is_pair_v<__remove_const_ref_t<_Arg> > &&
+          __enable_if_t<!is_same<_KeyT, _ValT>::value && __is_pair_v<__remove_const_ref_t<_Arg> > &&
                             is_same<__remove_const_t<typename __remove_const_ref_t<_Arg>::first_type>, _KeyT>::value,
                         int> = 0>
 _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX26 _Ret
@@ -58,12 +60,13 @@ __try_key_extraction_impl(__priority_tag<1>, _WithKey __with_key, _WithoutKey, _
 }
 
 template <class _KeyT,
+          class _ValT,
           class _Ret,
           class _WithKey,
           class _WithoutKey,
           class _Arg1,
           class _Arg2,
-          __enable_if_t<is_same<_KeyT, __remove_const_ref_t<_Arg1> >::value, int> = 0>
+          __enable_if_t<!is_same<_KeyT, _ValT>::value && is_same<_KeyT, __remove_const_ref_t<_Arg1> >::value, int> = 0>
 _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX26 _Ret
 __try_key_extraction_impl(__priority_tag<1>, _WithKey __with_key, _WithoutKey, _Arg1&& __arg1, _Arg2&& __arg2) {
   return __with_key(__arg1, std::forward<_Arg1>(__arg1), std::forward<_Arg2>(__arg2));
@@ -71,13 +74,15 @@ __try_key_extraction_impl(__priority_tag<1>, _WithKey __with_key, _WithoutKey, _
 
 #ifndef _LIBCPP_CXX03_LANG
 template <class _KeyT,
+          class _ValT,
           class _Ret,
           class _WithKey,
           class _WithoutKey,
           class _PiecewiseConstruct,
           class _Tuple1,
           class _Tuple2,
-          __enable_if_t<is_same<__remove_const_ref_t<_PiecewiseConstruct>, piecewise_construct_t>::value &&
+          __enable_if_t<!is_same<_KeyT, _ValT>::value &&
+                            is_same<__remove_const_ref_t<_PiecewiseConstruct>, piecewise_construct_t>::value &&
                             __is_tuple_v<_Tuple1> && tuple_size<_Tuple1>::value == 1 &&
                             is_same<__remove_const_ref_t<typename tuple_element<0, _Tuple1>::type>, _KeyT>::value,
                         int> = 0>
@@ -101,11 +106,11 @@ _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX26 _Ret __try_key_extraction_im
 // arguments. Otherwise it calls the `__without_key` function with all of the arguments.
 //
 // Both `__with_key` and `__without_key` must take all arguments by reference.
-template <class _KeyT, class _WithKey, class _WithoutKey, class... _Args>
+template <class _KeyT, class _ValT, class _WithKey, class _WithoutKey, class... _Args>
 _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX26 decltype(std::declval<_WithoutKey>()(std::declval<_Args>()...))
 __try_key_extraction(_WithKey __with_key, _WithoutKey __without_key, _Args&&... __args) {
   using _Ret = decltype(__without_key(std::forward<_Args>(__args)...));
-  return std::__try_key_extraction_impl<_KeyT, _Ret>(
+  return std::__try_key_extraction_impl<_KeyT, _ValT, _Ret>(
       __priority_tag<1>(), __with_key, __without_key, std::forward<_Args>(__args)...);
 }
 
diff --git a/libcxx/test/std/containers/associative/set/emplace.pass.cpp b/libcxx/test/std/containers/associative/set/emplace.pass.cpp
index 55ef489d2a6ba..cd9fc88860505 100644
--- a/libcxx/test/std/containers/associative/set/emplace.pass.cpp
+++ b/libcxx/test/std/containers/associative/set/emplace.pass.cpp
@@ -17,6 +17,7 @@
 
 #include <cassert>
 #include <set>
+#include <string>
 
 #include "../../Emplaceable.h"
 #include "DefaultOnly.h"
@@ -92,6 +93,16 @@ TEST_CONSTEXPR_CXX26 bool test() {
     assert(std::get<1>(res));
     assert(set.begin() == std::get<0>(res));
   }
+  if (!TEST_IS_CONSTANT_EVALUATED) {
+    // Regression test for #220451
+    // Make sure emplace with multiple arguments doesn't extract the first argument as a key for sets.
+    std::set<std::string> s;
+    s.emplace("foo");
+    auto res = s.emplace(std::string("ofoo"), 1);
+    assert(!res.second);
+    assert(s.size() == 1);
+    assert(*s.begin() == "foo");
+  }
 
   return true;
 }
diff --git a/libcxx/test/std/containers/unord/unord.set/emplace.pass.cpp b/libcxx/test/std/containers/unord/unord.set/emplace.pass.cpp
index 24e85a1ab7f54..60a0e85cbe487 100644
--- a/libcxx/test/std/containers/unord/unord.set/emplace.pass.cpp
+++ b/libcxx/test/std/containers/unord/unord.set/emplace.pass.cpp
@@ -18,6 +18,7 @@
 //     pair<iterator, bool> emplace(Args&&... args);
 
 #include <cassert>
+#include <string>
 #include <unordered_set>
 
 #include "../../Emplaceable.h"
@@ -75,6 +76,15 @@ int main(int, char**) {
     assert(std::get<1>(res));
     assert(set.begin() == std::get<0>(res));
   }
+  { // Regression test for #220451
+    // Make sure emplace with multiple arguments doesn't extract the first argument as a key for unordered sets.
+    std::unordered_set<std::string> s;
+    s.emplace("foo");
+    auto res = s.emplace(std::string("ofoo"), 1);
+    assert(!res.second);
+    assert(s.size() == 1);
+    assert(*s.begin() == "foo");
+  }
 
   return 0;
 }

- Pass an NTTP `__is_map` into `__try_key_extraction_impl` rather than
  threading `_ValT` through all overloads.
- Replace `std::string` in `set/emplace.pass.cpp` with a lightweight,
  constexpr-friendly struct so the test works during constant evaluation
  without needing guards.
- Update PR references in tests to point to https://llvm.org/PR220451.

Written by Gemini, reviewed by me.
@gburgessiv

Copy link
Copy Markdown
Member Author

Thanks for the reviews! I'll merge tomorrow if no other comments arise before then.

@gburgessiv
gburgessiv merged commit 10d4bdf into llvm:main Sep 9, 2026
84 checks passed
@gburgessiv
gburgessiv deleted the libcxx-fix-tree-inference branch September 9, 2026 13:19
@philnik777 philnik777 added this to the LLVM 23.x Release milestone Sep 10, 2026
@github-project-automation github-project-automation Bot moved this from Needs Triage to Done in LLVM Release Status Sep 10, 2026
@github-project-automation github-project-automation Bot moved this to Needs Triage in LLVM Release Status Sep 10, 2026
@philnik777

Copy link
Copy Markdown
Contributor

/cherry-pick 10d4bdf

@llvmbot

llvmbot commented Sep 10, 2026

Copy link
Copy Markdown
Member

/pull-request #222641

vadimkotov pushed a commit to vadimkotov/llvm-project that referenced this pull request Sep 11, 2026
…#220452)

PR llvm#154512 (relanded by llvm#155565) removed `__can_extract_map_key`, which
had a blanket opt-out for `std::*set`s. The new logic does not have that
opt-out, leading to `std::set`s being incorrectly constructed.

The new regression tests demonstrate this, but essentially the idea is:
1. Have `std::set<T> foo;`
2. Call `foo.emplace(some_t,
arg_that_influences_comparisons_or_hashes);`
3. The emplace will internally search using `some_t` as the key, *not*
`T(some_t, arg_that_influences_comparisons_or_hashes);`

This opts out `std::*set` from this optimization to match previous
behavior.

Tests and fix were produced by an LLM. I reviewed them and they seem
reasonable to me, though I don't have a strong background in libc++
testing conventions.

(Credit to Deva S, our partner who tracked this down. Unfortunately I
don't know his GH handle)

Fixes llvm#220451
aobolensk pushed a commit to aobolensk/llvm-project that referenced this pull request Sep 15, 2026
…#220452)

PR llvm#154512 (relanded by llvm#155565) removed `__can_extract_map_key`, which
had a blanket opt-out for `std::*set`s. The new logic does not have that
opt-out, leading to `std::set`s being incorrectly constructed.

The new regression tests demonstrate this, but essentially the idea is:
1. Have `std::set<T> foo;`
2. Call `foo.emplace(some_t,
arg_that_influences_comparisons_or_hashes);`
3. The emplace will internally search using `some_t` as the key, *not*
`T(some_t, arg_that_influences_comparisons_or_hashes);`

This opts out `std::*set` from this optimization to match previous
behavior.

Tests and fix were produced by an LLM. I reviewed them and they seem
reasonable to me, though I don't have a strong background in libc++
testing conventions.

(Credit to Deva S, our partner who tracked this down. Unfortunately I
don't know his GH handle)

Fixes llvm#220451
dyung pushed a commit to llvmbot/llvm-project that referenced this pull request Sep 16, 2026
…#220452)

PR llvm#154512 (relanded by llvm#155565) removed `__can_extract_map_key`, which
had a blanket opt-out for `std::*set`s. The new logic does not have that
opt-out, leading to `std::set`s being incorrectly constructed.

The new regression tests demonstrate this, but essentially the idea is:
1. Have `std::set<T> foo;`
2. Call `foo.emplace(some_t,
arg_that_influences_comparisons_or_hashes);`
3. The emplace will internally search using `some_t` as the key, *not*
`T(some_t, arg_that_influences_comparisons_or_hashes);`

This opts out `std::*set` from this optimization to match previous
behavior.

Tests and fix were produced by an LLM. I reviewed them and they seem
reasonable to me, though I don't have a strong background in libc++
testing conventions.

(Credit to Deva S, our partner who tracked this down. Unfortunately I
don't know his GH handle)

Fixes llvm#220451

(cherry picked from commit 10d4bdf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

libc++ libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi.

Projects

Development

Successfully merging this pull request may close these issues.

libc++ std::{unordered_,}set<T>::emplace(T, ...) may break container invariants

5 participants