[clang-cl] Handle some pragma alloc_text corner cases handled by MSVC
authorStephen Long <steplong@quicinc.com>
Tue, 28 Jun 2022 13:45:18 +0000 (06:45 -0700)
committerStephen Long <steplong@quicinc.com>
Wed, 29 Jun 2022 13:45:59 +0000 (06:45 -0700)
MSVC's pragma alloc_text accepts a function that was redeclared in
a non extern-C context if the previous declaration was in an extern-C
context. i.e.

```
extern "C" { static void f(); }
static void f();
```

MSVC's pragma alloc_text also rejects non-functions.

Reviewed By: hans

Differential Revision: https://reviews.llvm.org/D128649

clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaAttr.cpp
clang/test/Sema/pragma-ms-alloc-text.c
clang/test/Sema/pragma-ms-alloc-text.cpp

index 442088d..dc9ca4b 100644 (file)
@@ -992,6 +992,8 @@ def err_pragma_expected_file_scope : Error<
   "'#pragma %0' can only appear at file scope">;
 def err_pragma_alloc_text_c_linkage: Error<
   "'#pragma alloc_text' is applicable only to functions with C linkage">;
+def err_pragma_alloc_text_not_function: Error<
+  "'#pragma alloc_text' is applicable only to functions">;
 
 def warn_pragma_unused_undeclared_var : Warning<
   "undeclared variable %0 used as an argument for '#pragma unused'">,
index c7e62e5..c997d01 100644 (file)
@@ -810,8 +810,13 @@ void Sema::ActOnPragmaMSAllocText(
       return;
     }
 
-    DeclContext *DC = ND->getDeclContext();
-    if (getLangOpts().CPlusPlus && !DC->isExternCContext()) {
+    auto *FD = dyn_cast<FunctionDecl>(ND->getCanonicalDecl());
+    if (!FD) {
+      Diag(Loc, diag::err_pragma_alloc_text_not_function);
+      return;
+    }
+
+    if (getLangOpts().CPlusPlus && !FD->isInExternCContext()) {
       Diag(Loc, diag::err_pragma_alloc_text_c_linkage);
       return;
     }
index a5f2e9f..ff49fa4 100644 (file)
@@ -1,9 +1,12 @@
 // RUN: %clang_cc1 -fms-extensions -fsyntax-only -verify %s
 
 void foo();
-#pragma alloc_text("hello", foo) // expected-no-diagnostics
+#pragma alloc_text("hello", foo) // no-error
 void foo() {}
 
 static void foo1();
-#pragma alloc_text("hello", foo1) // expected-no-diagnostics
+#pragma alloc_text("hello", foo1) // no-error
 void foo1() {}
+
+int foo2;
+#pragma alloc_text(c, foo2) // expected-error {{'#pragma alloc_text' is applicable only to functions}}
index 931b152..a150cb2 100644 (file)
@@ -40,3 +40,20 @@ static void foo6();
 #pragma alloc_text(c, foo6) // no-warning
 void foo6() {}
 }
+
+extern "C" {
+static void foo7();
+}
+static void foo7();
+#pragma alloc_text(c, foo7) // no-warning
+void foo7() {}
+
+static void foo8();
+extern "C" {
+static void foo8();
+}
+#pragma alloc_text(c, foo8) // expected-error {{'#pragma alloc_text' is applicable only to functions with C linkage}}
+void foo8() {}
+
+enum foo9 { A, B, C };
+#pragma alloc_text(c, foo9) // expected-error {{'#pragma alloc_text' is applicable only to functions}}