Search code examples
cstandardsc-standard-library

Is there a standard-compliant way to detect whether a function in the C standard library is implemented via intrinsic/builtin?


Is there a standard-compliant way to detect whether a function in the C standard library is implemented via intrinsic/builtin?

I'm pretty confident I can implement code which performs better than the function provided by the standard library for a specific call site if only because of function call overhead. But if the function in question is implemented via intrinsic/builtin, there's no function call overhead to beat, so it would be foolish to try.

If there's a way, I have a feeling it won't be simple because it may vary by call site. For example, passing a constant length to memcpy may provide the compiler a great opportunity to generate inline code, but a variable length may provide a lesser opportunity. I guess the best hint available might be one of three values, "always", "never", or "sometimes". That would be good enough for me.

The details of how this might be accomplished are negotiable as long as they're standard-compliant. The version of the standard is even negotiable because that's testable and I'd be happy making the safest assumption if the question weren't answerable for an earlier version of the standard. But of course a way to do this at compile-time would be preferred.

(edited to include concrete details to make it easier to think about even though these details don't matter)

Let's assume memcpy is indeed the function in question and that we know the length is always variable because it was passed in to the function which calls memcpy, but we also know that length is frequently 1.

The overhead of calling into a library will surely dominate both if (1==length) and *dst = *src;. So the questions are how frequently 1 is actually the value, which is a question only I can answer, and whether any possibility the implementation will call into a library can be eliminated.

This question isn't about whether one can write a function which goes faster than memcpy or any other standard library function. There are plenty of questions on that and this isn't one of them.


Solution

  • It seems the closest we'll get to a simple YES or NO answer is this comment from Nate Eldredge: "The C standard doesn't even have the concept of 'intrinsic / builtin'".