From 0c1761d3f4662d9239a35aa6d5c0c84da2c359b8 Mon Sep 17 00:00:00 2001 From: Michael Buch Date: Fri, 20 Sep 2024 19:42:41 +0100 Subject: [PATCH] [clang][CodeGen] Check initializer of zero-size fields for nullptr (#109271) In https://github.com/llvm/llvm-project/pull/96422 we started treating empty records as zero-sized for the purpose of layout. In `C`, empty fields were never considered `isZeroSize`, so we would never have tried to call `Init->hasSideEffects` on them. But since https://github.com/llvm/llvm-project/pull/96422 we can get here when compiling `C`, but `Init` need not exist. This patch adds a null-check to account for this situtation. (cherry picked from commit 2162a18fb206736c41c9182737b72ae15d5e6bf0) --- clang/lib/CodeGen/CGExprConstant.cpp | 2 +- clang/test/CodeGen/union-init2.c | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/clang/lib/CodeGen/CGExprConstant.cpp b/clang/lib/CodeGen/CGExprConstant.cpp index 7c57d00a3aa3b..e12374957d99e 100644 --- a/clang/lib/CodeGen/CGExprConstant.cpp +++ b/clang/lib/CodeGen/CGExprConstant.cpp @@ -738,7 +738,7 @@ bool ConstStructBuilder::Build(const InitListExpr *ILE, bool AllowOverwrite) { // Zero-sized fields are not emitted, but their initializers may still // prevent emission of this struct as a constant. if (isEmptyFieldForLayout(CGM.getContext(), Field)) { - if (Init->HasSideEffects(CGM.getContext())) + if (Init && Init->HasSideEffects(CGM.getContext())) return false; continue; } diff --git a/clang/test/CodeGen/union-init2.c b/clang/test/CodeGen/union-init2.c index 2c167683c4e55..048ff00517b4e 100644 --- a/clang/test/CodeGen/union-init2.c +++ b/clang/test/CodeGen/union-init2.c @@ -1,4 +1,5 @@ // RUN: %clang_cc1 -emit-llvm %s -o - -triple i686-pc-linux-gnu | FileCheck %s +// RUN: %clang_cc1 -x c++ %s -emit-llvm -triple x86_64-linux-gnu -o - | FileCheck %s --check-prefixes=CHECK-CXX // Make sure we generate something sane instead of a ptrtoint // CHECK: @r, [4 x i8] undef @@ -11,3 +12,10 @@ union z { long long b; }; union z y = {}; + +// CHECK: @foo = {{.*}}global %union.Foo undef, align 1 +// CHECK-CXX: @foo = {{.*}}global %union.Foo undef, align 1 +union Foo { + struct Empty {} val; +}; +union Foo foo = {};