Modifying Structs


I am writing an AST consumer to modify fields of the structs in a C program and let clang to generate code accordingly. I was modifying structs in HandleTagDeclDefinition(TagDecl *D) but I realized that if a struct defined using typedef like below, HandleTagDeclDefinition is not called after it’s definition is completed. Is there any way to solve this problem? Thank you.

typedef struct
int a;
} Integer;


Actually, HandleTagDeclDefinition is called for Integer struct but I couldn’t get the name of the struct which is “Integer” from TagDecl. Is there any way to do this in HandleTagDeclDefinition function.

Hello Mats,

I have a list of struct names and I need to change the order of fields of
these structs. I think I can only do this in HandleTagDeclDefinition
because once a struct definition is completed, it is called and the changes
I do here will be applied to rest of the codegen.

Those structs have no name. There is a typedef-name, but the struct has no

Maybe the trick is to not use a list of struct names, but identify the
relevant structures in some other way?

I can access the name of the struct which is defined using typedef keyword
in HandleTranslationUnit (ASTContext &Ctx) but it is going to be too late
to make changes here. Please let me know if I think wrong.

It _may_ be too late. That depends on what you are actually trying to
achieve and how. If you are re-ordering fields, then yes, it'll involve
looking up all references to that field and changing it to the new index.
Compilers do more difficult things throughout compilation.

Maybe there is a way to get the struct name in HandleTagDeclDefinition
even if it is defined with typedef but I couldn't find it.

There is obviously a typedef name in the compiler, but it's not part of the
ASTConsumer interface to "give" that name (as far as I can see). I don't
know the answer to how you solve this.

So there is no way to look up typedef-name in HandleTagDeclDefinition. In this case maybe I can use the the name and type of fields of structs to identify the relevant structs but I am not sure about this.

Yes, that would certainly be one possible scenario.

Obviously, assuming those are reasonably unique and can be used to identify
structs of interest.

Thank you Mats!