2012-03-13 20 views
2

我一直在試圖通過利用下面的代碼來識別紅外陣列訪問:確定陣列式紅外

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指令,但並不確定其是否是第一個操作數是一個數組類型或不。請讓我知道我的代碼有什麼問題。

回答

4

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; 
} 

但請注意,許多「陣列」,在C/C++實際上是指針,所以你可能不會得到你所期望的數組類型。

例如,如果您編譯此代碼:

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處理作爲數組,編譯器認爲它作爲一個指針,所以沒有陣列類型。我上面粘貼的pass在這裏不會識別數組,因爲GEP的第一個操作數是指向的指針