[cfe-dev] Custom pragmas handling

Douglas Gregor dgregor at apple.com
Fri Oct 30 13:53:42 PDT 2009


On Oct 30, 2009, at 4:03 AM, Sylvain HENRY wrote:

> Hi,
>
> I would like to have a C compiler which can handle some custom
> pragmas. For instance consider the following C file:
>
> #pragma starpu interface
> void foo();
>
> #pragma starpu implements(foo)
> void foo_v1() {...}
>
> #pragma starpu implements(foo)
> void foo_v2() {...}
>
> I would like the compiler to transform it into:
>
> void foo() {
>   //do something with foo_v1() and/or foo_v2()
> }
> void foo_v1() {...}
> void foo_v2() {...}
>
> And finally compile it.
>
> I have copied clang-cc and modified it to detect "starpu" pragmas by
> adding a PragmaHandler to the preprocessor. However I have a few
> questions:
> 1) Is there a non intrusive way (ie without modifying clang-cc or
> clang) to add this kind a custom pragma handling in Clang? That would
> be helpful to implement OpenMP too. Maybe a plan for some sort of
> plugin system?

We don't have a non-intrusive way to add such pragmas, but I think  
that some kind of plugin system that allows one to add pragmas and  
then query them (say, as part of the ASTConsumer interface) would be  
very useful.

> 2) How can I determine in the PragmaHandler which function the pragma
> applies to? Then, how can I modify the function's body to add some
> statements? I think I could create a custom Action class, which would
> perform AST modification in the appropriate ActOn* callbacks, and
> replace the ParseAST call in clang-cc by a call to an other Parser
> using my Action, but then how do I compile/ast-dump/...  the modified
> AST?


I think this would best be accomplished by extending the ASTConsumer  
interface. Sema could be taught to associate pragmas with  
declarations, notifying the AST consumer when an otherwise-unknown  
pragma is associated with a declaration that it has type-checked.

As for producing a modified AST, that's a little harder. The AST  
printing routines aren't good enough for source-to-source  
transformation, and I wouldn't recommend that route anyway: you'll  
lose all of the formatting. Instead, check out the Rewriter, which  
allows textual rewriting of a source file based on source location  
information.

	- Doug



More information about the cfe-dev mailing list