[cfe-dev] Recombining AST Nodes

David Rector via cfe-dev cfe-dev at lists.llvm.org
Fri Feb 5 07:57:32 PST 2021


Hi John,

IIUC you are creating a new RecordDecl, manually replacing the old one with the new one in its DeclContext, and then printing it.  As you seem to recognize this is the problematic line (recall this is from that DeclPrinter code I referenced the last time):

https://github.com/llvm-mirror/clang/blob/master/lib/AST/DeclPrinter.cpp#L410 <https://github.com/llvm-mirror/clang/blob/master/lib/AST/DeclPrinter.cpp#L394>

You need the FieldDecl (which should be the very next Decl* in the DeclContext after the old RecordDecl *) to have an elaborated type whose owned tag decl is the new RecordDecl you have created (which will be `Decls[0]` in that code); if it is thus, and if the RecordDecl you created is marked as !isFreeStanding(), it should print as you expect, I think.

To create that type, use the ASTContext::getElaboratedType(…) method, which accepts the OwnedTagDecl as an arg.  (ASTContext manages the types to ensure there are not multiple copies of the same Type* floating around, IIUC.)

Then, I would probably also replace the existing FieldDecl with a newly Created one, in the same manner you replaced the RecordDecl *, only now Create it with the new type.

Hope that works — good luck,

Dave

> On Feb 4, 2021, at 9:59 AM, John Leidel via cfe-dev <cfe-dev at lists.llvm.org> wrote:
> 
> I'm in the process of debugging (again) issues with anonymous struct
> decls.  I have the following basic structures located in a C source
> file that I'm attempting to transform.  I want to preserve the layout
> of the structs.
> 
> struct{
>  int A;
> }S;
> 
> struct{
>  int B;
>  struct{
>    int C;
>  }T;
> }R;
> 
> When I use my AST visitors, I can pick up the RecordDecl for the
> struct definitions and the VarDecl for the variable definitions, but
> the transformed code is outputted as:
> struct{
>  int A;
> };
> struct (anonymous) S;
> 
> I can view the RecordDecl as as TagDecl and save off a reference to it
> if it is !isFreeStanding(), but how does one go about recombining the
> declaration of "S" and the original TagDecl?
> 
> For the VarDecl ("S" in this case), I can determine whether or not its
> an "ElaboratedType", but I'm not sure how to utilize the saved
> reference to the RecordDecl:
> 
> if(isa<ElaboratedType>(SemaRef.Context.getBaseElementType(MyVarDecl))) {
>   /// how do i recombine the VarDecl and the RecordDecl/TagDecl?
> }
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20210205/7d7eae9b/attachment.html>


More information about the cfe-dev mailing list