c++ - 确定 GetElementPtr 的字节偏移量

标签 c++ c compiler-construction llvm llvm-ir

这是一个简单的 C 程序:

struct S {char c; short arr[16]; char dummy2;};

extern struct S A[20];
extern short* p;

int main() {
    p = &A[10].arr[6];
    return 0;
}

这是 LLVM IR:

%struct.S = type { i8, [16 x i16], i8 }

@A = external global [20 x %struct.S]
@p = external global i16*

; Function Attrs: nounwind
define i32 @main() #0 {
entry:
  store i16* getelementptr inbounds ([20 x %struct.S]* @A, i64 0, i64 10, i32 1, i64 6), i16** @p, align 8, !tbaa !1
  ret i32 0
}

我如何计算 getelementptr 添加到 @A 的字节偏移量? ?

我可以很容易地遍历并打印出 GEP:

  auto& P = *GEP.getPointerOperand();
  Out << "GEP(";
  GEP.getType()->print(Out); // return type
  Out << ", ";
  P.printAsOperand(Out); // base
  for (auto i=0U; i<GEP.getNumIndices(); i++) {
    Out << ", ";
    GEP.getOperand(i+1)->printAsOperand(Out); // index i
  }
  Out << ")\n";

这打印:

 GEP(i16*, [20 x %struct.S]* @A, i64 0, i64 10, i32 1, i64 6)

假设所有索引都是常量整数,如何确定相对于基指针的字节偏移量?

最佳答案

你能使用 ptrtoint 指令并减去它们吗?

关于c++ - 确定 GetElementPtr 的字节偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32444497/

相关文章:

c++ - 当 A=LLt 时求解 Lx=b 和 Px=b

c++ - 防止或阻止 cpu 数据缓存加载

c - 使用 fscanf 和 malloc 的段错误

c++ - 我什么时候应该定义自己的复制构造函数和赋值运算符

c++ - 常量全局变量模板

c++ - 为什么 C 或 C++ 标准不明确将 char 定义为有符号或无符号?

.net - 用于 .NET 的 IL 编译器?

java - 在mac终端上编译并运行java程序

c++ - 段错误错误 C++

c - 使用 Erlang 的 NIF,我应该如何在 ERL_NIF_TERM 上使用 malloc?