识别IR中的阵列类型 [英] Identify array type in IR
问题描述
我一直在尝试通过使用以下代码来识别IR中的阵列访问:
I have been trying to identify array access in IR by making use of following code:
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";
}
}
}
此代码标识getElementPtr指令,但不能标识其第一个操作数是否为数组类型.请让我知道我的代码有什么问题.
This code identifies getElementPtr instruction but it does not identify whether it's first operand is an array type or not. Please let me know what is the problem with my code.
推荐答案
GEP(getelementptr
指令)的第一个操作数是指针,而不是数组.该指针可能指向一个数组,也可能指向一个数组(请参见下文).因此,您需要查看此指针指向的内容.
The first operand of a GEP (getelementptr
instruction) is a pointer, not an array. That pointer may point to an array, or it may not (see below). So you need to look what this pointer points to.
以下是示例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;
}
但是,请注意,C/C ++中的许多数组"实际上都是指针,因此您可能无法在所需的位置获得数组类型.
Note, however, that many "arrays" in C/C++ are actually pointers so you may not get the array type where you expect.
例如,如果您编译此代码:
For example, if you compile this code:
int main(int argc, char **argv) {
return (int)argv[1][8];
}
您获得了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
}
尽管argv
被视为 作为数组,但编译器将其视为指针,因此看不到数组类型.我上面粘贴的代码在这里无法识别数组,因为GEP的第一个操作数是指向 a 的指针.
Although argv
is treated as an array, the compiler thinks of it as a pointer, so there is no array type in sight. The pass I pasted above won't recognize an array here, because the first operand of the GEP is a pointer to a pointer.
这篇关于识别IR中的阵列类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!