【问题标题】:Is there a way to distinguish pointer types in llvm ir?有没有办法区分llvm ir中的指针类型?
【发布时间】:2020-05-27 18:49:07
【问题描述】:

我正在尝试优化 llvm ir 中的代码,意识到 Types - isPointerTy 不区分 *i8、*i16、*i32、*i64。打印出它们的类型值显然会给出不同的值。下面是我用来检测问题的代码。

在 C 中:

...
if (CallInst *CI = dyn_cast<CallInst>(UsrI)) {
   if (CI->getCalledFunction()->getReturnType() ->isPointerTy()){
      outs() << "Calling func with ptr return = " << CI->getCalledFunction()->getName() << "\n";
      outs() << CI->getCalledFunction()->getReturnType() << "\n";
   }
}
...

在 llvm 中:

...
if.end:
    %test3 = call i64* @malloc64(i64 %mul)
    %call = call i32* @malloc32(i64 %mul) #4
    %test = call i16* @malloc16(i64 %mul)
    %test2 = call i8* @malloc8(i64 %mul)
...
declare i8* @malloc8(i64)
declare i16* @malloc16(i64)
declare i16* @malloc16(i64)
declare i16* @malloc16(i64)

显示输出为

使用 ptr return = malloc8 调用 func
0x1c56e90
使用 ptr return = malloc16 调用 func
0x1c56e20
使用 ptr return = malloc32 调用 func
0x1c56db0
使用 ptr return = malloc64 调用 func
0x1c56d40

我尝试检查了许多 llvm 文档,但我错过了一些东西。任何关于我如何检查确切指针类型的建议都将不胜感激。

【问题讨论】:

    标签: llvm


    【解决方案1】:

    isPointerTy 方法不区分不同的类型,它只是告诉truefalse 类型是否为指针。

    解决问题的一种方法是查看它的底层 pointee 类型(指针指向的类型)。

    你可以这样做:

    Type *returnType = CI->getCalledFunction()->getReturnType();
    if (PointerType *pointerType = dyn_cast<PointerType>(returnType)) {
      llvm::Type *pointeeType = pointerType->getElementType();
      /// the pointee type now holds one of i8, i16, i32, or i64
      if (IntegerType *intType = dyn_cast<IntegerType>(pointeeType)) {
        outs() << intType->getBitWidth() << "\n";
      }
    }
    

    第二行尝试将一般的Type * 转换为更特殊的PointerType *。如果returnType 不是PointerTypedyn_cast 返回有效指针或nullptr

    然后,您可以访问指针类型(通过getElementType)并可以进行进一步检查。在您的示例中,所有底层类型都是IntegerTypes,区分它们的方法是检查它们的位宽。

    我想这应该会有所帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-14
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      • 2018-01-12
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      相关资源
      最近更新 更多