[clang] [Clang] Extend lifetime bound analysis to support assignments (PR #96475)

Haojian Wu via cfe-commits cfe-commits at lists.llvm.org
Fri Jun 28 07:27:10 PDT 2024


================
@@ -964,11 +966,26 @@ static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
   return false;
 }
 
-void checkExprLifetime(Sema &SemaRef, const InitializedEntity &Entity,
+void checkExprLifetime(Sema &SemaRef, const CheckingEntity &CEntity,
                        Expr *Init) {
-  LifetimeResult LR = getEntityLifetime(&Entity);
-  LifetimeKind LK = LR.getInt();
-  const InitializedEntity *ExtendingEntity = LR.getPointer();
+  LifetimeKind LK = LK_FullExpression;
+
+  const AssignedEntity *AEntity = nullptr;
+  // Local variables for initialized entity.
+  const InitializedEntity *InitEntity = nullptr;
+  const InitializedEntity *ExtendingEntity = nullptr;
+  if (auto IEntityP = std::get_if<const InitializedEntity *>(&CEntity)) {
+    InitEntity = *IEntityP;
+    auto LTResult = getEntityLifetime(InitEntity);
+    LK = LTResult.getInt();
+    ExtendingEntity = LTResult.getPointer();
+  } else if (auto AEntityP = std::get_if<const AssignedEntity *>(&CEntity)) {
+    AEntity = *AEntityP;
+    if (AEntity->LHS->getType()->isPointerType()) // builtin pointer type
+      LK = LK_Extended;
----------------
hokein wrote:

Yeah, right, assignments do not extend the object lifetime.

The `LK_Extended` doesn't affect the actual analysis; it's mainly a flag used to control whether we emit the dangling diagnostics:

1. It expresses that 'we expect the lifetime of the temporary to be extended to the initialized entity itself' (in other words, the lifetime of the temporary object should not be shorter than the lifetime of the entity).
2. The actual analysis involves finding paths to a temporary by examining the AST of the `Init` expression.

If we find a path that does not extend the lifetime of the temporary object and have the expectation mentioned in 1), we consider this a dangling case.

Most of the existing code can be reused. The only difference is that it is impossible to get a path that would extend the lifetime of the temporary object for the assignment case (see the newly added assertions).

https://github.com/llvm/llvm-project/pull/96475


More information about the cfe-commits mailing list