by jcelerier · 8y ago · 0 comments
so... you like never free, never fclose, never munmap, never pthread_join, never unlock mutexes, never close network connections or what ?
Also, all of your protoypes such as
sg_pipeline sg_alloc_pipeline() {
should really be sg_pipeline sg_alloc_pipeline(void) {
since the first one can actually be called with any number of arguments (in C, not in C++).Note also that C doesn't have return-value-optimization, hence all your struct-returning functions can possibly cause a call to memcpy (won't happen when compiled in C++ mode of course) and will generally lead to much more binary bloat than the traditional C way of passing outputs as arguments. e.g. given this trivial code in foo.c:
typedef struct _foo
{
int x;
float foo, bar;
char z[1024]; // change this to 10024 to get a memcpy!
} foo;
void do_stuff_to_foo(foo*);
foo blah()
{
foo f;
do_stuff_to_foo(&f);
return f;
}
A disassembly after compilation with gcc -std=c99 -O3 gives blah:
.LFB0:
pushq %rbp
movq %rdi, %rbp
pushq %rbx
subq $1064, %rsp
movq %fs:40, %rax
movq %rax, 1048(%rsp)
xorl %eax, %eax
movq %rsp, %rbx
movq %rbx, %rdi
call do_stuff_to_foo@PLT
movq (%rsp), %rax
leaq 8(%rbp), %rdi
movq %rbp, %rcx
andq $-8, %rdi
movq %rbx, %rsi
subq %rdi, %rcx
movq %rax, 0(%rbp)
movq 1028(%rbx), %rax
subq %rcx, %rsi
addl $1036, %ecx
movq %rax, 1028(%rbp)
shrl $3, %ecx
rep movsq
movq 1048(%rsp), %rdx
xorq %fs:40, %rdx
jne .L5
addq $1064, %rsp
movq %rbp, %rax
popq %rbx
popq %rbp
ret
The same thing built with g++ -O3 gives _Z4blahv:
pushq %rbx
movq %rdi, %rbx
call _Z15do_stuff_to_fooP4_foo@PLT
movq %rbx, %rax
popq %rbx
ret
While clang (in C mode) goes for a memcpy: blah: # @blah
pushq %r14
pushq %rbx
subq $1048, %rsp # imm = 0x418
movq %rdi, %rbx
movq %fs:40, %rax
movq %rax, 1040(%rsp)
movq %rsp, %r14
movq %r14, %rdi
callq do_stuff_to_foo@PLT
movl $1036, %edx # imm = 0x40C
movq %rbx, %rdi
movq %r14, %rsi
callq memcpy@PLT
movq %fs:40, %rax
cmpq 1040(%rsp), %rax
jne .LBB0_2
movq %rbx, %rax
addq $1048, %rsp # imm = 0x418
popq %rbx
popq %r14
retqWhat ?
RVO is precisely needed because a copy in C++ can run arbitrary code and so is not as easy to ellide as a memcpy. RVO is basically a promess you make to have your copy constructor & destructor be semantically harmless compared to a memcpy.
There is no need for RVO in C.
The compilers are using basically the same underling optimizer and back-end with different front-ends, and since in C there are no "user-defined constructors" and no destructors, one would expect that you don't need any special RVO rule in C: the compiler can simply observe that a local object is returned and construct it in-place as necessary.
Thinking about this example, this may not be the case: distinct objects have to have distinct addresses, right? So in C you might not be able to make this optimization since the do_stuff_to_foo method (a black box to the compiler) could save its argument, and the caller of blah() could see that the argument it passed has the same address as the local f object in blah, a violation of "distinct objects, distinct addresses".
C++ has a the RVO escape hatch for this: it is expected that some objects that appear distinct in the source may not actually be distinct if they fit the RVO (or NVRO) pattern - but C does not. So perhaps gcc and clang are doing the right there here.
---
[1] All numbered versions of clang up to 6.0 seem to behave the way indicated in the GP post, but trunk in godbolt, which shows version as 7.0.0 (trunk 333657) compiles C efficiently like C++.
In that case though, I think clang is right to optimize the callee (but it does introduce a problem in the caller) :
the only place you could do the equality check and observe the rule being broken is before the callee returns since the lifetime of its variable is bound to the call.
It seems that clang will not let the return pointer alias a local in the caller except when the call is the initialization of said local.
So if the caller goes :
foo x; leak(&x); x = returns_foo();
the memory will be temporary stack (and then memcpy), thus upholding the rule. (and it seems to me that this inefficiency is really required to respect the standard if we actually leak the pointer)
in the case :
foo x = returns_foo();
clang will pass the actual address of x down but that's before the object exists (and its address cannot be known yet) so the rule is still fine.
I stand corrected though, this does mean that RVO would be useful for C as well, as a way to relax the aliasing rule.
edit: nevermind that, in the first case it's perfectly legal to read/write foo through the pointer downstream so you cannot make the optimization anyway.
Here's an example:
This happens on clang versions back 3.6.
Note that if you change the caller to:
Foo f;
f = callee(&f);
the code changes and distinct objects are passed. I'm not sure if the first form (all in the definition) has a relevant difference per the standard that lets clang do this.If the assignment is in the initializer then its using the simple C++ RVO-style call to blah():
void zot() {
foo f = blah();
}
zot:
push rbp
mov rbp, rsp
sub rsp, 1040
lea rdi, [rbp - 1040]
call blah
add rsp, 1040
pop rbp
ret
But if the variable has the opportunity to leak then it adds a memcpy in the caller: void zot() {
foo f;
leak(&f);
f = blah();
}
zot:
push rbp
mov rbp, rsp
sub rsp, 2080
lea rdi, [rbp - 1040]
call leak
lea rdi, [rbp - 2080]
call blah
mov eax, 1036
mov edx, eax
lea rdi, [rbp - 1040]
lea rcx, [rbp - 2080]
mov rsi, rcx
call memcpy
add rsp, 2080
pop rbp
ret
Although weirdly the memcpy is removed when optimizations are turned on. This may be a bug.I updated my comment with some assembly.
I guess you could say that RVO is more robust since it's implemented in the frontend and does not rely on finding the optimization after a fair amount of lowering.
Edit: I don't have time to debug this but at least for llvm, I think this optimization should trigger in the optimizer's memcpy elimination pass ( https://github.com/llvm-mirror/llvm/blob/0818e789cb58fbf6b5e... ).
However I don't see why clang could not simply apply the RVO logic to C code as well.
Seeing as blah isn't a static function, I think the calling convention for C that g++ uses somehow dictates that a memcpy is to be used in this case.
Note that I haven't acually tried this, so no guarantees.
> sg_pipeline sg_alloc_pipeline() {
> should really be
> sg_pipeline sg_alloc_pipeline(void) {
Ah thanks, I fixed that :)
In the case of sokol-gfx, missing return value optimization won't be a big deal, but I'll keep that in mind.
(btw i was talking about Clang, not GCC above)
What do you mean by this, exactly? You mean leaving it to RAII instead of doing it explicitly?
the memcpy feature, on the other hand, might be unexpected enough to escalate to something worth fretting about..
Regarding the assembly example. If the copy matters performance-wise (note: it doesn't!) then DON'T MAKE A COPY. Have a pointer argument and put the result there.
it sure does, especially if you're going to make a high performance graphics library. Some old benchmarks I found were on an average of 10-15% performance loss if calling non-RVO'ed code in some tight loop.
That was tongue-in-cheek. Of course you can always find a slow instance for any approach.
The more explicit message is: You're optimizing the wrong thing. "Tight loop" and "RVO", these things don't go together. Don't write slow and complicated code and expect the compiler to magically make it fast. Write straightforward code. It's easy. It will be effortlessly fast.
There are very few cases where you need to work hard to get fast code (SIMD etc). Typically, if you need to work hard, the code will be slow.
To put it another way, RAII is a hack which co-opts one semantic to cover the drawbacks of another semantic. Without exceptions there's no need for RAII because there's no problem to solve.
RAII is about any scope exit automatically cleaning up resources. Exceptions is a big one, but so is return, break, etc. Having it happen automatically in all cases is a win for robust software (in my opinion).
Note that am not arguing that RAII is unecesary, it is just I completely agree with the author that RAII is much less needed in C then in C++ due to different code style and structure. Plus there are static code checkers and/or compiler options that allows to enforce various RAII patterns in C.