2012-11-13 136 views
5

我一直在尋找小時,我找不到任何可以幫助我的東西。我正在開發一個涉及FunctionPass的項目。我已經實現了runOnFunction(函數& f)方法,這工作正常。基本上它需要:如何插入LLVM指令?

1)檢測存儲指令

2)轉換存儲指令的存儲器地址爲Integer

3)使用按位與運算(0000FFFF改變整數)

4)轉換整數回指針

到目前爲止,我有以下幾點:

virtual bool runOnFunction(Function &F) { 
    for (Function::iterator bb = F.begin(), bbe = F.end(); bb != bbe; ++bb) { 
    BasicBlock& b = *bb; 
    for (BasicBlock::iterator i = b.begin(), ie = b.end(); i != ie; ++i) { 
     if(StoreInst *si = dyn_cast<StoreInst>(&*i)) { 
     PtrToIntInst* ptrToInt = new PtrToIntInst(si->getPointerOperand(), IntegerType::get(si->getContext(), 32), "", si); 
     } 
    } 
    } 
    return true; 
} 

我不能爲我的生活弄清楚如何實際插入指令,甚至找到一種方法來創建一個AND指令。如果有人能指出我的方向正確,那會很棒。

在此先感謝。

回答

4

我推薦看看​​- 它有一個相當不錯的基本覆蓋。

特別是,有a section about creating and inserting new instructions。最簡單的方法就是提供一個現有指令作爲新指令構造函數的最後一個參數,然後該指令將立即在現有指令之前插入該指令。

或者,您可以傳遞封閉的基本塊,如果你只是想添加到它的最後(但記住你需要照顧終結者!)。最後,您可以在封裝的基本塊上調用getInstList(),然後在insertpush_back上插入新的指令。另外,您不必遍歷所有塊,然後遍歷每個塊中的所有指令,您可以直接迭代指令;見the section about the instruction iterator in the programmer's manual

+0

在通過封閉基本塊的情況下,你如何照顧終結者? – PatoBeltran

+1

@PatoBeltran以這種方式添加指令不會觸發對基本塊的驗證,因此您可以在這些中間階段中使用格式不正確的基本塊。在結束傳球功能之前,請務必在最後放置一個終結器。 – Oak

4
virtual bool runOnFunction(Function &F) { 
    for (Function::iterator bb = F.begin(), bbe = F.end(); bb != bbe; ++bb) { 
    BasicBlock &b = *bb; 
    for (BasicBlock::iterator i = b.begin(), ie = b.end(); i != ie; ++i) { 
     if (StoreInst *si = dyn_cast<StoreInst>(&*i)) { 
     IRBuilder Builder(si); 
     Value *StoreAddr = Builder.CreatePtrToInt(si->getPointerOperand(), Builder.getInt32Ty()); 
     Value *Masked = Builder.CreateAnd(StoreAddr, 0xffff); 
     Value *AlignedAddr = Builder.CreateIntToPtr(Masked, si->getPointerOperand()->getType()); 
     // ... 
     } 
    } 
    } 
    return true; 
} 
0

您可以使用IRBuilder輕鬆地在另一條指令之前或在基本塊的末尾插入新指令。

替代地,如果需要後插入一個指令另一個,則需要在含有基本塊使用instruction list

BasicBlock *pb = ...; 
Instruction *pi = ...; 
Instruction *newInst = new Instruction(...); 

pb->getInstList().insertAfter(pi, newInst); 

代碼和從here採取溶液。