llvm-project/clang/test/SemaCXX/PR19955.cpp

16 lines
458 B
C++
Raw Normal View History

// RUN: %clang_cc1 -triple i686-win32 -fms-compatibility -verify -std=c++11 %s
extern int __attribute__((dllimport)) var;
constexpr int *varp = &var; // expected-error {{must be initialized by a constant expression}}
extern __attribute__((dllimport)) void fun();
constexpr void (*funp)(void) = &fun; // expected-error {{must be initialized by a constant expression}}
AST: Initialization with dllimport functions in C The C++ language requires that the address of a function be the same across all translation units. To make __declspec(dllimport) useful, this means that a dllimported function must also obey this rule. MSVC implements this by dynamically querying the import address table located in the linked executable. This means that the address of such a function in C++ is not constant (which violates other rules). However, the C language has no notion of ODR nor does it permit dynamic initialization whatsoever. This requires implementations to _not_ dynamically query the import address table and instead utilize a wrapper function that will be synthesized by the linker which will eventually query the import address table. The effect this has is, to say the least, perplexing. Consider the following C program: __declspec(dllimport) void f(void); typedef void (*fp)(void); static const fp var = &f; const fp fun() { return &f; } int main() { return fun() == var; } MSVC will statically initialize "var" with the address of the wrapper function and "fun" returns the address of the actual imported function. This means that "main" will return false! Note that LLVM's optimizers are strong enough to figure out that "main" should return true. However, this result is dependent on having optimizations enabled! N.B. This change also permits the usage of dllimport declarators inside of template arguments; they are sufficiently constant for such a purpose. Add tests to make sure we don't regress here. llvm-svn: 211677
2014-06-25 16:15:07 +08:00
template <void (*)()>
struct S {};
S<&fun> x;
template <int *>
struct U {};
U<&var> y;