How to tell LLVM that pointers don't alias or they are equal?

With __restrict this code generates memcpy call

void copy(int  *__restrict a, int  *b, int size) {
    for(int i=0; i<size; i++) {
        a[i] = b[i];
    }
}

However, without __restrict it does not.

What I want to do is to tell the compiler, that a could intersect with b only if a and b are same pointers (or in other words, a and b point to the start of memory region), so it can generate check and memcpy. It could be useful for languages like java, where arrays could not partially intersect.

Is there any LLVM metadata, that could express that semantics?

1 Like

Maybe you are searching for noalias: LLVM Language Reference Manual — LLVM 17.0.0git documentation?

For your example with __restrict the IR function that is created looks like:

define dso_local void @copy(ptr noalias nocapture noundef writeonly %0, ptr nocapture noundef readonly %1, i32 noundef %2)

while without __restrict the noalias is missing:

define dso_local void @copy(ptr nocapture noundef writeonly %0, ptr nocapture noundef readonly %1, i32 noundef %2)

You can add the check yourself.
If you generate IR and can add metadata, you might as well just generate something to the effect of

if (a == b)
  do nothing/slow path
else
  memcpy(...)