[llvm-dev] Aliasing rules for const type pointer

Tim Northover via llvm-dev llvm-dev at lists.llvm.org
Tue Jun 11 01:26:59 PDT 2019


Hi Ashutosh,

On Tue, 11 Jun 2019 at 06:32, Nema, Ashutosh via llvm-dev
<llvm-dev at lists.llvm.org> wrote:
> In this test case the type for “C” is const int * type, it means the pointer is pointing to a memory which is of type constant.
>
> My understanding is value at *C can’t be modified in the program, so its invariant and possibly can be hoisted.

This isn't quite right. In C and C++, const applies to a specific
pointer, and only rarely to the underlying memory[*]. A given object
is often accessed through both const and non-const pointers througout
its lifetime.

What const really means on a function like your foo is that the writer
of foo has promised not to modify C through that pointer (and even
that might only be an approximation since you can cast the const
away). It's still possible for the caller to pass the same object in
through A or B (as you say later), and depending on foo's contract
that may be perfectly legitimate or an API violation. The compiler
doesn't know which, so it can't assume they don't alias.

Think about memmove for a concrete example which is very close to your
foo: the source is a const pointer, but it's explicitly allowed to
overlap with the dest.

Cheers.

Tim.

[*] The memory itself is usually const for literal strings, and
sometimes global variables declared const. Situations where the
compiler knows that an object is immutable where it's actually
allocated.


More information about the llvm-dev mailing list