[PATCH] D120372: [clang] 'unused-but-set-variable' warning should not apply to __attribute__((objc_precise_lifetime) Objective-C pointers

Michael Wyman via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Tue Feb 22 17:07:10 PST 2022


mwyman created this revision.
mwyman added reviewers: stephanemoore, dmaclach.
mwyman added a project: clang.
mwyman requested review of this revision.
Herald added a subscriber: cfe-commits.

The `objc_precise_lifetime` attribute is applied to Objective-C pointers to ensure the optimizer does not prematurely release an object under Automatic Reference Counting (ARC). It is a common enough pattern to assign values to these variables but not reference them otherwise, and annotating them with `__unused` is not really correct as they //are// being used to ensure an object's lifetime.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120372

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/test/SemaObjC/objc-precise-lifetime-unused-variable.m


Index: clang/test/SemaObjC/objc-precise-lifetime-unused-variable.m
===================================================================
--- /dev/null
+++ clang/test/SemaObjC/objc-precise-lifetime-unused-variable.m
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macos11 -fsyntax-only -fobjc-arc -fblocks -verify -Wunused-but-set-variable -Wno-objc-root-class %s
+
+id getFoo(void);
+
+void test() {
+  // no diagnostics for objects with precise lifetime semantics.
+  __attribute__((objc_precise_lifetime)) id x;
+  x = getFoo();
+
+  id x2; // expected-warning {{variable 'x2' set but not used}}
+  x2 = getFoo();
+}
Index: clang/lib/Sema/SemaDecl.cpp
===================================================================
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -2008,6 +2008,12 @@
   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
     return;
 
+  // Don't warn about Objective-C pointer variables with precise lifetime
+  // semantics; they can be used to ensure ARC releases the object at a known
+  // time, which may mean assignment but no other references.
+  if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
+    return;
+
   auto iter = RefsMinusAssignments.find(VD);
   if (iter == RefsMinusAssignments.end())
     return;


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D120372.410677.patch
Type: text/x-patch
Size: 1313 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20220223/700666cc/attachment.bin>


More information about the cfe-commits mailing list