c++ - 确定数组索引

标签 c++ llvm-ir

我在 C 代码中有以下循环:

int f[10],b[10],k=0;
for(int i = 0; i < 10; i++)
{
    k = b[i+3]*f[i+2]; //please ignore the out of bound problem
}

我想在上面的代码中确定数组 b 的步幅为 3,f 的增量因子为 2。

生成的 LLVM 程序集是(对于包含循环的 block ):

;<label>:12
%13 = load i32* %i, align 4
%14 = icmp slt i32 %13, 10
br i1 %14, label %15, label %30

;<label>:15                         ;preds=%12
%16 = load i32* %i, align 4
%17 = add nsw i32 %16,**3** // this is the increment value
%18 = sext i32 %17 to i64
**%19 = getelementptr inbounds [10 x i32]* %b, i32 0, i64 % 18**
%20 = load i32* % 19, align 4
%21 = load i32* %i, align 4
%22 = add nsw i32 %21,**2** // this is the increment value
%23 = sext i32 %22 to i64
**%24 = getelementptr invounds[10xi32]* %f, i32 0, i64 %23**
%25 = load i32* %24, align 4
%26 = mul nsw i32 %20, %25
store i32 %26, i32* %k, align 4
br label %27

;<label>:27
%28 = load i32* %l, align 4
%29 = add nsw i32 %28,1
store i32 %29, i32* %i, align 4
br label %12

现在在我的 LoopPass 中,我使用以下代码:

Value *f = gep->getOperand(3);
if(dyn_cast<llvm::ConstantInt>(f))
{
    errs()<<(dyn_cast<llvm::ConstantInt>(f))->getValue();
   // the output should be 3 and 2 respectively

}

但是我没有得到任何输出。我在这里做错了什么?

最佳答案

首先,从ConstantInt 实例获取整数的正确方法是通过getSExtValue(),而不是getValue();最好您还确保可以处理返回值,因此:

assert (CI->getBitWidth() <= 32);
int x = CI->getSExtValue();

其次,仅获取作为第三个操作数传递给 GEP 的值不会为您提供 ConstantInt,它会为您提供指向 sext 指令的指针!如果你想找到实际的常量,你必须一直往回遍历图,直到找到 add 指令,然后将常量标识为它的操作数之一。

最后,您似乎在寻找偏移量,而不是步骤;但如果您正在寻找步骤,请考虑使用标量演化,它具有您可能会觉得有用的机制,例如:

/// getStepRecurrence - This method constructs and returns the recurrence
/// indicating how much this expression steps by.  If this is a polynomial
/// of degree N, it returns a chrec of degree N-1.
/// We cannot determine whether the step recurrence has self-wraparound.
const SCEV *getStepRecurrence(ScalarEvolution &SE) const

关于c++ - 确定数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13171731/

相关文章:

c++ - 我怎样才能得到一个 v8 函数来返回一个 C++ 对象?

c++ - 为什么编译不会失败?

llvm - 了解 LLVM IR 中的 bitcast

c - 我的编译器如何找到 stat(文件状态)函数?

c++ - 如何为 Tesseract 构建静态二进制文件?

c++ - 遍历对象 vector

c++ - 尝试在 qt 中创建访问器函数

pointers - llvm中有符号执行工具吗?

x86 - 如何在 LLVM 中获取 IR 指令的操作码长度

debugging - 如何使用 lldb 获取 llvm::Value 的类型