Marc-O
Marc-O

Reputation: 711

Get the size of a variable in Clang

With the Clang library, is there some available method to get the size of a variable (as if I used sizeof() in a regular C/C++ program ?

I am able (and this is what I want to do) to spot VarDecl, but at the moment I still can't find any method in the Clang namespace to get the size of my var spotted with the current VarDecl

Upvotes: 4

Views: 2985

Answers (1)

Robin Joy
Robin Joy

Reputation: 401

Size information for a type is stored in a TypeInfo associated with a given type. You can get a corresponding FieldInfo pair from the ASTContext via the getTypeInfo function. The first element of the pair is the size of the type in bits. The second element is the alignment of the type in bits.

bool VisitVarDecl(VarDecl *VD) {
    std::pair<uint64_t, unsigned> FieldInfo = VD->getASTContext().getTypeInfo(VD->getType());
    uint64_t TypeSize = FieldInfo.first;
    unsigned FieldAlign = FieldInfo.second;
    llvm::outs() << VD->getNameAsString() << " Size: " << TypeSize/8 << " Alignment: " << FieldAlign/8 << '\n';
}

Upvotes: 7

Related Questions