[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
martinboehme wrote:
> @martinboehme Could you explain how that is any different from this?
>
> ```
> #include
> #include
>
> bool TryInsert(std::vector& v, std::string&& s) {
> if (some_condition()) { return false; }
> v.push_back(std::move(s));
> return true;
> }
>
> std::string foo(std::vector& v, std::string&& s) {
> if (!TryInsert(v, std::move(s))) {
> return std::move(s); // warning: 's' used after it was moved
> [bugprone-use-after-move]
> }
> return {};
> }
> ```
You mean how is this different from the example I posted earlier? Quoting it
again:
```cxx
SomeMoveableType obj;
void foo(SomeMoveableType &&, SomeOtherType);
// Obviously a contrived example, but you get the point
foo(std::move(obj), obj.operation());
```
One difference is that `TryInsert` in your example has "maybe move" semantics
(it might move, or it might not, similar to `try_emplace()`). But that's not
the decisive difference here.
The key line in my example is this one:
```cxx
foo(std::move(obj), obj.operation());
```
Note how this uses `obj` in two arguments to the same function.
If the check assumed that `std::move(obj)` already leaves `obj` in a moved-from
state, then it would need to flag `obj.operation()` as a use-after-move. But
the check knows that the move only happens once `foo()` starts executing, so
`obj.operation()` is guaranteed to be evaluated before the move, and hence it
is not a use-after-move[^1].
Now let's look at a similar example but with a user-defined invalidation
function. We'll assume
[`close(2)`](https://pubs.opengroup.org/onlinepubs/009604499/functions/close.html)
has been marked as an invalidation function.
```cxx
int fd = open(...);
void foo(int err, ssize_t bytes_written);
foo(close(fd), write(fd, ...));
```
Observations:
- This is a synthetic example -- I'm not sure what purpose this would serve.
But I assume this kind of pattern could come up in real code with other
invalidation functions.
- This is an "use after invalidation". The order in which function arguments
are evaluated is unspecified, so we have to assume pessimistically that
`close(fd)` (the invalidation) is evaluated before `write(fd, ...)` (the use).
- The check does not currently flag this use after invalidation because it uses
the same logic as for `std::move` and hence concludes, erroneously, that the
invalidation only happens once `foo()` starts executing.
> It seems to me the crux of your argument...
>
> > sooner or later someone is going to ~configure an invalidation function~
> > _compose an outer function_ that does return a value, will use that value
> > in an expression, and be mightily confused about why the check doesn't
> > understand when the invalidation happens.
>
> ...applies ~verbatim to situations with `std::move` and `std::forward` too,
> no?
I'm not sure exactly what you mean here (particularly with respect to the
"compose an outer function"), but I hope I've made it clear above how
`std::move` and `std::forward` are different from user-defined invalidation
functions.
> > I realize this is often not an issue in practice
>
> This is important, and has been our guiding principle here. The reality is
> this check (and the typical tidy in general) has always had rough edges and
> been inherently limited in what it can do.
Definitely. (I'm the original author of bugprone-use-after-move and am
painfully aware of its limitations.)
However, we accept these limitations because they are hard to overcome. The
issue I point out above is not hard to overcome at all: `std::move` and
`std::forward` should continue to determine the `moving-call` using [this
matcher](https://github.com/llvm/llvm-project/blob/a95a9465bfd261f7b7a464d79336faa74af780c0/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp#L508),
whereas user-defined invalidation functions should simply consider the
`moving-call` to be identical to the `call-move`[^2]. (IOW, we should be doing
_less_ work for user-defined invalidation functions!)
My wider point is that this illustrates how the semantics of `std::move` and
`std::forward` are different from user-defined invalidation functions and that
these should therefore be handled by a different check (which would internally
reuse almost all of the implementation).
> All that said, though, I'm not really opposing you: if you'd like to make the
> check more precise, or rename it more accurately, and others are on board --
> I have no particular opposition. I've done what I can to improve it so far,
> and I'll be happy to see contributors improve the check further.
I unfortunately currently can't devote the time to contributing to the check. I
realize it's on me that I didn't notice this PR while it was open and voice my
concerns at the time. I do believe that the status quo is unsatisfactory, and I
hope that I've explained why.
[^1]: C++ doesn't define the order in which function arguments are
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
higher-performance wrote:
@martinboehme Could you explain how that is any different from this?
```
#include
#include
bool TryInsert(std::vector& v, std::string&& s) {
if (some_condition()) { return false; }
v.push_back(std::move(s));
return true;
}
std::string foo(std::vector& v, std::string&& s) {
if (!TryInsert(v, std::move(s))) {
return std::move(s); // warning: 's' used after it was moved
[bugprone-use-after-move]
}
return {};
}
```
It seems to me the crux of your argument...
> sooner or later someone is going to ~configure an invalidation function~
> _compose an outer function_ that does return a value, will use that value in
> an expression, and be mightily confused about why the check doesn't
> understand when the invalidation happens.
...applies ~verbatim to situations with `std::move` and `std::forward` too, no?
---
> I realize this is often not an issue in practice
This is important, and has been our guiding principle here. The reality is this
check (and the typical tidy in general) has always had rough edges and been
inherently limited in what it can do. Tidies are improved incrementally after
actual circumstances arise commonly enough to warrant it. (See the
`try_emplace` hack in this tidy, for example.) They are never going to be
perfect, or even as precise as a compiler -- nor should they be expected to be.
Perfect is the enemy of good here.
---
All that said, though, I'm not really opposing you: if you'd like to make the
check more precise, or rename it more accurately, and others are on board -- I
have no particular opposition. I've done what I can to improve it so far, and
I'll be happy to see contributors improve the check further.
https://github.com/llvm/llvm-project/pull/170346
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
martinboehme wrote: @higher-performance > Yes, these were explicitly specified. The error messages themselves aren't > necessarily confusing, it's just that the name of the check also shows up, > and people assume there has to be a move because the name of the check has > move in it, when the invalidation occurs due to something else like close() > or free(). Exactly. We have an internal configuration where `close()` is configured as one of the invalidation functions, and the developer encountering the error message got confused because "bugprone-use-after-move" has "move" in it, yet they didn't see a move in their code. @vbvictor > I'm -1 on separating this checks because we essentially will duplicate a huge > portion of logic into multiple places which can double the time of analysis Separating the checks would not double the time spent on analysis. We run a separate analysis for every "moving call" that we encounter -- see the the matcher [here](https://github.com/llvm/llvm-project/blob/a95a9465bfd261f7b7a464d79336faa74af780c0/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp#L508). So the number of analyses we run would remain the same: One for every call to an invalidation function. > and we need to keep two versions in sync. All of the shared code should, of course, be in a shared location and should not be duplicated. @higher-performance > I'm not really sure what to do about this given the check is basically > identical regardless of the name of the function. There's an important way in which the check should _not_ be the same for `std::move` versus other invalidation functions. The check considers the `Stmt` that performs the move to be not the `std::move` itself but its parent (with some nodes being ignored -- for details, see [this matcher](https://github.com/llvm/llvm-project/blob/a95a9465bfd261f7b7a464d79336faa74af780c0/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp#L508)). This reflects the fact that `std::move` itself does not perform the move but just a cast, which can become important in situations like this: ```cxx SomeMoveableType obj; void foo(SomeMoveableType &&, SomeOtherType); // Obviously a contrived example, but you get the point foo(std::move(obj), obj.operation()); ``` This isn't a use-after-move (regardless of the order in which arguments are evaluated) because the move only happens inside `foo()` and is thus guaranteed to happen after the evaluation of `obj.operation()`. (Never mind that this example seems a bit pointless because `foo()` itself could call `obj.operation()` -- but I've seen real code do more complex variations of this kind of pattern.) For other invalidation functions, however, we _should_ consider the call to the invalidation function itself to be the invalidation, not its parent. I realize this is often not an issue in practice because I presume many invalidation functions return `void`, but sooner or later someone is going to configure an invalidation function that does return a value, will use that value in an expression, and be mightily confused about why the check doesn't understand when the invalidation happens. Fixing this obviously doesn't require splitting the check into two separate checks, but it shows how "move" is different from other forms of "invalidation" and is therefore another reason to handle these in two different checks to avoid programmer confusion. https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
higher-performance wrote: I agree, and I ran into situations where I would've found the better diagnostics helpful too. https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
vbvictor wrote: I'm -1 on separating this checks because we essentially will duplicate a huge portion of logic into multiple places which can double the time of analysis and we need to keep two versions in sync. One thing we can do is provide better diag message like: ``` warning: 'X' used after it was invalidated by 'MyFunction' call [use-after-move]. note: invalidation occurred here ``` So we clearly show that it's not `std::move/std::forward` but a custom function. https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
higher-performance wrote: > > I've seen reports from users who were confused about a > > bugprone-use-after-move diagnostic they were getting because "there is no > > move in my code". > > Could you give some examples that are confusing to read. > > By default the check does not use any custom invalidation functions, so the > must have been specified explicitly or..? Yes, these were explicitly specified. The error messages themselves aren't necessarily confusing, it's just that the name of the check also shows up, and people assume there has to be a move because the name of the check has move in it, when the invalidation occurs due to something else like close() or free(). I'm not really sure what to do about this given the check is basically identical regardless of the name of the function. https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
vbvictor wrote: > I've seen reports from users who were confused about a > bugprone-use-after-move diagnostic they were getting because "there is no > move in my code". Could you give some examples that are confusing to read. By default the check does not use any custom invalidation functions, so the must have been specified explicitly or..? https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
martinboehme wrote: I've seen reports from users who were confused about a bugprone-use-after-move diagnostic they were getting because "there is no move in my code". With this added functionality, the name of the check is now misleading. One solution would be to rename the check, but I think the better solution would be to split the new functionality out into a separate check. https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
higher-performance wrote: Note there is a bug in the name pattern matching: #174229 https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
https://github.com/higher-performance closed https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
@@ -253,3 +253,13 @@ For example, if an additional member variable is added to ``S``, it is easy to forget to add the reinitialization for this additional member. Instead, it is safer to assign to the entire struct in one go, and this will also avoid the use-after-move warning. + +Options +--- + +.. option:: InvalidationFunctions + + A semicolon-separated list of names of functions that cause their initial higher-performance wrote: I ended up changing this to `first` anyway, since I couldn't find any instances of `initial` in the docs. Thanks for the suggestion. https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
https://github.com/higher-performance updated
https://github.com/llvm/llvm-project/pull/170346
>From 6f3e917beee08ca8a2716298f09511b08b9710c5 Mon Sep 17 00:00:00 2001
From: higher-performance
Date: Tue, 2 Dec 2025 13:20:24 -0500
Subject: [PATCH] Extend bugprone-use-after-move check to allow custom
invalidation functions
---
.../clang-tidy/bugprone/UseAfterMoveCheck.cpp | 76 ---
.../clang-tidy/bugprone/UseAfterMoveCheck.h | 7 +-
clang-tools-extra/docs/ReleaseNotes.rst | 4 +
.../checks/bugprone/use-after-move.rst| 10 +++
.../checkers/bugprone/use-after-move.cpp | 62 ++-
5 files changed, 129 insertions(+), 30 deletions(-)
diff --git a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
index 6d134a0e896a0..b2e08fe688a1b 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
@@ -19,6 +19,7 @@
#include "../utils/ExprSequence.h"
#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
#include
using namespace clang::ast_matchers;
@@ -48,7 +49,8 @@ struct UseAfterMove {
/// various internal helper functions).
class UseAfterMoveFinder {
public:
- UseAfterMoveFinder(ASTContext *TheContext);
+ UseAfterMoveFinder(ASTContext *TheContext,
+ llvm::ArrayRef InvalidationFunctions);
// Within the given code block, finds the first use of 'MovedVariable' that
// occurs after 'MovingCall' (the expression that performs the move). If a
@@ -71,6 +73,7 @@ class UseAfterMoveFinder {
llvm::SmallPtrSetImpl *DeclRefs);
ASTContext *Context;
+ llvm::ArrayRef InvalidationFunctions;
std::unique_ptr Sequence;
std::unique_ptr BlockMap;
llvm::SmallPtrSet Visited;
@@ -78,6 +81,11 @@ class UseAfterMoveFinder {
} // namespace
+static auto getNameMatcher(llvm::ArrayRef InvalidationFunctions) {
+ return anyOf(hasAnyName("::std::move", "::std::forward"),
+ matchers::matchesAnyListedName(InvalidationFunctions));
+}
+
// Matches nodes that are
// - Part of a decltype argument or class template argument (we check this by
// seeing if they are children of a TypeLoc), or
@@ -92,8 +100,9 @@ static StatementMatcher inDecltypeOrTemplateArg() {
hasAncestor(expr(hasUnevaluatedContext(;
}
-UseAfterMoveFinder::UseAfterMoveFinder(ASTContext *TheContext)
-: Context(TheContext) {}
+UseAfterMoveFinder::UseAfterMoveFinder(
+ASTContext *TheContext, llvm::ArrayRef InvalidationFunctions)
+: Context(TheContext), InvalidationFunctions(InvalidationFunctions) {}
std::optional
UseAfterMoveFinder::find(Stmt *CodeBlock, const Expr *MovingCall,
@@ -359,7 +368,7 @@ void UseAfterMoveFinder::getReinits(
unless(parmVarDecl(hasType(
references(qualType(isConstQualified())),
unless(callee(functionDecl(
-hasAnyName("::std::move", "::std::forward")))
+getNameMatcher(InvalidationFunctions)))
.bind("reinit");
Stmts->clear();
@@ -388,18 +397,21 @@ void UseAfterMoveFinder::getReinits(
}
}
-enum class MoveType {
- Move,// std::move
- Forward, // std::forward
+enum MoveType {
+ Forward = 0, // std::forward
+ Move = 1, // std::move
+ Invalidation = 2, // other
};
static MoveType determineMoveType(const FunctionDecl *FuncDecl) {
- if (FuncDecl->getName() == "move")
-return MoveType::Move;
- if (FuncDecl->getName() == "forward")
-return MoveType::Forward;
+ if (FuncDecl->isInStdNamespace()) {
+if (FuncDecl->getName() == "move")
+ return MoveType::Move;
+if (FuncDecl->getName() == "forward")
+ return MoveType::Forward;
+ }
- llvm_unreachable("Invalid move type");
+ return MoveType::Invalidation;
}
static void emitDiagnostic(const Expr *MovingCall, const DeclRefExpr *MoveArg,
@@ -408,29 +420,38 @@ static void emitDiagnostic(const Expr *MovingCall, const
DeclRefExpr *MoveArg,
const SourceLocation UseLoc = Use.DeclRef->getExprLoc();
const SourceLocation MoveLoc = MovingCall->getExprLoc();
- const bool IsMove = (Type == MoveType::Move);
-
- Check->diag(UseLoc, "'%0' used after it was %select{forwarded|moved}1")
- << MoveArg->getDecl()->getName() << IsMove;
- Check->diag(MoveLoc, "%select{forward|move}0 occurred here",
+ Check->diag(UseLoc,
+ "'%0' used after it was %select{forwarded|moved|invalidated}1")
+ << MoveArg->getDecl()->getName() << Type;
+ Check->diag(MoveLoc, "%select{forward|move|invalidation}0 occurred here",
DiagnosticIDs::Note)
- << IsMove;
+ << Type;
if (Use.EvaluationOrderUndefined) {
Check->diag(
UseLoc,
-"the use and %select{forward|move}0 are unsequenced, i.e. "
+"the use and
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
@@ -253,3 +253,13 @@ For example, if an additional member variable is added to ``S``, it is easy to forget to add the reinitialization for this additional member. Instead, it is safer to assign to the entire struct in one go, and this will also avoid the use-after-move warning. + +Options +--- + +.. option:: InvalidationFunctions + + A semicolon-separated list of names of functions that cause their initial + arguments to be invalidated (e.g., closing a handle). + For member functions, the initial argument is considered to be the implicit + object argument (`this`). Default value is an empty string. vbvictor wrote: That's tricky to remember, don't know if clang docs follow same style. https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
@@ -253,3 +253,13 @@ For example, if an additional member variable is added to ``S``, it is easy to forget to add the reinitialization for this additional member. Instead, it is safer to assign to the entire struct in one go, and this will also avoid the use-after-move warning. + +Options +--- + +.. option:: InvalidationFunctions + + A semicolon-separated list of names of functions that cause their initial + arguments to be invalidated (e.g., closing a handle). + For member functions, the initial argument is considered to be the implicit + object argument (`this`). Default value is an empty string. higher-performance wrote: Oops! Didn't realize that, thanks! https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
https://github.com/higher-performance updated
https://github.com/llvm/llvm-project/pull/170346
>From 47bab323ade589aff9d397020847c29d72a37705 Mon Sep 17 00:00:00 2001
From: higher-performance
Date: Tue, 2 Dec 2025 13:20:24 -0500
Subject: [PATCH] Extend bugprone-use-after-move check to allow custom
invalidation functions
---
.../clang-tidy/bugprone/UseAfterMoveCheck.cpp | 76 ---
.../clang-tidy/bugprone/UseAfterMoveCheck.h | 7 +-
clang-tools-extra/docs/ReleaseNotes.rst | 4 +
.../checks/bugprone/use-after-move.rst| 10 +++
.../checkers/bugprone/use-after-move.cpp | 62 ++-
5 files changed, 129 insertions(+), 30 deletions(-)
diff --git a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
index 6d134a0e896a0..b2e08fe688a1b 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
@@ -19,6 +19,7 @@
#include "../utils/ExprSequence.h"
#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
#include
using namespace clang::ast_matchers;
@@ -48,7 +49,8 @@ struct UseAfterMove {
/// various internal helper functions).
class UseAfterMoveFinder {
public:
- UseAfterMoveFinder(ASTContext *TheContext);
+ UseAfterMoveFinder(ASTContext *TheContext,
+ llvm::ArrayRef InvalidationFunctions);
// Within the given code block, finds the first use of 'MovedVariable' that
// occurs after 'MovingCall' (the expression that performs the move). If a
@@ -71,6 +73,7 @@ class UseAfterMoveFinder {
llvm::SmallPtrSetImpl *DeclRefs);
ASTContext *Context;
+ llvm::ArrayRef InvalidationFunctions;
std::unique_ptr Sequence;
std::unique_ptr BlockMap;
llvm::SmallPtrSet Visited;
@@ -78,6 +81,11 @@ class UseAfterMoveFinder {
} // namespace
+static auto getNameMatcher(llvm::ArrayRef InvalidationFunctions) {
+ return anyOf(hasAnyName("::std::move", "::std::forward"),
+ matchers::matchesAnyListedName(InvalidationFunctions));
+}
+
// Matches nodes that are
// - Part of a decltype argument or class template argument (we check this by
// seeing if they are children of a TypeLoc), or
@@ -92,8 +100,9 @@ static StatementMatcher inDecltypeOrTemplateArg() {
hasAncestor(expr(hasUnevaluatedContext(;
}
-UseAfterMoveFinder::UseAfterMoveFinder(ASTContext *TheContext)
-: Context(TheContext) {}
+UseAfterMoveFinder::UseAfterMoveFinder(
+ASTContext *TheContext, llvm::ArrayRef InvalidationFunctions)
+: Context(TheContext), InvalidationFunctions(InvalidationFunctions) {}
std::optional
UseAfterMoveFinder::find(Stmt *CodeBlock, const Expr *MovingCall,
@@ -359,7 +368,7 @@ void UseAfterMoveFinder::getReinits(
unless(parmVarDecl(hasType(
references(qualType(isConstQualified())),
unless(callee(functionDecl(
-hasAnyName("::std::move", "::std::forward")))
+getNameMatcher(InvalidationFunctions)))
.bind("reinit");
Stmts->clear();
@@ -388,18 +397,21 @@ void UseAfterMoveFinder::getReinits(
}
}
-enum class MoveType {
- Move,// std::move
- Forward, // std::forward
+enum MoveType {
+ Forward = 0, // std::forward
+ Move = 1, // std::move
+ Invalidation = 2, // other
};
static MoveType determineMoveType(const FunctionDecl *FuncDecl) {
- if (FuncDecl->getName() == "move")
-return MoveType::Move;
- if (FuncDecl->getName() == "forward")
-return MoveType::Forward;
+ if (FuncDecl->isInStdNamespace()) {
+if (FuncDecl->getName() == "move")
+ return MoveType::Move;
+if (FuncDecl->getName() == "forward")
+ return MoveType::Forward;
+ }
- llvm_unreachable("Invalid move type");
+ return MoveType::Invalidation;
}
static void emitDiagnostic(const Expr *MovingCall, const DeclRefExpr *MoveArg,
@@ -408,29 +420,38 @@ static void emitDiagnostic(const Expr *MovingCall, const
DeclRefExpr *MoveArg,
const SourceLocation UseLoc = Use.DeclRef->getExprLoc();
const SourceLocation MoveLoc = MovingCall->getExprLoc();
- const bool IsMove = (Type == MoveType::Move);
-
- Check->diag(UseLoc, "'%0' used after it was %select{forwarded|moved}1")
- << MoveArg->getDecl()->getName() << IsMove;
- Check->diag(MoveLoc, "%select{forward|move}0 occurred here",
+ Check->diag(UseLoc,
+ "'%0' used after it was %select{forwarded|moved|invalidated}1")
+ << MoveArg->getDecl()->getName() << Type;
+ Check->diag(MoveLoc, "%select{forward|move|invalidation}0 occurred here",
DiagnosticIDs::Note)
- << IsMove;
+ << Type;
if (Use.EvaluationOrderUndefined) {
Check->diag(
UseLoc,
-"the use and %select{forward|move}0 are unsequenced, i.e. "
+"the use and
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
https://github.com/vbvictor approved this pull request. lgtm https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
https://github.com/vbvictor edited https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
@@ -253,3 +253,13 @@ For example, if an additional member variable is added to ``S``, it is easy to forget to add the reinitialization for this additional member. Instead, it is safer to assign to the entire struct in one go, and this will also avoid the use-after-move warning. + +Options +--- + +.. option:: InvalidationFunctions + + A semicolon-separated list of names of functions that cause their initial + arguments to be invalidated (e.g., closing a handle). + For member functions, the initial argument is considered to be the implicit + object argument (`this`). Default value is an empty string. vbvictor wrote: ```suggestion object argument (``this``). Default value is an empty string. ``` Double ticks for language constructs https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
https://github.com/higher-performance edited https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
https://github.com/higher-performance deleted https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
https://github.com/higher-performance edited https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
@@ -253,3 +253,13 @@ For example, if an additional member variable is added to ``S``, it is easy to forget to add the reinitialization for this additional member. Instead, it is safer to assign to the entire struct in one go, and this will also avoid the use-after-move warning. + +Options +--- + +.. option:: InvalidationFunctions + + A semicolon-separated list of names of functions that cause their initial higher-performance wrote: Sorry I meant sometimes being before the first explicit one. https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
@@ -253,3 +253,13 @@ For example, if an additional member variable is added to ``S``, it is easy to forget to add the reinitialization for this additional member. Instead, it is safer to assign to the entire struct in one go, and this will also avoid the use-after-move warning. + +Options +--- + +.. option:: InvalidationFunctions + + A semicolon-separated list of names of functions that cause their initial higher-performance wrote: I deliberately avoided writing first because that felt super confusing when indices start at 0 and we might be sometimes skipping one... do you feel this is more confusing? https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
@@ -408,41 +420,53 @@ static void emitDiagnostic(const Expr *MovingCall, const
DeclRefExpr *MoveArg,
const SourceLocation UseLoc = Use.DeclRef->getExprLoc();
const SourceLocation MoveLoc = MovingCall->getExprLoc();
- const bool IsMove = (Type == MoveType::Move);
-
- Check->diag(UseLoc, "'%0' used after it was %select{forwarded|moved}1")
- << MoveArg->getDecl()->getName() << IsMove;
- Check->diag(MoveLoc, "%select{forward|move}0 occurred here",
+ Check->diag(UseLoc,
+ "'%0' used after it was %select{forwarded|moved|invalidated}1")
+ << MoveArg->getDecl()->getName() << Type;
+ Check->diag(MoveLoc, "%select{forward|move|invalidation}0 occurred here",
DiagnosticIDs::Note)
- << IsMove;
+ << Type;
if (Use.EvaluationOrderUndefined) {
Check->diag(
UseLoc,
-"the use and %select{forward|move}0 are unsequenced, i.e. "
+"the use and %select{forward|move|invalidation}0 are unsequenced, i.e.
"
"there is no guarantee about the order in which they are evaluated",
DiagnosticIDs::Note)
-<< IsMove;
+<< Type;
} else if (Use.UseHappensInLaterLoopIteration) {
Check->diag(UseLoc,
"the use happens in a later loop iteration than the "
-"%select{forward|move}0",
+"%select{forward|move|invalidation}0",
DiagnosticIDs::Note)
-<< IsMove;
+<< Type;
}
}
+UseAfterMoveCheck::UseAfterMoveCheck(StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+ InvalidationFunctions(utils::options::parseStringList(
+ Options.get("InvalidationFunctions", ""))) {}
+
+void UseAfterMoveCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+ Options.store(Opts, "InvalidationFunctions",
+utils::options::serializeStringList(InvalidationFunctions));
+}
+
void UseAfterMoveCheck::registerMatchers(MatchFinder *Finder) {
// try_emplace is a common maybe-moving function that returns a
// bool to tell callers whether it moved. Ignore std::move inside
// try_emplace to avoid false positives as we don't track uses of
// the bool.
auto TryEmplaceMatcher =
cxxMemberCallExpr(callee(cxxMethodDecl(hasName("try_emplace";
+ auto Arg = declRefExpr().bind("arg");
+ auto IsMemberCallee = callee(functionDecl(unless(isStaticStorageClass(;
auto CallMoveMatcher =
- callExpr(argumentCountIs(1),
- callee(functionDecl(hasAnyName("::std::move", "::std::forward"))
+ callExpr(callee(functionDecl(getNameMatcher(InvalidationFunctions))
.bind("move-decl")),
- hasArgument(0, declRefExpr().bind("arg")),
+ anyOf(cxxMemberCallExpr(IsMemberCallee, on(Arg)),
+ callExpr(unless(cxxMemberCallExpr(IsMemberCallee)),
+ hasArgument(0, Arg))),
higher-performance wrote:
Yup, I deliberately didn't try to generalize in this PR, since as you mentioned
I expect that to be much less common, and I don't have a use case for it yet.
There are other cases to consider too (like emplace), but if people want it
later we can always extend it further.
https://github.com/llvm/llvm-project/pull/170346
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
@@ -253,3 +253,13 @@ For example, if an additional member variable is added to ``S``, it is easy to forget to add the reinitialization for this additional member. Instead, it is safer to assign to the entire struct in one go, and this will also avoid the use-after-move warning. + +Options +--- + +.. option:: InvalidationFunctions + + A semicolon-separated list of names of functions that cause their initial 5chmidti wrote: I think `initial`->`first` is better in this context https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
@@ -408,41 +420,53 @@ static void emitDiagnostic(const Expr *MovingCall, const
DeclRefExpr *MoveArg,
const SourceLocation UseLoc = Use.DeclRef->getExprLoc();
const SourceLocation MoveLoc = MovingCall->getExprLoc();
- const bool IsMove = (Type == MoveType::Move);
-
- Check->diag(UseLoc, "'%0' used after it was %select{forwarded|moved}1")
- << MoveArg->getDecl()->getName() << IsMove;
- Check->diag(MoveLoc, "%select{forward|move}0 occurred here",
+ Check->diag(UseLoc,
+ "'%0' used after it was %select{forwarded|moved|invalidated}1")
+ << MoveArg->getDecl()->getName() << Type;
+ Check->diag(MoveLoc, "%select{forward|move|invalidation}0 occurred here",
DiagnosticIDs::Note)
- << IsMove;
+ << Type;
if (Use.EvaluationOrderUndefined) {
Check->diag(
UseLoc,
-"the use and %select{forward|move}0 are unsequenced, i.e. "
+"the use and %select{forward|move|invalidation}0 are unsequenced, i.e.
"
"there is no guarantee about the order in which they are evaluated",
DiagnosticIDs::Note)
-<< IsMove;
+<< Type;
} else if (Use.UseHappensInLaterLoopIteration) {
Check->diag(UseLoc,
"the use happens in a later loop iteration than the "
-"%select{forward|move}0",
+"%select{forward|move|invalidation}0",
DiagnosticIDs::Note)
-<< IsMove;
+<< Type;
}
}
+UseAfterMoveCheck::UseAfterMoveCheck(StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+ InvalidationFunctions(utils::options::parseStringList(
+ Options.get("InvalidationFunctions", ""))) {}
+
+void UseAfterMoveCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+ Options.store(Opts, "InvalidationFunctions",
+utils::options::serializeStringList(InvalidationFunctions));
+}
+
void UseAfterMoveCheck::registerMatchers(MatchFinder *Finder) {
// try_emplace is a common maybe-moving function that returns a
// bool to tell callers whether it moved. Ignore std::move inside
// try_emplace to avoid false positives as we don't track uses of
// the bool.
auto TryEmplaceMatcher =
cxxMemberCallExpr(callee(cxxMethodDecl(hasName("try_emplace";
+ auto Arg = declRefExpr().bind("arg");
+ auto IsMemberCallee = callee(functionDecl(unless(isStaticStorageClass(;
auto CallMoveMatcher =
- callExpr(argumentCountIs(1),
- callee(functionDecl(hasAnyName("::std::move", "::std::forward"))
+ callExpr(callee(functionDecl(getNameMatcher(InvalidationFunctions))
.bind("move-decl")),
- hasArgument(0, declRefExpr().bind("arg")),
+ anyOf(cxxMemberCallExpr(IsMemberCallee, on(Arg)),
+ callExpr(unless(cxxMemberCallExpr(IsMemberCallee)),
+ hasArgument(0, Arg))),
5chmidti wrote:
Given the invalidated object o to detect, you are matching
```c++
o.destroy();
destroy(o);
Class::destroy(o);
```
but not
```c++
shredder.destroy(o);
```
But I see why it's not supported: is `this` or the first arg the things that is
getting invalidated.
One solution would be to have a separate option list for either case, but that
might confuse people. I think the cases you do match are the ones that are more
likely to happen, so it might be fine. Just wanted to point this out if others
think we should support the one that is currently not matched.
https://github.com/llvm/llvm-project/pull/170346
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
@@ -1645,3 +1653,47 @@ void create() {
}
} // namespace issue82023
+
+namespace custom_invalidation
+{
+
+template
+struct Database {
+ template
+ void CloseConnection(T = T()) {}
+ template
+ static void StaticCloseConnection(Database&, T = T()) {}
+ template
+ friend void FriendCloseConnection(Database&, T = T()) {}
+ void Query();
+};
+
+void Run() {
+ using DB = Database<>;
+
+ DB db1;
+ db1.CloseConnection();
+ db1.Query();
+ // CHECK-NOTES: [[@LINE-1]]:3: warning: 'db1' used after it was invalidated
+ // CHECK-NOTES: [[@LINE-3]]:7: note: invalidation occurred here
+
+ DB db2;
+ DB::StaticCloseConnection(db2);
+ db2.Query();
+ // CHECK-NOTES: [[@LINE-1]]:3: warning: 'db2' used after it was invalidated
+ // CHECK-NOTES: [[@LINE-3]]:3: note: invalidation occurred here
+
+ DB db3;
+ DB().StaticCloseConnection(db3);
+ db3.Query();
+ // CHECK-NOTES: [[@LINE-1]]:3: warning: 'db3' used after it was invalidated
+ // CHECK-NOTES: [[@LINE-3]]:3: note: invalidation occurred here
+
+ DB db4;
+ FriendCloseConnection(db4);
+ db4.Query();
+ // CHECK-NOTES: [[@LINE-1]]:3: warning: 'db4' used after it was invalidated
+ // CHECK-NOTES: [[@LINE-3]]:3: note: invalidation occurred here
+}
higher-performance wrote:
Added the timeout case.
https://github.com/llvm/llvm-project/pull/170346
___
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
https://github.com/higher-performance updated
https://github.com/llvm/llvm-project/pull/170346
>From b3ace442dcf10c14bfe5782d7c6aba4867df55b4 Mon Sep 17 00:00:00 2001
From: higher-performance
Date: Tue, 2 Dec 2025 13:20:24 -0500
Subject: [PATCH] Extend bugprone-use-after-move check to allow custom
invalidation functions
---
.../clang-tidy/bugprone/UseAfterMoveCheck.cpp | 76 ---
.../clang-tidy/bugprone/UseAfterMoveCheck.h | 7 +-
clang-tools-extra/docs/ReleaseNotes.rst | 4 +
.../checks/bugprone/use-after-move.rst| 10 +++
.../checkers/bugprone/use-after-move.cpp | 62 ++-
5 files changed, 129 insertions(+), 30 deletions(-)
diff --git a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
index 6d134a0e896a0..b2e08fe688a1b 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
@@ -19,6 +19,7 @@
#include "../utils/ExprSequence.h"
#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
#include
using namespace clang::ast_matchers;
@@ -48,7 +49,8 @@ struct UseAfterMove {
/// various internal helper functions).
class UseAfterMoveFinder {
public:
- UseAfterMoveFinder(ASTContext *TheContext);
+ UseAfterMoveFinder(ASTContext *TheContext,
+ llvm::ArrayRef InvalidationFunctions);
// Within the given code block, finds the first use of 'MovedVariable' that
// occurs after 'MovingCall' (the expression that performs the move). If a
@@ -71,6 +73,7 @@ class UseAfterMoveFinder {
llvm::SmallPtrSetImpl *DeclRefs);
ASTContext *Context;
+ llvm::ArrayRef InvalidationFunctions;
std::unique_ptr Sequence;
std::unique_ptr BlockMap;
llvm::SmallPtrSet Visited;
@@ -78,6 +81,11 @@ class UseAfterMoveFinder {
} // namespace
+static auto getNameMatcher(llvm::ArrayRef InvalidationFunctions) {
+ return anyOf(hasAnyName("::std::move", "::std::forward"),
+ matchers::matchesAnyListedName(InvalidationFunctions));
+}
+
// Matches nodes that are
// - Part of a decltype argument or class template argument (we check this by
// seeing if they are children of a TypeLoc), or
@@ -92,8 +100,9 @@ static StatementMatcher inDecltypeOrTemplateArg() {
hasAncestor(expr(hasUnevaluatedContext(;
}
-UseAfterMoveFinder::UseAfterMoveFinder(ASTContext *TheContext)
-: Context(TheContext) {}
+UseAfterMoveFinder::UseAfterMoveFinder(
+ASTContext *TheContext, llvm::ArrayRef InvalidationFunctions)
+: Context(TheContext), InvalidationFunctions(InvalidationFunctions) {}
std::optional
UseAfterMoveFinder::find(Stmt *CodeBlock, const Expr *MovingCall,
@@ -359,7 +368,7 @@ void UseAfterMoveFinder::getReinits(
unless(parmVarDecl(hasType(
references(qualType(isConstQualified())),
unless(callee(functionDecl(
-hasAnyName("::std::move", "::std::forward")))
+getNameMatcher(InvalidationFunctions)))
.bind("reinit");
Stmts->clear();
@@ -388,18 +397,21 @@ void UseAfterMoveFinder::getReinits(
}
}
-enum class MoveType {
- Move,// std::move
- Forward, // std::forward
+enum MoveType {
+ Forward = 0, // std::forward
+ Move = 1, // std::move
+ Invalidation = 2, // other
};
static MoveType determineMoveType(const FunctionDecl *FuncDecl) {
- if (FuncDecl->getName() == "move")
-return MoveType::Move;
- if (FuncDecl->getName() == "forward")
-return MoveType::Forward;
+ if (FuncDecl->isInStdNamespace()) {
+if (FuncDecl->getName() == "move")
+ return MoveType::Move;
+if (FuncDecl->getName() == "forward")
+ return MoveType::Forward;
+ }
- llvm_unreachable("Invalid move type");
+ return MoveType::Invalidation;
}
static void emitDiagnostic(const Expr *MovingCall, const DeclRefExpr *MoveArg,
@@ -408,29 +420,38 @@ static void emitDiagnostic(const Expr *MovingCall, const
DeclRefExpr *MoveArg,
const SourceLocation UseLoc = Use.DeclRef->getExprLoc();
const SourceLocation MoveLoc = MovingCall->getExprLoc();
- const bool IsMove = (Type == MoveType::Move);
-
- Check->diag(UseLoc, "'%0' used after it was %select{forwarded|moved}1")
- << MoveArg->getDecl()->getName() << IsMove;
- Check->diag(MoveLoc, "%select{forward|move}0 occurred here",
+ Check->diag(UseLoc,
+ "'%0' used after it was %select{forwarded|moved|invalidated}1")
+ << MoveArg->getDecl()->getName() << Type;
+ Check->diag(MoveLoc, "%select{forward|move|invalidation}0 occurred here",
DiagnosticIDs::Note)
- << IsMove;
+ << Type;
if (Use.EvaluationOrderUndefined) {
Check->diag(
UseLoc,
-"the use and %select{forward|move}0 are unsequenced, i.e. "
+"the use and
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
https://github.com/zeyi2 approved this pull request. But would be nice to wait for other reviewers :) https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Extend `bugprone-use-after-move` to allow custom invalidation functions (PR #170346)
https://github.com/zeyi2 edited https://github.com/llvm/llvm-project/pull/170346 ___ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
