Create a placement operator new directly. (#6941)

Instead of injecting code to declare an `operator new`, generate AST for
it directly. In order to use this, directly generate a `CXXNewExpr`
rather than asking Clang to build one.

This is less of a hack, and doesn't visibly leak an `operator new`
declaration that inline C++ code or template instantiations might see.
It also avoids generating a warning in C++26 and later that the
`constexpr` declaration of `operator new` is used but not defined.

Assisted-by: Gemini 3.1 Pro via Antigravity
This commit is contained in:
Richard Smith
2026-03-20 16:50:37 +00:00
committed by GitHub
parent 8e824d02be
commit e06eb8f532
5 changed files with 120 additions and 84 deletions
-28
View File
@@ -86,34 +86,6 @@ static auto GenerateCppIncludesHeaderCode(
}
}
}
// Inject a declaration of placement operator new, because the code we
// generate in thunks depends on it for placement new expressions. Clang has
// special-case logic for lowering a new-expression using this, so a
// definition is not required.
// TODO: This is a hack. We should be able to directly generate Clang AST to
// construct objects in-place without this.
// TODO: Once we can rely on libc++ being available, consider including
// `<__new/placement_new_delete.h>` instead.
code_stream << R"(# 1 "<carbon-internal>"
#undef constexpr
#if __cplusplus > 202302L
constexpr
#endif
#undef void
#undef operator
#undef new
void* operator new(__SIZE_TYPE__, void*)
#if __cplusplus < 201103L
#undef throw
throw()
#else
#undef noexcept
noexcept
#endif
;
)";
return code;
}