有没有办法知道在LLVM中使用alloca指令创建的堆栈分配局部变量的堆栈地址

Is there any way to know the stack address of stack allocated local variable created using alloca instruction in LLVM

我有一个简单的添加程序。

int main() {

    int x=10,y=10,result=0;
    result=x+y;
    return 0;
}

我创建了一个 LLVM 前端模块 pass,它可以遍历整个模块。

所以我的遍遍历基本块并获取指令。

FORE(iter, (*bb)) {
    if(isa<AllocaInst>(iter)) {
        errs()<<"The address of allocated variable is "<<&(*iter);
    }
} 

它的输出是alloca指令的地址,而不是局部变量的实际堆栈地址。

有什么方法可以使用pass获取局部变量的栈地址吗?

你不能。

甚至无法保证当您多次 运行 程序时变量的地址相同(参​​见 Address Space Layout Randomization),因此无法静态预测地址。

即使我们确实知道堆栈始终从固定地址开始,但在不同的函数调用期间,同一个变量具有不同的地址是完全正常的。以此为例:

#include <stdio.h>

void f() {
  int x;
  printf("The address of x is: %p\n", &x);
}

void g() {
  int y;
  f();
}

int main() {
  f();
  g();
  return 0;
}

假设您在没有优化的情况下编译它(这将删除 y 的定义),这将为 x 打印两个不同的地址。因此,当查看 f 的定义时,我们不可能预测其变量的地址,因为它甚至不会在程序的相同 运行 中相同。

此外,您的阶段不会知道在它之后 运行 将进行哪些优化,哪些变量将存储在寄存器中,或者哪个寄存器将溢出到堆栈内存 - 所有这些这会影响地址。