如何生成LLVM SSA格式

She*_*fer 5 llvm clang ssa llvm-clang llvm-ir

我编写以下C代码,其中变量X被分配了两次:

int main()
{
        int x;
        x = 10;
        x = 20;
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

使用以下命令编译并生成IR表示

clang -emit-llvm -c ssa.c
Run Code Online (Sandbox Code Playgroud)

产生红外线

; Function Attrs: nounwind uwtable
define i32 @main() #0 {
entry:
  %retval = alloca i32, align 4
  %x = alloca i32, align 4
  store i32 0, i32* %retval
  store i32 10, i32* %x, align 4
  store i32 20, i32* %x, align 4
  ret i32 0
}
Run Code Online (Sandbox Code Playgroud)

如果我对SSA格式的理解是正确的,则在此示例中,我们应将x1和x2视为生成的两个LLVM IR变量,并分别分配两个值10和20。我们应该使用一些特定的选项来获得SSA IR表示,或者我对IR表示的理解不正确吗?请指教。

编辑:正如一个答案中所建议的那样,使用-mem2reg优化传递会给我以下输出

clang -c -emit-llvm ssa.c -o ssa.bc
opt -mem2reg ssa.bc -o ssa.opt.bc
llvm-dis ssa.opt.bc
cat ssa.opt.ll
Run Code Online (Sandbox Code Playgroud)

产生的结果IR

; Function Attrs: nounwind uwtable
define i32 @main() #0 {
entry:
  ret i32 0
}
Run Code Online (Sandbox Code Playgroud)

看起来整个x分配都使用mem2reg优化进行了优化。还有其他产生和保留不同x值的方法吗?

arr*_*owd 4

LLVM 将mem2regreg2mem转换代码与 SSA 形式进行传递。您可以使用opt工具运行它们。