2015-02-11 20 views
1

首先我是clang/llvm的真正noob。clang將元數據設置爲allocainst

但我試圖修改clang的某種用途。

我想添加元數據,無論何時在IR代碼中發佈Alloca指令,以獲取具有某些註釋的變量。

我注意到CGDecl.cpp此功能:

CodeGenFunction::AutoVarEmission 
CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) 

包含到底好看線:

if (D.hasAttr<AnnotateAttr>()) 
     EmitVarAnnotations(&D, emission.Address); 

這看起來像我所需要的條件,所以我把它修改爲

if (D.hasAttr<AnnotateAttr>()) { 
     AnnotateAttr* attr = D.getAttr<AnnotateAttr>(); 
     if(attr->getAnnotation() == "_my_custom_annotation_") { 
      // set metadata... 
     } 
     EmitVarAnnotations(&D, emission.Address); 
    } 

我的問題是我不知道如何添加元數據在這一點上,因爲我找不到方法來訪問inst然而,在CGExp.cpp中,我看到了AllocaInstr的構建位置,但此時我無法訪問VarDecl,因此我不知道註釋是否存在。

我想反正在這個函數添加元數據(unconditionaly):

llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty, 
               const Twine &Name) { 
    llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name); 
    // FIXME: Should we prefer the preferred type alignment here? 
    CharUnits Align = getContext().getTypeAlignInChars(Ty); 

    // how to put it conditionaly on the annotation? 
    llvm::MDNode* node = getRangeForLoadFromType(Ty); 
    Alloc->setMetadata("_my_custom_metadata", node); 
    Alloc->setAlignment(Align.getQuantity()); 
    return Alloc; 
} 

通過添加setMetadata電話。

但是我沒有看到在生成的IR中附加的元數據。

clang -g -S -target i686-pc-win32 -emit-llvm main.cpp -o output.ll

也許編譯我完全錯了,但事情是,我不掌握代碼生成鐺:)

PS:這裏是我的代碼編譯

int main() { 
    __attribute__ ((annotate("_my_custom_annotation_"))) float a[12]; 
} 

任何幫助表示讚賞!

感謝

回答

2
if (D.hasAttr<AnnotateAttr>()) { 
     AnnotateAttr* attr = D.getAttr<AnnotateAttr>(); 
     if(attr->getAnnotation() == "_my_custom_annotation_") { 
      // set metadata... 
     } 
     EmitVarAnnotations(&D, emission.Address); 
    } 

看起來你是在正確的地方。事實上,所有的EmitAutoVarAlloca對不同類型的變量聲明都有特殊的處理,但是所有的末尾都帶有emission.Address中的「地址」(即指令)。

所以,你想要做的是:

if (D.hasAttr<AnnotateAttr>()) { 
     AnnotateAttr* attr = D.getAttr<AnnotateAttr>(); 
     if(attr->getAnnotation() == "_my_custom_annotation_") { 
      emission.Address->setMetadata(...); // <--- your MDNode goes here 
     } 
     EmitVarAnnotations(&D, emission.Address); 
    } 

不過,我會建議一個特殊的屬性添加元數據來說明。如果您通過代碼進一步閱讀,則會看到AnnotateAttr具有特殊含義,您的發射IR可能不如預期。您可以在Attr.td文件中添加自定義屬性。我建議註解條目的副本。然後,您可以通過代碼跟隨AnnotateAttr,並在正確的位置爲您的Attribute添加代碼,以便通過clang識別並處理它。

+0

感謝確認。它現在很好工作 – 2015-02-13 16:09:13

+0

@Michael Haidl,我嘗試了相同的代碼,它抱怨:clang :: CodeGen :: Address'沒有名爲'setMetadata'的成員。你知道如何解決這個問題嗎?提前致謝! – ignorer 2017-08-11 20:25:03

+0

@ignorer emission.Address已從'llvm :: Instruction *'更改爲'clang :: CodeGen :: Address'。 Address現在是一個'llvm :: Value *'的包裝器,您必須將它轉換爲一個指令(使用nullptr檢查做一個dyn_cast以確保您沒有指令)。在指令中,您可以像答案中那樣調用'setMetadata'。 – 2017-08-12 21:35:21