Telling the C optimizer that a pointer's contents won't be modified

Hugo Musso Gualandi hgualandi@inf.puc-rio.br
Thu Mar 11 15:29:51 GMT 2021


Hi everyone,

Does anyone know if there is a way to tell the C compiler that a 
pointer's contents won't change after a function call? For example, if 
I compile the following code with -O2 then GCC 10 can optimize away the 
second pointer dereference in "f" but not in "g". 
https://godbolt.org/z/5P3rxn

    void reader(const int *p);

    int f(int *p) {
        int x = *p;
        int y = *p;
        return x + y;
    }

    int g(int *p) {
        int x = *p;
        reader(p);
        int y = *p;
        return x + y;
    }

Note how there is a single "movl" in the first case but two in the 
second:

    f:
            movl (%rdi), %eax
            addl %eax, %eax
            ret
    g:
            pushq %rbp
            pushq %rbx
            movq %rdi, %rbx
            subq $8, %rsp
            movl (%rdi), %ebp
            call reader
            movl (%rbx), %eax
            addq $8, %rsp
            popq %rbx
            addl %ebp, %eax
            popq %rbp
            ret

I also tried using restrict but the result was still the same.

    // The generated ASM was still the same even with restrict.
    int g(int * restrict p) {

Is there a way to tell the optimizer that the "reader" function won't 
modify the contents of "p"? The context of this is that I'm working 
with a compiler that uses C as a compilation target. We can rely on GCC 
to optimize most things I can't figure out how help it optimize this 
one...

-- Hugo




More information about the Gcc-help mailing list