[clang] [LifetimeSafety] Flow pointee loan for lifetimebound reference-to-pointer params (PR #239753)
via cfe-commits
cfe-commits at lists.llvm.org
Sun Nov 8 09:03:20 PST 2026
================
@@ -1287,10 +1293,33 @@ void FactsGenerator::handleFunctionCall(const Expr *Call,
KillSrc = false;
} else if (ShouldTrackArg) {
// Lifetimebound on a non-GSL-ctor function means the returned
- // pointer/reference itself must not outlive the arguments. This
- // only constrains the top-level origin.
+ // pointer/reference itself must not outlive the arguments.
+ // This usually only constrains the top-level origin.
+ // If the number of indirections differ between the parameter and the
+ // return value then we need to adjust the origin.
+ //
+ // The number of levels to peel is the indirection-depth difference
+ // between the argument and the result: for `T*&` returning `T*` that is
+ // one, but for a reference to a multi-level pointer (`T**&` returning
+ // `T*`) it can be more.
+ // This is restricted to raw-pointer pointees. For a reference to a
+ // gsl::Pointer (`const View&`) the returned view borrows the referent
+ // itself, so the outer origin is correct and must not peel.
+ OriginList *Src = ArgList;
+ if (const auto *PVD = dyn_cast<const ParmVarDecl *>(*TrackedArg)) {
+ if (isReferenceToPointer(PVD->getType())) {
+ size_t CallListLen = CallList->getLength();
+ size_t SrcLen = Src->getLength();
+ if (SrcLen > CallListLen) {
+ size_t LevelsToDrop = SrcLen - CallListLen;
+ for (size_t I = LevelsToDrop; I > 0; --I) {
+ Src = Src->peelOuterOrigin();
+ }
+ }
----------------
NeKon69 wrote:
I think this is a broader change than I'd like.
Consider the following case:
```cpp
void* f(int***& p [[clang::lifetimebound]]) {
return p;
}
```
Here, this loop will happily peel until the shapes match, even though we're just returning the top-level pointer. Which I believe is the general reason why we don't simply try to match origin list shapes by peeling.
Another example would be:
```cpp
int*& f(int**& p [[clang::lifetimebound]]);
```
Where this change would still peel to match the origin list depths, even though we're returning a reference.
Do we really want to touch the general pointer-level mismatch problem in this PR?
https://github.com/llvm/llvm-project/pull/239753
More information about the cfe-commits
mailing list