gpt4 book ai didi

assembly - 将文字值赋给 LLVM IR 中的局部变量

转载 作者:行者123 更新时间:2023-12-02 19:24:53 33 4
gpt4 key购买 nike

我一直在搞 LLVM IR 的代码生成,有一些我不太明白的事情,那就是何时必须分配局部变量以及如何将文字值加载到局部变量中的区别。如果我将以下简单的 C 代码编译为 LLVM IR,

//test.c
int main() {
int x = 3;
int y = x + 4;
return y;
}

我得到这个输出:

; ModuleID = 'test.c'
target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64-S128"
target triple = "x86_64-apple-macosx10.10.0"

; Function Attrs: nounwind ssp uwtable
define i32 @main() #0 {
%1 = alloca i32, align 4
%x = alloca i32, align 4
%y = alloca i32, align 4
store i32 0, i32* %1
store i32 3, i32* %x, align 4
%2 = load i32* %x, align 4
%3 = add nsw i32 %2, 4
store i32 %3, i32* %y, align 4
%4 = load i32* %y, align 4
ret i32 %4
}

attributes #0 = { nounwind ssp uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" }

!llvm.ident = !{!0}

!0 = metadata !{metadata !"Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)"}

我可以缩减到

target triple = "x86_64-apple-macosx10.10.0"

define i32 @main() {
%t1 = alloca i32
store i32 3, i32* %t1
%x = add nsw i32 0, 3

%y = add nsw i32 %x, 4
ret i32 %y
}

所以我想我的问题是,为什么它是一种将文字数字加载到变量中的迂回方法?有更好/更直接的方法吗?另外,为什么 %t1 需要进行 alloca 编辑,但 %x%y 不需要?

最佳答案

Clang 负责生成第一个代码段。 Clang 选择最简单的方法来为这些指令生成 IR——即为每条指令分配内存,然后存储和加载到该内存中。这创建了可以模拟 C 变量语义的 IR,可以在其整个生命周期中重新分配不同的值 - LLVM IR 中没有这样的东西(没有变量 - read more about SSA )。

不过,Clang 所做的只是编译的第一步。然后,该 IR 将经过多次转换(称为“传递”)。一人负责getting rid of the memory use ,正如您在第二个片段中所示的那样 - 这将允许稍后使用寄存器而不是堆栈来存储这些值。再次通过将 get rid of the unused value %t1,另一个将identify that constants are being used here and will replace the entire function body with return i32 7 ...等等。

综上所述,这不是一种“迂回方式”,它只是 Clang 生成 IR 的最简单方法,而让 IR 变得更好是后面 LLVM 传递的责任。

关于assembly - 将文字值赋给 LLVM IR 中的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24605063/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com