[clang] Use cast_or_null instead of cast (PR #93749)

Akira Hatanaka via cfe-commits cfe-commits at lists.llvm.org
Wed May 29 16:32:41 PDT 2024


https://github.com/ahatanak created https://github.com/llvm/llvm-project/pull/93749

`Eval->Value.get` returns a null pointer when the variable doesn't have an initializer.

This fixes https://github.com/llvm/llvm-project/issues/93625.

rdar://128482541

>From 4648f46f5e15d5747596347feaef85069a8ce4df Mon Sep 17 00:00:00 2001
From: Akira Hatanaka <ahatanak at gmail.com>
Date: Wed, 29 May 2024 15:19:58 -0700
Subject: [PATCH] Use cast_or_null instead of cast

`Eval->Value.get` returns a null pointer when the variable doesn't have
an initializer.

This fixes https://github.com/llvm/llvm-project/issues/93625.

rdar://128482541
---
 clang/lib/AST/Decl.cpp                 |  8 +++++---
 clang/test/SemaObjCXX/block-capture.mm | 18 ++++++++++++++++++
 2 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index 41fbfe281ef65..4940a787e7d30 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -2408,9 +2408,11 @@ Expr *VarDecl::getInit() {
     return cast<Expr>(S);
 
   auto *Eval = getEvaluatedStmt();
-  return cast<Expr>(Eval->Value.isOffset()
-                        ? Eval->Value.get(getASTContext().getExternalSource())
-                        : Eval->Value.get(nullptr));
+
+  return cast_or_null<Expr>(
+      Eval->Value.isOffset()
+          ? Eval->Value.get(getASTContext().getExternalSource())
+          : Eval->Value.get(nullptr));
 }
 
 Stmt **VarDecl::getInitAddress() {
diff --git a/clang/test/SemaObjCXX/block-capture.mm b/clang/test/SemaObjCXX/block-capture.mm
index 8ba02f919e015..231aef33f2c7e 100644
--- a/clang/test/SemaObjCXX/block-capture.mm
+++ b/clang/test/SemaObjCXX/block-capture.mm
@@ -83,3 +83,21 @@
   SubMove(SubSubMove &&);
 };
 TEST(SubMove);
+
+
+#if __cplusplus >= 202302L
+// clang used to crash compiling this code.
+namespace BlockInLambda {
+  struct S {
+    constexpr ~S();
+  };
+
+  void func(S const &a) {
+    [a](auto b) {
+      ^{
+        (void)a;
+      }();
+    }(12);
+  }
+}
+#endif



More information about the cfe-commits mailing list