r/Compilers • u/Repulsive_Egg_5786 • Aug 14 '26
Optimization Question
How do compilers optimize constructs of this form ?
for(i=o; i<inputs; i++) {
A[i] = B[i];
B[i] = A[i];
}
7
Upvotes
r/Compilers • u/Repulsive_Egg_5786 • Aug 14 '26
How do compilers optimize constructs of this form ?
for(i=o; i<inputs; i++) {
A[i] = B[i];
B[i] = A[i];
}
11
u/fernando_quintao Aug 14 '26
Hi u/Repulsive_Egg_5786. That depends on how much information you pass to the compiler. If you tell the compiler that the pointers don't overlap, both gcc and clang are able to use
memcpyto copyBintoA. E.g., you can try it in godbolt:When I compile it with gcc 16.1 (ARM), at -O2, I get:
If you remove
restrict, then the compiler can no longer guarantee A and B don't point to overlapping memory regions. Then it will implement the copy with a loop. Here's what I got in godbolt:3
u/EggplantExtra4946 Aug 14 '26 edited Aug 14 '26
This question doesn't make any sense, you need to write the optimized code you expect and I assume your question will then be "how does the compiler can make this optmization?".
1
u/choikwa Aug 14 '26
do u mean a swap? else the B assignment is redundant