How to correctly store value to pointer and then dereference

What I’m trying to do is take a pointer to “i” on “x” and then assign a value to “x” (like a dereference) and then finally dereference “x” again and pass that to a function call.

I’m confused about why the first version works but doesn’t need to do the usual load a temporary, like the failed version does. If I don’t store the value on x this second version does work, so what am I doing wrong?

Thanks again.

Works:

  store i64 3, ptr @i, align 4
  store ptr @i, ptr @x, align 8
  store i64 1, ptr @x, align 4
  %x = load i64, ptr @x, align 4
  call void @PrintNum(i64 %x)

Fails:

  store i64 3, ptr @i, align 4
  store ptr @i, ptr @x, align 8
  store i64 1, ptr @x, align 4
  %x = load ptr, ptr @x, align 8
  %x1 = load i64, ptr %x, align 4
  call void @PrintNum(i64 %x1)

In the second version, the code fails because of an incorrect usage of the load instruction. Specifically, in the line %x = load ptr, ptr @x, align 8, you are attempting to load a pointer value from the address stored in @x. This is incorrect because the type specified for the load instruction should match the type of the value being loaded which is i64

OK I see what you mean. This is basically what I’m try to do.

int main() {
    int i = 3;
    int *x = &i;
    *x = 1;
    // then printf the value at *x
}

I can’t figure out how to get Godbolt to use LLVM 16 so it doesn’t have opaque pointers but here is the version I found a template for. It looks like what I did wrong was the store to %0 and I changed the type.

  %i = alloca i32, align 4
  %x = alloca i32*, align 8
  store i32 3, i32* %i, align 4
  store i32* %i, i32** %x, align 8
  %0 = load i32*, i32** %x, align 8
  store i32 1, i32* %0, align 4

While I did store i64 1, ptr @x, align 4 and changed the type. Is that correct? I’m clearly still struggling with the basics :slight_smile: thanks.

Btw, does anyone know how to get LLVM 16 in Godbolt? This is what I see, but how can you change the LLVM IR part?