识别IR中的数组类型

sha*_*ran 3 llvm

我一直在尝试通过使用以下代码来识别IR中的数组访问:

  for (BasicBlock::iterator ii = BB->begin(), ii2; ii != BB->end(); ii++) {
     Instruction *I=ii;             
    if(GetElementPtrInst *getElePntr = dyn_cast<GetElementPtrInst>(&*I))
    {                   

        Value *valAlloc = (getElePntr->getOperand(0));

        if(getElePntr->getOperand(0)->getType()->isArrayTy())
            {
                errs()<<"\tarray found";
            }
    }  
 }  
Run Code Online (Sandbox Code Playgroud)

此代码标识getElementPtr指令,但它不识别它的第一个操作数是否是数组类型.请告诉我我的代码有什么问题.

Eli*_*sky 5

GEP(getelementptr指令)的第一个操作数是指针,而不是数组.该指针可能指向一个数组,或者它可能没有(见下文).所以你需要看看这个指针指向的是什么.

这是一个访问样本BasicBlockPass:

virtual bool runOnBasicBlock(BasicBlock &BB) {
    for (BasicBlock::iterator ii = BB.begin(), ii_e = BB.end(); ii != ii_e; ++ii) {
        if (GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(&*ii)) {
            // Dump the GEP instruction
            gep->dump();
            Value* firstOperand = gep->getOperand(0);
            Type* type = firstOperand->getType();

            // Figure out whether the first operand points to an array
            if (PointerType *pointerType = dyn_cast<PointerType>(type)) {
                Type* elementType = pointerType->getElementType();
                errs() << "The element type is: " << *elementType << "\n";

                if (elementType->isArrayTy()) {
                    errs() << "  .. points to an array!\n";
                }
            }
        }
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)

但请注意,C/C++中的许多"数组"实际上都是指针,因此您可能无法获得所期望的数组类型.

例如,如果您编译此代码:

int main(int argc, char **argv) {
  return (int)argv[1][8];
}
Run Code Online (Sandbox Code Playgroud)

你得到了IR:

define i32 @main(i32 %argc, i8** %argv) nounwind uwtable {
  %1 = alloca i32, align 4
  %2 = alloca i32, align 4
  %3 = alloca i8**, align 8
  store i32 0, i32* %1
  store i32 %argc, i32* %2, align 4
  store i8** %argv, i8*** %3, align 8
  %4 = load i8*** %3, align 8
  %5 = getelementptr inbounds i8** %4, i64 1
  %6 = load i8** %5
  %7 = getelementptr inbounds i8* %6, i64 8
  %8 = load i8* %7
  %9 = sext i8 %8 to i32
  ret i32 %9
}
Run Code Online (Sandbox Code Playgroud)

尽管argv视为数组,但编译器将其视为指针,因此看不到数组类型.我上面粘贴的传递在这里不会识别数组,因为GEP的第一个操作数是指向指针的指针.