Skip to content

Commit 913b74f

Browse files
[clang] Predefine _CRT_USE_BUILTIN_OFFSETOF in MS-compatible modes
This patch makes Clang predefine `_CRT_USE_BUILTIN_OFFSETOF` in MS-compatible modes. The macro can make the offsetof provided by MS UCRT's `<stddef.h>` to select the `__builtin_offsetof` version, so with it Clang (Clang-cl) can directly consume UCRT's `offsetof`. MSVC predefines the macro as `1` since at least VS 2017 19.14, but I think it's also OK to define it in "older" compatible modes.
1 parent 663db5c commit 913b74f

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

clang/lib/Basic/Targets/OSTargets.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,8 @@ static void addVisualCDefines(const LangOptions &Opts, MacroBuilder &Builder) {
220220
Builder.defineMacro("_MSC_FULL_VER", Twine(Opts.MSCompatibilityVersion));
221221
// FIXME We cannot encode the revision information into 32-bits
222222
Builder.defineMacro("_MSC_BUILD", Twine(1));
223+
// https://github.com/llvm/llvm-project/issues/59689
224+
Builder.defineMacro("_CRT_USE_BUILTIN_OFFSETOF", Twine(1));
223225

224226
if (Opts.CPlusPlus11 && Opts.isCompatibleWithMSVC(LangOptions::MSVC2015))
225227
Builder.defineMacro("_HAS_CHAR16_T_LANGUAGE_SUPPORT", Twine(1));

clang/test/Sema/offsetof-ucrt.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// RUN: %clang_cc1 %s -triple i686-pc-win32 -fsyntax-only -verify -fms-compatibility
2+
3+
typedef __typeof__(sizeof(0)) size_t;
4+
5+
#if defined _MSC_VER && !defined _CRT_USE_BUILTIN_OFFSETOF
6+
#ifdef __cplusplus
7+
#define offsetof(s,m) ((::size_t)&reinterpret_cast<char const volatile&>((((s*)0)->m)))
8+
#else
9+
#define offsetof(s,m) ((size_t)&(((s*)0)->m))
10+
#endif
11+
#else
12+
#define offsetof(s,m) __builtin_offsetof(s,m)
13+
#endif
14+
15+
struct S { int a; };
16+
_Static_assert(offsetof(struct S, a) == 0, "");
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// RUN: %clang_cc1 %s -triple i686-pc-win32 -fsyntax-only -verify -fms-compatibility
2+
3+
typedef __typeof__(sizeof(0)) size_t;
4+
5+
#if defined _MSC_VER && !defined _CRT_USE_BUILTIN_OFFSETOF
6+
#ifdef __cplusplus
7+
#define offsetof(s,m) ((::size_t)&reinterpret_cast<char const volatile&>((((s*)0)->m)))
8+
#else
9+
#define offsetof(s,m) ((size_t)&(((s*)0)->m))
10+
#endif
11+
#else
12+
#define offsetof(s,m) __builtin_offsetof(s,m)
13+
#endif
14+
15+
struct S { int a; };
16+
_Static_assert(offsetof(S, a) == 0, "");

0 commit comments

Comments
 (0)