1

I know how to store a int variable 'x' in LLVM code, I would use the command:

  store i32 1, i32* %x

If I then want to pull '%x' out and use it in a command such as add, how would I do that?

%Temp1 = add i32 1, %x

Basically asking how to reference the store

arrowd
  • 33,231
  • 8
  • 79
  • 110
billybob2
  • 681
  • 1
  • 8
  • 17
  • 4
    [load](https://llvm.org/docs/LangRef.html#load-instruction). – arnt Sep 25 '18 at 06:16
  • I may have this mixed up, but isn't `i32 * %x` using `%x` *as a pointer*? So it's not storing the value in `%x`, it's storing it in `*%x`, the memory pointed-to by `%x`. If you just want locals, you use assignment, not store/load, and let the compiler choose to spill/reload if it needs to. – Peter Cordes Sep 25 '18 at 07:34
  • 2
    @PeterCordes It's common to represent local variables as pointers to `alloca`ed memory and then let the compiler decide whether to replace the `alloca` using registers or not. That way you don't have to translate the assignments into SSA form yourself and don't have to bother with phi nodes. – sepp2k Sep 25 '18 at 11:28
  • @sepp2k: Thanks, that makes sense. I haven't played around with LLVM-IR. @billybbbob2: you can see compiler-generated LLVM-IR for C functions if you compile with the right options. [How to make clang compile to llvm IR](https://stackoverflow.com/q/9148890). With `clang -O0`, there are LLVM-IR load and store instructions for locals: https://godbolt.org/z/fqzjbT – Peter Cordes Sep 25 '18 at 11:35

1 Answers1

1

As one of the commenters replied the solution is to use the load instruction. When you use the store instruction in LLVM you write to some memory address.

To read the said variable and save it into a virtual register you use the load instruction.

For instance, consider the following function that adds two integers.

define i32 @add(i32, i32) {
  %3 = alloca i32
  %4 = alloca i32
  store i32 %0, i32* %3
  store i32 %1, i32* %4
  %5 = load i32, i32* %3
  %6 = load i32, i32* %4
  %7 = add i32 %5, %6
  ret i32 %7
}

The first two lines allocate memory on the stack for two integers that are four bytes in size. We then write the value of the function arguments to these locations. Before we can use add we load these two variables from memory into the virtual registers %5 and %6. The add instruction is then executed, with the result assigned to the virtual register %7.

We then return the result of the computation using the ret instruction which is also the only terminator of the single basic block that makes up this example function.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
JKRT
  • 1,179
  • 12
  • 25