-
Notifications
You must be signed in to change notification settings - Fork 14.3k
[Sema] Fix lifetime extension for temporaries in range-based for loops in C++23 #145164
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
Thank you for submitting a Pull Request (PR) to the LLVM Project! This PR will be automatically labeled and the relevant teams will be notified. If you wish to, you can add reviewers by using the "Reviewers" section on this page. If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers. If you have further questions, they may be answered by the LLVM GitHub User Guide. You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums. |
This comment was marked as resolved.
This comment was marked as resolved.
Done! |
A couple of quick notes:
|
@llvm/pr-subscribers-clang-modules @llvm/pr-subscribers-clang Author: Marco Vitale (mrcvtl) ChangesC++23 mandates that temporaries used in range-based for loops are lifetime-extended Includes test cases based on examples from CWG900/P2644R1. Fixes #109793 Full diff: https://github.com/llvm/llvm-project/pull/145164.diff 2 Files Affected:
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp b/clang/lib/Sema/CheckExprLifetime.cpp
index 060ba31660556..0434aa0c29c26 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -57,6 +57,31 @@ enum LifetimeKind {
};
using LifetimeResult =
llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
+
+/// Returns true if the given entity is part of a range-based for loop and
+/// should trigger lifetime extension under C++23 rules.
+///
+/// This handles both explicit range loop variables and internal compiler-
+/// generated variables like `__range1`.
+static bool
+isRangeBasedForLoopVariable(const Sema &SemaRef,
+ const InitializedEntity *ExtendingEntity) {
+ if (!SemaRef.getLangOpts().CPlusPlus23)
+ return false;
+
+ const Decl *EntityDecl = ExtendingEntity->getDecl();
+ if (!EntityDecl)
+ return false;
+
+ if (const auto *VD = dyn_cast<VarDecl>(EntityDecl)) {
+ if (VD->isCXXForRangeDecl() || VD->getName().starts_with("__range")) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
} // namespace
/// Determine the declaration which an initialized entity ultimately refers to,
@@ -1341,6 +1366,9 @@ checkExprLifetimeImpl(Sema &SemaRef, const InitializedEntity *InitEntity,
}
if (IsGslPtrValueFromGslTempOwner && DiagLoc.isValid()) {
+ if (isRangeBasedForLoopVariable(SemaRef, ExtendingEntity))
+ return true;
+
SemaRef.Diag(DiagLoc, diag::warn_dangling_lifetime_pointer)
<< DiagRange;
return false;
diff --git a/clang/test/SemaCXX/range-for-lifetime-cxx23.cpp b/clang/test/SemaCXX/range-for-lifetime-cxx23.cpp
new file mode 100644
index 0000000000000..bb6e06ec4517c
--- /dev/null
+++ b/clang/test/SemaCXX/range-for-lifetime-cxx23.cpp
@@ -0,0 +1,79 @@
+// RUN: %clangxx -std=c++23 -fsyntax-only -Xclang -verify %s
+
+#include <string>
+#include <vector>
+#include <map>
+#include <tuple>
+#include <optional>
+#include <variant>
+#include <array>
+#include <span>
+
+static std::vector<std::string> getVector() {
+ return {"first", "second", "third"};
+}
+
+static std::map<std::string, std::vector<int>> getMap() {
+ return {{"key", {1, 2, 3}}};
+}
+
+static std::tuple<std::vector<double>> getTuple() {
+ return std::make_tuple(std::vector<double>{3.14, 2.71});
+}
+
+static std::optional<std::vector<char>> getOptionalColl() {
+ return std::vector<char>{'x', 'y', 'z'};
+}
+
+static std::variant<std::string, int> getVariant() {
+ return std::string("variant");
+}
+
+static const std::array<int, 4>& arrOfConst() {
+ static const std::array<int, 4> arr = {10, 20, 30, 40};
+ return arr;
+}
+
+static void testGetVectorSubscript() {
+ for (auto e : getVector()[0]) {
+ (void)e;
+ }
+}
+
+static void testGetMapSubscript() {
+ for (auto valueElem : getMap()["key"]) {
+ (void)valueElem;
+ }
+}
+
+static void testGetTuple() {
+ for (auto e : std::get<0>(getTuple())) {
+ (void)e;
+ }
+}
+
+static void testOptionalValue() {
+ for (auto e : getOptionalColl().value()) {
+ (void)e;
+ }
+}
+
+static void testVariantGetString() {
+ for (char c : std::get<std::string>(getVariant())) {
+ (void)c;
+ }
+}
+
+static void testSpanLastFromConstArray() {
+ for (auto s : std::span{arrOfConst()}.last(2)) {
+ (void)s;
+ }
+}
+
+static void testSpanFromVectorPtr() {
+ for (auto e : std::span(getVector().data(), 2)) {
+ (void)e;
+ }
+}
+
+// expected-no-diagnostics
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thank you for the patch!
Please add a release note in clang/docs/ReleaseNotes.rst
so that users can know the improvement.
clang/lib/Sema/CheckExprLifetime.cpp
Outdated
/// This handles both explicit range loop variables and internal compiler- | ||
/// generated variables like `__range1`. | ||
static bool | ||
isRangeBasedForLoopVariable(const Sema &SemaRef, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This parameter type can be const LangOptions &
.
@@ -0,0 +1,79 @@ | |||
// RUN: %clangxx -std=c++23 -fsyntax-only -Xclang -verify %s |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use %clang_cc1
for frontend tests.
-Xclang
can be removed.
#include <string> | ||
#include <vector> | ||
#include <map> | ||
#include <tuple> | ||
#include <optional> | ||
#include <variant> | ||
#include <array> | ||
#include <span> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do not include files outside test folders. You can search namespace std
to see how other test files handle this case.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can construct some simple fake std dependencies.
Eg.
namespace std {
typedef decltype(sizeof(int)) size_t;
template <class E>
struct initializer_list {
const E *begin;
size_t size;
initializer_list() : begin(nullptr), size(0) {}
};
template <typename E>
struct list {
list() {}
~list() {}
E *begin();
E *end();
const E *begin() const;
const E *end() const;
};
template <typename E>
struct vector {
vector() {}
vector(std::initializer_list<E>) {}
~vector() {}
E *begin();
E *end();
const E *begin() const;
const E *end() const;
};
} // namespace std
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I have a more simple reproducer:
using size_t = decltype(sizeof(void *));
namespace std {
template <typename T> struct vector {
T &operator[](size_t I);
};
struct string {
const char *begin();
const char *end();
};
} // namespace std
extern "C" int printf(const char *, ...);
std::vector<std::string> getData();
void foo() {
for (auto c : getData()[0]) {
printf("%c\n", c);
}
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yup, my initial test was actually very similar (even if I used the stdlib), but I wanted to try out all the scenarios mentioned in the paper that you implemented. Since that doesn’t really make much sense, I’ll stick with this approach, thanks!
Thanks for you fix! |
I’ve taken some time to better understand the code and think through the solution. I tried using llvm-project/clang/lib/Parse/ParseDecl.cpp Lines 2314 to 2318 in b581f9d
However, the warning is actually triggered starting from this location: llvm-project/clang/lib/Parse/ParseDecl.cpp Line 2266 in b581f9d
An alternative approach would be to apply your logic and set again the flag in here: llvm-project/clang/lib/Parse/ParseStmt.cpp Lines 2174 to 2179 in 43d042b
Maybe we could act on What do you think? I'm absolutely open to every approach (the cleaner, the better!). |
IMO, we have 2 options:
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 9397546c8fc5..c639a4b4af58 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -6786,6 +6786,9 @@ public:
/// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
bool RebuildDefaultArgOrDefaultInit = false;
+ /// Whether we are initializing a C++ for-range implicit variable '__range'.
+ bool InitCXXForRangeVar = false;
+
// When evaluating immediate functions in the initializer of a default
// argument or default member initializer, this is the declaration whose
// default initializer is being evaluated and the location of the call
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp b/clang/lib/Sema/CheckExprLifetime.cpp
index 060ba3166055..150e27f8acf7 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -1341,6 +1341,8 @@ checkExprLifetimeImpl(Sema &SemaRef, const InitializedEntity *InitEntity,
}
if (IsGslPtrValueFromGslTempOwner && DiagLoc.isValid()) {
+ if (SemaRef.currentEvaluationContext().InitCXXForRangeVar)
+ return false;
SemaRef.Diag(DiagLoc, diag::warn_dangling_lifetime_pointer)
<< DiagRange;
return false;
diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 923a9e81fbd6..da97d34854ac 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -2374,6 +2374,13 @@ static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
SemaRef.ObjC().inferObjCARCLifetime(Decl))
Decl->setInvalidDecl();
+ // EnterExpressionEvaluationContext ForRangeInitContext(
+ // SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated,
+ // /*LambdaContextDecl=*/nullptr,
+ // Sema::ExpressionEvaluationContextRecord::EK_Other,
+ // SemaRef.getLangOpts().CPlusPlus23);
+ if (SemaRef.getLangOpts().CPlusPlus23)
+ SemaRef.currentEvaluationContext().InitCXXForRangeVar = true;
SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
SemaRef.FinalizeDeclaration(Decl);
SemaRef.CurContext->addHiddenDecl(Decl);
CC @cor3ntin |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As a previous comment noted, this needs a release note but I think the summary should also mention that this fixes the warning diagnostic from -Wdangling-gsl
. Maybe worth a comment in the test explaining these are verifying we don't trigger a diagnostic from -Wdangling-gsl
I like option one! Maybe a stupid question, but why can’t we use I updated (locally) the PR to address the other feedbacks and I will push it to be reviewed when I have the green light to use option 1! |
This flag will tiger subroutines to collect |
Agreed. My last commit should implement this. Let me know if something is wrong! Edit: I pushed again because I messed up with the branches, sorry! |
…s in C++23 C++23 mandates that temporaries used in range-based for loops are lifetime-extended to cover the full loop. This patch adds a check for loop variables and compiler- generated `__range` bindings to apply the correct extension. Includes test cases based on examples from CWG900/P2644R1.
Old clang tidy test failing seems flaky, locally it pass correctly. If it continue to fail I can rebase on upstream. |
C++23 mandates that temporaries used in range-based for loops are lifetime-extended
to cover the full loop. This patch adds a check for loop variables and compiler-
generated
__range
bindings to apply the correct extension.Includes test cases based on examples from CWG900/P2644R1.
Fixes #109793