[clang] [Clang][ThreadSafety] Add [[clang::coro_deferred_capabilities]] and [clang::coro_preserve_capabilities]] (PR #247797)
via cfe-commits
cfe-commits at lists.llvm.org
Wed Dec 2 06:52:20 PST 2026
https://github.com/etiennep-chromium updated https://github.com/llvm/llvm-project/pull/247797
>From f8ac3035cba24ee7ba8524291558e8c96c3393c0 Mon Sep 17 00:00:00 2001
From: Etienne Pierre-doray <etiennep at chromium.org>
Date: Tue, 1 Dec 2026 20:52:33 +0000
Subject: [PATCH] [Clang][ThreadSafety] Add
[[clang::coro_deferred_capabilities]] and
[[clang::coro_preserve_capabilities]]
Deferred/lazy coroutine calls produce coroutine objects whose body may resume
after releasing a capability or on a different thread/executor (e.g., when
stored in a local variable or container, or passed to a cross-executor API such
as `schedule_on(bg_executor, Foo())`). Checking the call against the caller's
held capability set lets caller capabilities leak across lock releases and
executor hops.
Following Clang's opt-in coroutine attribute convention (`coro_lifetimebound`,
`coro_await_elidable` / `coro_await_elidable_argument`), add two attributes so
existing `[[clang::coro_return_type]]` users remain completely unaffected:
- `[[clang::coro_deferred_capabilities]]` (`CXXRecord`): opts a coroutine
return type into direct-await capability checking under `-Wthread-safety`.
- `[[clang::coro_preserve_capabilities]]` (`ParmVar`, `InheritableParamAttr`):
marks parameters (or parameter packs) of same-context combinators (e.g.,
`when_all`, `with_timeout`, `retry`) that propagate the directly-awaited
context.
Update `ThreadSafetyAnalyzer` to check prvalue `CallExpr`s returning a
`[[clang::coro_deferred_capabilities]]` type against an empty capability set
unless the call is:
1. Directly awaited via `co_await` (walking through parens, implicit nodes,
casts, and conditional operators `?:`),
2. Passed to a `[[clang::coro_preserve_capabilities]]` parameter of a directly
awaited combinator (matching arguments via `AnyCall::forExpr` and
`llvm::zip`), or
3. Directly returned from a `[[clang::coro_wrapper]]` function whose return type
also carries `[[clang::coro_deferred_capabilities]]` (deferring the check to
the wrapper's call site).
Eagerly evaluated argument sub-expressions (such as copying a `GUARDED_BY`
member into a by-value parameter) remain checked under the caller's capability
set, and the caller's capability set is restored unchanged after checking an
un-awaited call. Cross-executor dispatch APIs require no annotation, and
because propagation runs strictly top-down from `co_await` / wrapper `return`,
un-awaited combinator calls (or combinators passed into cross-executor APIs)
still strip capabilities from their inner coroutine calls.
---
clang/docs/ReleaseNotes.md | 11 +
clang/docs/ThreadSafetyAnalysis.md | 32 ++
clang/include/clang/Basic/Attr.td | 16 +
clang/include/clang/Basic/AttrDocs.td | 75 ++++
clang/lib/Analysis/ThreadSafety.cpp | 83 ++++
...a-attribute-supported-attributes-list.test | 2 +
.../test/SemaCXX/warn-thread-safety-coro.cpp | 404 ++++++++++++++++++
7 files changed, 623 insertions(+)
create mode 100644 clang/test/SemaCXX/warn-thread-safety-coro.cpp
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index c221b0d7f0fa08..6cd67fd49e7ebb 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -503,6 +503,17 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
### Attribute Changes in Clang
+- Added `[[clang::coro_deferred_capabilities]]` (for coroutine return types)
+ and `[[clang::coro_preserve_capabilities]]` (for same-context combinator
+ parameters) for `-Wthread-safety`. Prvalue calls returning a
+ `[[clang::coro_deferred_capabilities]]` type are checked against an empty
+ capability set unless directly awaited via `co_await` (optionally through
+ `[[clang::coro_preserve_capabilities]]` combinator parameters) or directly
+ returned from a `[[clang::coro_wrapper]]` function, catching capability
+ escapes across lock releases, stored coroutine handles, and cross-executor
+ dispatch APIs while keeping eager by-value argument copies checked under the
+ caller's capabilities.
+
- Clang now properly propagates attributes on class and variable templates to their redeclarations, which will result in redeclarations not interfering with diagnostics. (#GH209812)
- Clang now recognizes the `[[gnu::flag_enum]]` attribute and treats it equivalent to `[[clang::flag_enum]]`
diff --git a/clang/docs/ThreadSafetyAnalysis.md b/clang/docs/ThreadSafetyAnalysis.md
index a3c9020aca331e..e741808b510e84 100644
--- a/clang/docs/ThreadSafetyAnalysis.md
+++ b/clang/docs/ThreadSafetyAnalysis.md
@@ -380,6 +380,38 @@ interface of a function, and should thus be placed on the function definition
(in the `.cc` or `.cpp` file) rather than on the function declaration
(in the header).
+### Coroutines (`coro_deferred_capabilities` and `coro_preserve_capabilities`)
+
+Annotating a coroutine return type with `[[clang::coro_deferred_capabilities]]`
+marks prvalue calls returning that type as deferred coroutine invocations that
+may resume after releasing a capability or on a different executor. Unless the
+call is directly awaited via `co_await` (or directly returned from a
+`[[clang::coro_wrapper]]` function whose return type also has
+`[[clang::coro_deferred_capabilities]]`), thread safety analysis checks the
+call's `REQUIRES(...)`, `RELEASE(...)`, guarded object arguments, and
+`-Wthread-safety-reference` / `-Wthread-safety-pointer` reference and pointer
+arguments against an empty capability set, leaving the caller's capability set
+unchanged. Eagerly evaluated argument sub-expressions (such as copying a
+`GUARDED_BY` field into a by-value parameter) remain checked under the caller's
+capability set.
+
+`[[clang::coro_preserve_capabilities]]` (or
+`__attribute__((coro_preserve_capabilities))`) is a parameter attribute for
+same-context coroutine combinators (such as `whenAll`, `withTimeout`, or
+`retry`). When the combinator call itself is directly awaited, the
+directly-awaited capability context propagates into arguments bound to annotated
+parameters. Cross-executor dispatch functions (such as `scheduleOn`) omit the
+attribute so caller capabilities are stripped automatically.
+
+```c++
+template <typename T>
+class [[clang::coro_return_type, clang::coro_deferred_capabilities]] Task { ... };
+
+template <typename... Ts>
+Awaitable<...> whenAll(
+ [[clang::coro_preserve_capabilities]] Task<Ts>... tasks);
+```
+
### RETURN_CAPABILITY(c)
*Previously*: `LOCK_RETURNED`
diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td
index 806debfe13cda8..c695ea0d4a93b2 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1411,6 +1411,22 @@ def CoroAwaitElidableArgument : InheritableAttr {
let SimpleHandler = 1;
}
+def CoroDeferredCapabilities : InheritableAttr {
+ let Spellings = [Clang<"coro_deferred_capabilities">];
+ let Subjects = SubjectList<[CXXRecord]>;
+ let LangOpts = [CPlusPlus];
+ let Documentation = [CoroDeferredCapabilitiesDoc];
+ let SimpleHandler = 1;
+}
+
+def CoroPreserveCapabilities : InheritableParamAttr {
+ let Spellings = [Clang<"coro_preserve_capabilities">];
+ let Subjects = SubjectList<[ParmVar]>;
+ let LangOpts = [CPlusPlus];
+ let Documentation = [CoroPreserveCapabilitiesDoc];
+ let SimpleHandler = 1;
+}
+
// OSObject-based attributes.
def OSConsumed : InheritableParamAttr {
let Spellings = [Clang<"os_consumed">];
diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td
index 5ff48c25d4e7db..8bedd097321ec6 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -10419,6 +10419,81 @@ Task<void> example3() {
}];
}
+def CoroDeferredCapabilitiesDoc : Documentation {
+ let Category = DocCatDecl;
+ let Content = [{
+The `[[clang::coro_deferred_capabilities]]` attribute applies to a C++
+coroutine return type (class or struct) whose execution may be deferred—for
+example, a lazy task type that may resume after releasing a capability or on a
+different thread or executor.
+
+When `-Wthread-safety` analyzes a prvalue call expression returning a
+`[[clang::coro_deferred_capabilities]]` type, it checks the call against an
+**empty** capability set (and leaves the caller's capability set unchanged)
+unless the call is:
+
+- directly awaited via `co_await`,
+- passed to a `[[clang::coro_preserve_capabilities]]` parameter of a directly
+ awaited same-context combinator, or
+- directly returned from a `[[clang::coro_wrapper]]` function whose return type
+ is also annotated with `[[clang::coro_deferred_capabilities]]`.
+
+Eagerly evaluated argument sub-expressions (such as copying a `guarded_by`
+field into a by-value parameter) remain checked under the caller's normal
+capability set.
+}];
+}
+
+def CoroPreserveCapabilitiesDoc : Documentation {
+ let Category = DocCatDecl;
+ let Content = [{
+The `[[clang::coro_preserve_capabilities]]` parameter attribute works with
+`[[clang::coro_deferred_capabilities]]` and `-Wthread-safety`.
+
+Placing `[[clang::coro_preserve_capabilities]]` on a parameter (or parameter
+pack) of a same-context coroutine combinator (such as `when_all`,
+`with_timeout`, or `retry`) propagates the directly-awaited capability context
+to the argument expression whenever the combinator call itself is directly
+awaited (or directly returned from a `[[clang::coro_wrapper]]` function
+returning a `[[clang::coro_deferred_capabilities]]` type). Cross-executor APIs
+(such as `schedule_on`) simply omit the attribute.
+
+Example:
+
+```c++
+template <typename T>
+class [[clang::coro_return_type, clang::coro_deferred_capabilities]] Task { ... };
+
+// Same-context combinator: preserves caller capabilities when directly awaited.
+template <typename... Ts>
+Awaitable<...> when_all([[clang::coro_preserve_capabilities]] Task<Ts>... tasks);
+
+// Cross-executor dispatch: omits attribute, so caller capabilities are stripped.
+template <typename T>
+Awaitable<T> schedule_on(Executor *exec, Task<T> task);
+
+class Worker {
+ Mutex mu;
+ std::string data GUARDED_BY(mu);
+
+ Task<void> work() REQUIRES(mu);
+ static Task<void> by_val(std::string s);
+ static Task<void> by_ref(const std::string &s);
+
+ Task<void> run(Executor *bg) REQUIRES(mu) {
+ co_await work(); // OK: directly awaited
+ co_await when_all(work(), by_ref(data)); // OK: preserved by when_all
+ co_await schedule_on(bg, by_val(data)); // OK: eager copy under mu
+ co_await schedule_on(bg, work()); // Warning: requires mu
+ co_await schedule_on(bg, by_ref(data)); // Warning: by-ref requires mu
+ auto t = work(); // Warning: not directly awaited
+ co_await std::move(t);
+ }
+};
+```
+}];
+}
+
def CountedByDocs : Documentation {
let Category = DocCatField;
let Heading = "counted_by";
diff --git a/clang/lib/Analysis/ThreadSafety.cpp b/clang/lib/Analysis/ThreadSafety.cpp
index 192d6a2e1b1d18..e331ca30ffc769 100644
--- a/clang/lib/Analysis/ThreadSafety.cpp
+++ b/clang/lib/Analysis/ThreadSafety.cpp
@@ -21,6 +21,7 @@
#include "clang/AST/DeclGroup.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
+#include "clang/AST/IgnoreExpr.h"
#include "clang/AST/OperationKinds.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/StmtVisitor.h"
@@ -30,6 +31,7 @@
#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
#include "clang/Analysis/Analyses/ThreadSafetyUtil.h"
#include "clang/Analysis/AnalysisDeclContext.h"
+#include "clang/Analysis/AnyCall.h"
#include "clang/Analysis/CFG.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/LLVM.h"
@@ -40,6 +42,7 @@
#include "llvm/ADT/ImmutableMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/ScopeExit.h"
+#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Allocator.h"
@@ -1242,6 +1245,10 @@ class ThreadSafetyAnalyzer {
LocalVariableMap LocalVarMap;
// Maps constructed objects to `this` placeholder prior to initialization.
llvm::SmallDenseMap<const Expr *, til::LiteralPtr *> ConstructedObjects;
+ // Calls directly awaited via `co_await` (including through
+ // [[clang::coro_preserve_capabilities]] combinator parameters) or directly
+ // returned from a [[clang::coro_wrapper]] function.
+ llvm::SmallPtrSet<const CallExpr *, 4> DirectlyAwaitedCalls;
FactManager FactMan;
std::vector<CFGBlockInfo> BlockInfo;
@@ -1298,6 +1305,7 @@ class ThreadSafetyAnalyzer {
}
void runAnalysis(AnalysisDeclContext &AC);
+ void collectDirectlyAwaitedCalls(const CFG *CFGraph);
void warnIfMutexNotHeld(const FactSet &FSet, const NamedDecl *D,
const Expr *Exp, AccessKind AK, Expr *MutexExp,
@@ -2539,7 +2547,23 @@ void BuildLockset::examineArguments(const FunctionDecl *FD,
}
}
+static bool hasDeferredCapabilities(QualType QT) {
+ const CXXRecordDecl *RD = QT->getAsCXXRecordDecl();
+ return RD && RD->hasAttr<CoroDeferredCapabilitiesAttr>();
+}
+
void BuildLockset::VisitCallExpr(const CallExpr *Exp) {
+ const bool ClearCaps = Exp->isPRValue() &&
+ hasDeferredCapabilities(Exp->getType()) &&
+ !Analyzer->DirectlyAwaitedCalls.contains(Exp);
+ FactSet SavedFSet;
+ if (ClearCaps)
+ std::swap(FSet, SavedFSet);
+ llvm::scope_exit RestoreFSet([&] {
+ if (ClearCaps)
+ FSet = std::move(SavedFSet);
+ });
+
if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
const auto *ME = dyn_cast<MemberExpr>(CE->getCallee());
// ME can be null when calling a method pointer
@@ -2842,6 +2866,61 @@ static bool neverReturns(const CFGBlock *B) {
return false;
}
+static void
+markDirectlyAwaitedCalls(const Expr *E,
+ llvm::SmallPtrSetImpl<const CallExpr *> &Calls) {
+ E = IgnoreExprNodes(E, IgnoreParensSingleStep, IgnoreImplicitSingleStep,
+ IgnoreCastsSingleStep);
+ if (!E)
+ return;
+ if (const auto *Cond = dyn_cast<AbstractConditionalOperator>(E)) {
+ markDirectlyAwaitedCalls(Cond->getTrueExpr(), Calls);
+ markDirectlyAwaitedCalls(Cond->getFalseExpr(), Calls);
+ return;
+ }
+ if (const auto *CE = dyn_cast<CallExpr>(E))
+ Calls.insert(CE);
+
+ std::optional<AnyCall> AC = AnyCall::forExpr(E);
+ if (!AC)
+ return;
+ auto Args = AC->arguments();
+ ArrayRef<const Expr *> ArgRef = Args;
+ if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(AC->getDecl());
+ AC->getKind() == AnyCall::Function && MD &&
+ MD->isImplicitObjectMemberFunction() && !ArgRef.empty())
+ ArgRef = ArgRef.drop_front();
+
+ for (auto [Param, Arg] : llvm::zip(AC->parameters(), ArgRef)) {
+ if (Param->hasAttr<CoroPreserveCapabilitiesAttr>())
+ markDirectlyAwaitedCalls(Arg, Calls);
+ }
+}
+
+void ThreadSafetyAnalyzer::collectDirectlyAwaitedCalls(const CFG *CFGraph) {
+ const bool IsCoro = CurrentFunction && isa_and_nonnull<CoroutineBodyStmt>(
+ CurrentFunction->getBody());
+ const bool IsCoroWrapper =
+ CurrentFunction && CurrentFunction->hasAttr<CoroWrapperAttr>() &&
+ hasDeferredCapabilities(CurrentFunction->getReturnType());
+ if (!IsCoro && !IsCoroWrapper)
+ return;
+
+ for (const CFGBlock *B : *CFGraph) {
+ for (const CFGElement &E : *B) {
+ std::optional<CFGStmt> CS = E.getAs<CFGStmt>();
+ if (!CS)
+ continue;
+ if (const auto *CA = dyn_cast<CoawaitExpr>(CS->getStmt());
+ CA && !CA->isImplicit())
+ markDirectlyAwaitedCalls(CA->getOperand(), DirectlyAwaitedCalls);
+ else if (const auto *RS = dyn_cast<ReturnStmt>(CS->getStmt());
+ IsCoroWrapper && RS)
+ markDirectlyAwaitedCalls(RS->getRetValue(), DirectlyAwaitedCalls);
+ }
+ }
+}
+
/// Check a function's CFG for thread-safety violations.
///
/// We traverse the blocks in the CFG, compute the set of mutexes that are held
@@ -2896,6 +2975,10 @@ void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
// Fill in source locations for all CFGBlocks.
findBlockLocations(CFGraph, SortedGraph, BlockInfo);
+ // Identify directly-awaited coroutine calls (and direct returns inside
+ // [[clang::coro_wrapper]] functions) that inherit caller capabilities.
+ collectDirectlyAwaitedCalls(CFGraph);
+
CapExprSet ExclusiveLocksAcquired;
CapExprSet SharedLocksAcquired;
CapExprSet LocksReleased;
diff --git a/clang/test/Misc/pragma-attribute-supported-attributes-list.test b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
index 452406bcaba9dd..61911917854cee 100644
--- a/clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -66,9 +66,11 @@
// CHECK-NEXT: CoopMatrixType (SubjectMatchRule_type_alias, SubjectMatchRule_variable, SubjectMatchRule_variable_is_parameter, SubjectMatchRule_field)
// CHECK-NEXT: CoroAwaitElidable (SubjectMatchRule_record)
// CHECK-NEXT: CoroAwaitElidableArgument (SubjectMatchRule_variable_is_parameter)
+// CHECK-NEXT: CoroDeferredCapabilities (SubjectMatchRule_record)
// CHECK-NEXT: CoroDisableLifetimeBound (SubjectMatchRule_function)
// CHECK-NEXT: CoroLifetimeBound (SubjectMatchRule_record)
// CHECK-NEXT: CoroOnlyDestroyWhenComplete (SubjectMatchRule_record)
+// CHECK-NEXT: CoroPreserveCapabilities (SubjectMatchRule_variable_is_parameter)
// CHECK-NEXT: CoroReturnType (SubjectMatchRule_record)
// CHECK-NEXT: CoroWrapper (SubjectMatchRule_function)
// CHECK-NEXT: DLLExport (SubjectMatchRule_function, SubjectMatchRule_variable, SubjectMatchRule_record, SubjectMatchRule_objc_interface)
diff --git a/clang/test/SemaCXX/warn-thread-safety-coro.cpp b/clang/test/SemaCXX/warn-thread-safety-coro.cpp
new file mode 100644
index 00000000000000..1115d8dc255870
--- /dev/null
+++ b/clang/test/SemaCXX/warn-thread-safety-coro.cpp
@@ -0,0 +1,404 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -Wno-c++23-lambda-attributes -Wthread-safety -Wthread-safety-pointer -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -Wno-c++23-lambda-attributes -Wthread-safety -Wthread-safety-pointer -Wthread-safety-beta -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++23 -Wthread-safety -Wthread-safety-pointer -verify %s
+
+#include "Inputs/std-coroutine.h"
+
+#define CAPABILITY(x) __attribute__((capability(x)))
+#define SCOPED_CAPABILITY __attribute__((scoped_lockable))
+#define GUARDED_BY(x) __attribute__((guarded_by(x)))
+#define PT_GUARDED_BY(x) __attribute__((pt_guarded_by(x)))
+#define REQUIRES(...) __attribute__((requires_capability(__VA_ARGS__)))
+#define REQUIRES_SHARED(...) \
+ __attribute__((requires_shared_capability(__VA_ARGS__)))
+#define ACQUIRE(...) __attribute__((acquire_capability(__VA_ARGS__)))
+#define RELEASE(...) __attribute__((release_capability(__VA_ARGS__)))
+#define EXCLUDES(...) __attribute__((locks_excluded(__VA_ARGS__)))
+#define CORO_PRESERVE_CAPABILITIES [[clang::coro_preserve_capabilities]]
+#define CORO_WRAPPER [[clang::coro_wrapper]]
+
+class CAPABILITY("mutex") Mutex {
+ public:
+ void Lock() ACQUIRE() {}
+ void Unlock() RELEASE() {}
+};
+
+class CAPABILITY("context") ExecutionContext {};
+
+class SCOPED_CAPABILITY ScopedContextGuard {
+ public:
+ explicit ScopedContextGuard(const ExecutionContext& c) ACQUIRE(c) {}
+ ~ScopedContextGuard() RELEASE() {}
+};
+
+struct Data {};
+
+template <typename T>
+struct Awaitable {
+ bool await_ready() const noexcept { return false; }
+ void await_suspend(std::coroutine_handle<>) const noexcept {}
+ T await_resume() const noexcept { return {}; }
+};
+
+template <typename T>
+struct [[clang::coro_return_type, clang::coro_deferred_capabilities]] Task {
+ struct promise_type {
+ Task get_return_object() { return {}; }
+ std::suspend_always initial_suspend() noexcept { return {}; }
+ std::suspend_always final_suspend() noexcept { return {}; }
+ void return_value(T) {}
+ void unhandled_exception() {}
+ // Verify await_transform preserves direct-await recognition.
+ template <typename A>
+ A&& await_transform(A&& a) noexcept {
+ return static_cast<A&&>(a);
+ }
+ };
+ Task() = default;
+ Task(Task&&) = default;
+ Task& operator=(Task&&) = default;
+ Task(const Task&) = delete;
+ Awaitable<T> operator co_await() && noexcept { return {}; }
+#if __cplusplus >= 202302L
+ template <typename Self>
+ Awaitable<T> FluentWrap(CORO_PRESERVE_CAPABILITIES this Self&&) noexcept {
+ return {};
+ }
+#endif
+};
+
+// [[clang::coro_return_type]] without [[clang::coro_deferred_capabilities]]:
+// left untouched by the direct-await rule for backward compatibility.
+template <typename T>
+struct [[clang::coro_return_type]] PlainTask : Awaitable<T> {
+ struct promise_type {
+ PlainTask get_return_object() { return {}; }
+ std::suspend_always initial_suspend() noexcept { return {}; }
+ std::suspend_always final_suspend() noexcept { return {}; }
+ void return_value(T) {}
+ void unhandled_exception() {}
+ };
+};
+
+struct Executor {};
+
+// Cross-executor dispatch: NO annotation needed; caller capabilities are
+// stripped automatically because the Task is not directly awaited.
+template <typename T>
+Awaitable<T> ScheduleOn(Executor* exec, Task<T> task);
+
+// Same-context combinators opt in with [[clang::coro_preserve_capabilities]].
+template <typename A>
+Awaitable<int> Wrap(CORO_PRESERVE_CAPABILITIES A&& task);
+
+template <typename T>
+Task<T> WrapTask(CORO_PRESERVE_CAPABILITIES Task<T> task);
+
+template <typename... Ts>
+Awaitable<int> WhenAll(CORO_PRESERVE_CAPABILITIES Ts&&... tasks);
+
+// Selective annotation: only parameter 0 preserves caller capabilities.
+Awaitable<int> Mixed(CORO_PRESERVE_CAPABILITIES Task<int> preserved,
+ Task<int> unannotated);
+
+// Redeclaration inheritance (InheritableParamAttr).
+Awaitable<int> WrapRedecl(CORO_PRESERVE_CAPABILITIES Task<int> task);
+Awaitable<int> WrapRedecl(Task<int> task);
+
+// GNU spelling.
+Awaitable<int> WrapGnu(
+ __attribute__((coro_preserve_capabilities)) Task<int> task);
+
+// Combinator class constructor + member + operator + non-member operator.
+struct WrapCtor : Awaitable<int> {
+ explicit WrapCtor(CORO_PRESERVE_CAPABILITIES Task<int> task);
+};
+
+struct UnannotatedCtor : Awaitable<int> {
+ explicit UnannotatedCtor(Task<int> task);
+};
+
+struct CombinatorObj {
+ Awaitable<int> Run(CORO_PRESERVE_CAPABILITIES Task<int> task);
+ Awaitable<int> operator()(CORO_PRESERVE_CAPABILITIES Task<int> task);
+};
+
+Awaitable<int> operator|(CombinatorObj&,
+ CORO_PRESERVE_CAPABILITIES Task<int> task);
+
+#if __cplusplus >= 202302L
+struct DeducingThisCombinator {
+ template <typename Self>
+ Awaitable<int> Run(this Self&&, CORO_PRESERVE_CAPABILITIES Task<int> task);
+ template <typename Self>
+ Awaitable<int> operator()(this Self&&,
+ CORO_PRESERVE_CAPABILITIES Task<int> task);
+};
+
+struct StaticOpCombinator {
+ static Awaitable<int> operator()(CORO_PRESERVE_CAPABILITIES Task<int> task);
+};
+#endif
+
+// Invalid attribute targets.
+[[clang::coro_deferred_capabilities]] void BadDeferredFunc(); // expected-warning {{'clang::coro_deferred_capabilities' attribute only applies to classes}}
+[[clang::coro_preserve_capabilities]] void BadFunc(); // expected-warning {{'clang::coro_preserve_capabilities' attribute only applies to parameters}}
+struct BadStruct {
+ [[clang::coro_preserve_capabilities]] int field; // expected-warning {{'clang::coro_preserve_capabilities' attribute only applies to parameters}}
+};
+
+struct TaskVec {
+ void push_back(Task<int>);
+};
+
+void UnannotatedHelper(Task<int>);
+
+// Free helpers.
+template <typename T>
+Task<int> ByVal(T);
+template <typename T>
+Task<int> ByRef(const T&);
+template <typename T>
+Task<int> ByMutRef(T&);
+template <typename T>
+Task<int> ByPtr(const T*);
+Task<int> NoArgs();
+
+int global_guarded __attribute__((guarded_var)) = 0;
+
+struct Helper {
+ Task<int> Coro();
+};
+
+struct Functor {
+ Mutex* mu;
+ Task<int> operator()() REQUIRES(mu);
+};
+
+struct PlainFunctor {
+ Task<int> operator()();
+};
+
+class Worker {
+ Mutex mu_;
+ ExecutionContext ctx_;
+ Data data_ GUARDED_BY(mu_);
+ Data ctx_data_ GUARDED_BY(ctx_);
+ int count_ GUARDED_BY(mu_) = 0;
+ int* guarded_ptr_ GUARDED_BY(mu_) = nullptr;
+ int* pt_guarded_ptr_ PT_GUARDED_BY(mu_) = nullptr;
+ Helper helper_ GUARDED_BY(mu_);
+ Helper* helper_ptr_ GUARDED_BY(mu_) = nullptr;
+ Helper* pt_helper_ptr_ PT_GUARDED_BY(mu_) = nullptr;
+ PlainFunctor guarded_functor_ GUARDED_BY(mu_);
+
+ Task<int> GuardedCoro() REQUIRES(mu_);
+ Task<int> SharedCoro() REQUIRES_SHARED(mu_);
+ Task<int> AcquireCoro() ACQUIRE(mu_);
+ Task<int> ReleaseCoro() RELEASE(mu_);
+ Task<int> ExcludesCoro() EXCLUDES(mu_);
+ Task<int> ContextCoro() REQUIRES(ctx_);
+ PlainTask<int> PlainCoro() REQUIRES(mu_);
+ Data GetData() REQUIRES(mu_);
+
+ // [[clang::coro_wrapper]] direct return inherits the wrapper's capabilities.
+ CORO_WRAPPER Task<int> ValidWrapper() REQUIRES(mu_) {
+ return GuardedCoro();
+ }
+ CORO_WRAPPER Task<int> ValidWrapperCond(bool c) REQUIRES(mu_) {
+ return c ? GuardedCoro() : ByRef(data_);
+ }
+ CORO_WRAPPER Task<int> BadWrapperMissingRequires() {
+ return GuardedCoro(); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ }
+ CORO_WRAPPER Task<int> BadWrapperStoredLocal() REQUIRES(mu_) {
+ auto t = GuardedCoro(); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ return t;
+ }
+ CORO_WRAPPER Awaitable<int> BadWrapperNonCoroReturn() REQUIRES(mu_) {
+ return Wrap(GuardedCoro()); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ }
+ CORO_WRAPPER Task<int> RefWrapper(const Data& d) {
+ return ByRef(d);
+ }
+ CORO_WRAPPER Task<int> NestedLambdaInsideWrapper() REQUIRES(mu_) {
+ auto lam = [this] CORO_WRAPPER () -> Task<int> {
+ return GuardedCoro(); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ };
+ (void)lam;
+ return GuardedCoro();
+ }
+
+ Task<int> TestValid(Executor* bg, bool cond) REQUIRES(mu_) {
+ // Direct co_await (including await_transform, operator co_await, and ?:).
+ co_await GuardedCoro();
+ co_await SharedCoro();
+ co_await ValidWrapper();
+ co_await RefWrapper(data_);
+ co_await ByRef(data_);
+ co_await (cond ? GuardedCoro() : SharedCoro());
+ co_await ByVal(co_await GuardedCoro());
+
+ // Capture initializer inside a lambda is evaluated in this coroutine.
+ auto lam = [x = co_await GuardedCoro()] { return x; };
+ (void)lam;
+
+ // Directly awaited same-context combinators preserve caller capabilities.
+ co_await Wrap(GuardedCoro());
+ co_await WrapRedecl(GuardedCoro());
+ co_await WrapGnu(GuardedCoro());
+ co_await Mixed(GuardedCoro(), NoArgs());
+ co_await WhenAll(GuardedCoro(), SharedCoro(), ByRef(data_));
+ co_await Wrap(WhenAll(GuardedCoro(), SharedCoro()));
+ co_await WrapCtor(GuardedCoro());
+ CombinatorObj comb;
+ co_await comb.Run(GuardedCoro());
+ co_await comb(GuardedCoro());
+ co_await (comb | GuardedCoro());
+#if __cplusplus >= 202302L
+ DeducingThisCombinator dc;
+ co_await dc.Run(GuardedCoro());
+ co_await dc(GuardedCoro());
+ StaticOpCombinator sc;
+ co_await sc(GuardedCoro());
+ co_await GuardedCoro().FluentWrap();
+#endif
+
+ // By-value copies of guarded members execute eagerly under caller's mu_.
+ co_await ScheduleOn(bg, ByVal(data_));
+ co_await ScheduleOn(bg, ByVal(count_));
+ co_await ScheduleOn(bg, ByVal(global_guarded));
+ co_await ScheduleOn(bg, ByVal(GetData()));
+
+ // Dynamic vector fan-out of free by-value helpers works cleanly.
+ TaskVec vec;
+ vec.push_back(ByVal(data_));
+
+ // Plain unguarded local passed by reference/pointer is OK.
+ Data local;
+ co_await ScheduleOn(bg, ByRef(local));
+ co_await ScheduleOn(bg, ByPtr(&local));
+
+ // Pointer itself is GUARDED_BY(mu_) (copied eagerly), pointee unguarded.
+ co_await ScheduleOn(bg, ByPtr(guarded_ptr_));
+ co_await ScheduleOn(bg, helper_ptr_->Coro());
+
+ // EXCLUDES(mu_) succeeds under empty capability set.
+ co_await ScheduleOn(bg, ExcludesCoro());
+
+ // [[clang::coro_return_type]] without [[clang::coro_deferred_capabilities]]
+ // is unaffected.
+ auto plain = PlainCoro();
+ co_await std::move(plain);
+
+ // Caller's mu_ remains held after ScheduleOn.
+ co_return count_;
+ }
+
+ Task<int> TestInvalidWithoutLock(Executor* bg) {
+ // Eager copy of guarded member still requires caller to hold mu_.
+ co_await ScheduleOn(bg, ByVal(data_)); // expected-warning {{reading variable 'data_' requires holding mutex 'mu_'}}
+ co_await ScheduleOn(bg, ByVal(count_)); // expected-warning {{reading variable 'count_' requires holding mutex 'mu_'}}
+ co_await GuardedCoro(); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ co_return 0;
+ }
+
+ Task<int> TestCrossExecutorAndEscapes(Executor* bg, bool cond) REQUIRES(mu_) {
+ // Cross-executor dispatch (no attribute required on ScheduleOn).
+ co_await ScheduleOn(bg, GuardedCoro()); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ co_await ScheduleOn(bg, SharedCoro()); // expected-warning {{calling function 'SharedCoro' requires holding mutex 'mu_'}}
+ co_await ScheduleOn(bg, ValidWrapper()); // expected-warning {{calling function 'ValidWrapper' requires holding mutex 'mu_'}}
+ co_await ScheduleOn(bg, RefWrapper(data_)); // expected-warning {{passing variable 'data_' by reference requires holding mutex 'mu_'}}
+ co_await ScheduleOn(bg, cond ? GuardedCoro() : NoArgs()); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+
+ // Nested same-context combinator inside ScheduleOn is NOT directly awaited.
+ co_await ScheduleOn(bg, WrapTask(GuardedCoro())); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ co_await WhenAll(GuardedCoro(),
+ ScheduleOn(bg, GuardedCoro())); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ co_await Mixed(GuardedCoro(), GuardedCoro()); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ co_await UnannotatedCtor(GuardedCoro()); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+
+ // Stored local (init, reassignment, stored combinator, vector, helper).
+ auto t1 = GuardedCoro(); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ co_await std::move(t1);
+
+ Task<int> t2;
+ t2 = GuardedCoro(); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ co_await ScheduleOn(bg, std::move(t2));
+
+ auto w = Wrap(GuardedCoro()); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ co_await std::move(w);
+
+ auto wc = WrapCtor(GuardedCoro()); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ co_await std::move(wc);
+#if __cplusplus >= 202302L
+ auto fw = GuardedCoro().FluentWrap(); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ co_await std::move(fw);
+#endif
+
+ TaskVec vec;
+ vec.push_back(GuardedCoro()); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ vec.push_back(ByRef(data_)); // expected-warning {{passing variable 'data_' by reference requires holding mutex 'mu_'}}
+
+ UnannotatedHelper(GuardedCoro()); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ co_return count_;
+ }
+
+ Task<int> TestUnlockBeforeAwait() {
+ mu_.Lock();
+ auto t = GuardedCoro(); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ mu_.Unlock();
+ co_return co_await std::move(t);
+ }
+
+ void TestNonCoroutineCaller(Executor* bg) REQUIRES(mu_) {
+ (void)ScheduleOn(bg, GuardedCoro()); // expected-warning {{calling function 'GuardedCoro' requires holding mutex 'mu_'}}
+ (void)ScheduleOn(bg, ByVal(data_));
+ }
+
+ Task<int> TestReferenceAndPointerArgs(Executor* bg) REQUIRES(mu_) {
+ co_await ScheduleOn(bg, ByRef(data_)); // expected-warning {{passing variable 'data_' by reference requires holding mutex 'mu_'}}
+ co_await ScheduleOn(bg, ByMutRef(data_)); // expected-warning {{passing variable 'data_' by reference requires holding mutex 'mu_'}}
+ co_await ScheduleOn(bg, ByRef(count_)); // expected-warning {{passing variable 'count_' by reference requires holding mutex 'mu_'}}
+ co_await ScheduleOn(bg, ByRef(global_guarded)); // expected-warning {{reading variable 'global_guarded' requires holding any mutex}}
+ co_await ScheduleOn(bg, ByPtr(&data_)); // expected-warning {{passing pointer to variable 'data_' requires holding mutex 'mu_'}}
+ co_await ScheduleOn(bg, ByPtr(pt_guarded_ptr_)); // expected-warning {{passing pointer 'pt_guarded_ptr_' requires holding mutex 'mu_'}}
+ co_await ScheduleOn(bg, ByRef(*pt_guarded_ptr_)); // expected-warning {{passing the value that 'pt_guarded_ptr_' points to by reference requires holding mutex 'mu_'}}
+
+ const Data& alias = data_;
+ co_await ScheduleOn(bg, ByRef(alias)); // expected-warning {{passing variable 'data_' by reference requires holding mutex 'mu_'}}
+ co_return count_;
+ }
+
+ Task<int> TestGuardedObjectAndFunctor(Executor* bg,
+ Task<int> (*fp)() REQUIRES(mu_))
+ REQUIRES(mu_) {
+ co_await ScheduleOn(bg, helper_.Coro()); // expected-warning {{reading variable 'helper_' requires holding mutex 'mu_'}}
+ co_await ScheduleOn(bg, pt_helper_ptr_->Coro()); // expected-warning {{reading the value pointed to by 'pt_helper_ptr_' requires holding mutex 'mu_'}}
+ co_await ScheduleOn(bg, guarded_functor_()); // expected-warning {{reading variable 'guarded_functor_' requires holding mutex 'mu_'}}
+ Functor f{&mu_};
+ co_await ScheduleOn(bg, f()); // expected-warning {{calling function 'operator()' requires holding mutex 'f.mu'}}
+ co_await ScheduleOn(bg, fp()); // expected-warning {{calling function 'fp' requires holding mutex 'mu_'}}
+ co_return count_;
+ }
+
+ Task<int> TestAcquireReleaseDoesNotMutateCaller(Executor* bg) {
+ co_await ScheduleOn(bg, AcquireCoro());
+ co_return count_; // expected-warning {{reading variable 'count_' requires holding mutex 'mu_'}}
+ }
+
+ Task<int> TestReleaseCheckedAgainstEmpty(Executor* bg) REQUIRES(mu_) {
+ co_await ScheduleOn(bg, ReleaseCoro()); // expected-warning {{releasing mutex 'mu_' that was not held}}
+ co_return count_;
+ }
+
+ Task<int> TestScopedCustomCapability(Executor* bg) {
+ ScopedContextGuard guard(ctx_);
+ co_await ContextCoro();
+ co_await Wrap(ContextCoro());
+ co_await ScheduleOn(bg, ByVal(ctx_data_));
+ co_await ScheduleOn(bg, ContextCoro()); // expected-warning {{calling function 'ContextCoro' requires holding context 'ctx_'}}
+ co_await ScheduleOn(bg, ByRef(ctx_data_)); // expected-warning {{passing variable 'ctx_data_' by reference requires holding context 'ctx_'}}
+ co_return 0;
+ }
+};
More information about the cfe-commits
mailing list