Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forcing clang to emit code for never-referenced static member function of class-template instantiation

Tags:

c++

gcc

clang

I can easily achieve this in gcc using the used and noinline function attributes (see code below), but this doesn't work in clang even though it's supposed to support both of these function attributes.

A simplified example:

template<typename T>
struct Factory {
    static __attribute__((used, noinline))
    T createFoo() { return T(); }
};

int main() {
    Factory<int> f; // instantiate and use Factory<int>
}

Compile the code in gcc and use nm to confirm that gcc correctly emitted the function:

nm --demangle test | grep createFoo
0000000000403185 W Factory<int>::createFoo()

The code compiles fine in clang, but it does not emit code for the static createFoo() function like it's supposed to.

How can I force clang to emit this static function which is never referenced?

like image 225
etherice Avatar asked Sep 24 '13 00:09

etherice


1 Answers

This is definitely a bug in clang.

As the OP stated in a comment, the semantics of __attribute__((used)) is to treat the function as if it were actually referenced in the code, forcing it to emit code for the function, which clang is not doing in this case.

Furthermore, all class-member-functions have extern linkage as defined by C++. So when the class is instantiated, and the compiler (supporting gcc-style function attibutes) sees __attribute__((used)) for the member function, it should know immediately that an externally visible definition of that function should be emitted. gcc is doing this, bug clang is not.

A temporary workaround (for clang) is to explicitly reference the function somewhere in your code.

You should also file a clang bug report with llvm to get this issue fixed.

like image 116
MikeTusar Avatar answered Nov 30 '22 22:11

MikeTusar