Modifying struct layout

I'm interested in programmatically modifying the layout of arbitrary
(non-packed) structs in C programs using a source-to-source
transformation. In particular, I would like to: (1) reorder the
members of a struct basing on a predetermined criteria; (2) add
predefined padding (or dummy members of a predefined size) at the
beginning of the struct and between consecutive struct members.

LLVM types are immutable and I don't think the transformation can be
implemented as an LLVM pass. I'm considering using clang (ideally a
clang plugin) for the job, but I'm not sure this is possible/easy to
Is there any way to achieve (1) and/or (2) with clang? For example,
changing an existing type declaration
(clang::TypeDecl::setTypeForDecl()) with a newly-created type or
modifying ASTRecordLayout directly?



If you want to do source-to-source translation, I don't understand why
you care about modifying the ASTs at all. Just find the struct
declarations you care about, create a similar struct with the layout
you want, print that out, and have Clang's rewriter replace the original
source range with the new text.


Yes, you want a clang plugin. If you're doing a source-to-source
transformation, you don't need to mutate the AST; just analyze the
declared fields, then use the Rewriter to rearrange/insert fields as


Right. I'm actually considering all the options, since I would like to
use this strategy in different scenarios.
Say we rule out the possibility of a source-to-source translation and
we want to directly modify the ASTs on-the-fly to get the job done.
Would that be possible?