cclangllvmllvm-ir

What is the difference between my LLVM IR and Clang's


Currently I am working on a programming language that requires me to use LLVM. I am using clang as a reference because it uses LLVM too.

// The C code example I am using
int add(int num1, int num2){
    int result = num1 + num2;
    return result;
}
; The Clang output from compiling the C example code
define i32 @add(i32 noundef %0, i32 noundef %1) #0 {
  %3 = alloca i32, align 4
  %4 = alloca i32, align 4
  %5 = alloca i32, align 4
  store i32 %0, i32* %3, align 4
  store i32 %1, i32* %4, align 4
  %6 = load i32, i32* %3, align 4
  %7 = load i32, i32* %4, align 4
  %8 = add nsw i32 %6, %7
  store i32 %8, i32* %5, align 4
  %9 = load i32, i32* %5, align 4
  ret i32 %9
}
; My own version of the compiled C example code
define i32 @add(i32 %0, i32 %1) #0 {
  %2 = add nsw i32 %0, %1
  ret i32 %2
}

This is my version of the llvm ir generation

This is my first time using llvm and I am not sure what are the differences between those two code snippets in terms of speed and safety.


Solution

  • There is no "address of" operation in LLVM IR, but there is in C.

    When clang emits IR, it doesn't scan through variables to check whether it needs to allocate space on the stack for them, instead it always allocates space on the stack (the alloca instructions) and uses loads and stores to access the value. If the address is needed, the alloca instruction is the pointer. If the address is never needed, LLVM will clean it up in the optimization phase.