by turndown · 3y ago · 0 comments
This line lives in fear of the optimizer. sparse[i] references uninitialized memory and is thus UB and could be optimized out at a certain level. Also I think I read once that even if we’ll allow that sparse[i] stays in the program, there’s still no guarantee that each access of sparse[i] will read the same value since it’s still UB.
stop_messing_with_my_code:
mov rax, rdi
ret
extern "C" void *stop_messing_with_my_code(void *);
void *p = stop_messing_with_my_code(malloc(100));
// compiler cant know what my function does, it might have initialized it,
// aligned it properly, returned the correct, type, etc.
Also useful for getting around the idiotic type-based aliasing so you can write custom allocators (i.e a byte pool allocated statically/globally, then allocate data from that which is common in embedded, which is technically not possible in standard C or C++...)Is it? I thought that char-pointers-into-char-arrays are specifically allowed to alias with whatever type.
But yeah, it's a shame we don't have an official "launder" function a-la C++: the malloc/calloc/realloc get to launder the pointers they return simply because the standard declares those functions special.
I think they mean something like this:
char storage[1024];
struct pool pool_of_foos = { storage, sizeof(storage) }; // use storage as my memory
struct foo *p = pool_allocate(&pool_of_foos, sizeof(struct foo));
// pool_allocate cannot be implemented in conforming C or C++.
// i.e you cannot place a 'struct foo object' in the memory location containing 'char objects'
How can malloc() work then you might ask? Well it has defined semantics in the standard, so its essentially a magical special exception, you cannot write such a function yourself in standard C, you must use compiler extensions or assembly.Which is quite insane that it has come to this, I doubt K&R had that as their intention for the language.
But C++ has std::launder that allows you to do that, see the very last example in [0]: it does placement-new on a char array, then launders the pointer to that array recasted as a pointer-to-struct, and it's supposed to not be UB.
asm volatile("" : "+r"(my_val) ::);
This means "an empty assembly statement that you must assume contains side effects, and takes my_val as an input register and modifies it somehow." Note that because there is no assembly, this is perfectly portable (across architectures, maybe not across compilers, since only GCC and Clang know this syntax).I've used it to get the compiler to forget that function pointers cannot be null, for example.
Of course you are still in "implementation defined behavior" land re: the standard. But it's often pretty easy to reason like the compiler does once you know your target architecture, and once your values are all unconstrained integers.
Even if you construct a degenerate case:
int* sparse = (int*)malloc(100 * sizeof(int));
int x = sparse[40]; // provably unitialized
it still won't "optimize out" the access, since1. it's insane. nobody would write such an optimization because there's no possible performance gain, and it changes program behavior
2. malloc is just a function, it's not treated in any special way
3. there's no guarentee this malloc is a per-spec malloc, it can be a user-defined function for which this is perfectly valid
LLVM explicitly has an 'undef' constant value which facilitates this optimization. https://llvm.org/docs/LangRef.html#undefined-values
FWIW, the most important reason compilers do this is to decrease compile time. The compiler notices that some code has undefined behaviour and deletes the code now instead of waiting to prove that the path to this code is unreachable. The later optimizations tend to be slower and scale badly with more code in the function, so deleting it earlier will speed up the compilation.
> 2. malloc is just a function, it's not treated in any special way
The compiler is full of optimizations that treat malloc and other functions specially. This file implements an analysis, but the results of the analysis is used by transformations. https://github.com/llvm/llvm-project/blob/main/llvm/lib/Anal...
> 3. there's no guarentee this malloc is a per-spec malloc, it can be a user-defined function for which this is perfectly valid
Yep, there's a flag for that mode, `-ffreestanding` which corresponds to freestanding mode in the C89 standard, section 2.1.2.1. Without that flag, we assume malloc, strlen, etc., are the standard library functions that do as described in the standard.
...created only by adversarial compiler writers who seem to be as user-hostile as a lot of other "developers" these days. They can get away with being pedantic assholes, because they know that realistically no one is going to switch compilers that easily.
That said, C and even C++ used to not be like this.
The simple truth is a lot of UB exists to allow for optimizations that programmers entirely take for granted. In order to optimize something, you have to make assumptions, particularly when dealing with languages as permissive as C and C++. By programming to an abstract machine and explicitly specifying which behavior is defined and which is not, we allow a compiler to make these assumptions. Despite what you may wish, a compiler is not able to read your mind to know when a given piece of UB is actually code that you intended to execute with particular semantics, or whether it's the result of some other optimizations on a code path that will never execute.
#include <stdlib.h>
int foo(int x) {
int* p = malloc(1024);
x = p[x];
free (p);
return x;
}
assembly: foo: # @foo
ret
https://godbolt.org/z/jfvKon5v7asm:
foo: # @foo
push rbx
mov ebx, edi
mov edi, 1024
call malloc@PLT
movsxd rcx, ebx
mov ebx, dword ptr [rax + 4\*rcx]
mov rdi, rax
call free@PLT
mov eax, ebx
pop rbx
ret
https://godbolt.org/z/E6Teqns8bclang optimizes this function to a single ret, optimizing away not just the memory access, but the call to malloc() as well. I does this (and is allowed to do this) because it recognizes that sparse[40] accesses uninitialized memory, which is UB, and therefore anything goes – including replacing the entire function with a no-op.
Well, I think the compiler is just thinking that the control flow of a correct program cannot cause UB, so the path causing UB is infeasible path and is optimized away. E.g. https://godbolt.org/z/h69GnfYbd where the path causing UB is optimized away and it just returns 42 (and a call to rand).
/* Allocate SIZE bytes of memory. */
extern void *malloc (size_t __size) __THROW __attribute_malloc__
__attribute_alloc_size__ ((1)) __wur;
Expanding macro gives three GCC function attributes [2]: `__attribute__ ((malloc))`, `__attribute__ ((alloc_size(1)))` and `__attribute__ ((warn_unused_result))`. They are used for GCC (and others recognizing them) to actually ensure that they behave as the standard dictates and give better error messages. Your own malloc-like functions won't be treated same unless you give similar attributes.[1] https://github.com/bminor/glibc/blob/807690610916df8aef17cd1...
[2] https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attribute...
1. a specific optimisation pass won't do this, but the combination of several passes written with other intentions can
2 & 3. the C runtime a compiler links with is known to the compiler/linker, and it _does_ usually treat intrinsics like malloc specially
A quick google reveals https://github.com/llvm/llvm-project/issues/52930, LLVM recognising uninitialised memory as 'undef', and needing to treat it as poisoned (IIRC propogation of undef can cause things like separate uses of the variable to not even unify to a single value)
EDIT: duplicated link
Or use optimization barriers as described elsethread.