templates vs code to generate IR

Gordon reminded me that most people seem to generate code using code, whereas it has become natural for me to use templates to generate code. Let me include an example from an article I'm working on (Java centric). The same argument goes for LLVM IR templates versus using the C++ interface. Generating LLVM IR for me is super simple. Here are a few of my templates for generating IR from simple expressions with arrays (only i32 in this example):

load(id,reg) ::= "<reg> = load i32* %<id>"

/** reg = *(id+a) and addr is a temporary register name. a is the template with code to compute the index */
index(reg,addr,size,id,a) ::= <<
<a>
<addr> = getelementptr [<size> x i32]* %<id>, i32 0, i32 <a.reg>;
<reg> = load i32* <addr>
>>

intval(reg,v) ::= "<reg> = add i32 <v>,0"

Creating instances of those templates and setting the attribute that fill in the holes is very simple from an ANTLR grammar. :slight_smile:

Just a few thoughts in case people are wondering about the various approaches.

regards,
Ter

Hi Terence,

The reason I remarked, actually, is that for LLVM in particular the C++ API offers more safety, and emitting .ll generally requires at least partially reimplementing the IR object model. I think this is a topic in the FAQ. But both are perfectly valid approaches!

- Gordon

:slight_smile: Yep,The advantage of the code-based mechanism is that the compiler, because of that static typing, can do all sorts of well formedness checking for you. A major advantage of that approach and a weakness of the template-based approach.

My main goal is programmer productivity. An extreme example illustrates my point: imagine a bunch of support functions you need to generate in the output code (that cannot be linked in from C, for example). What would you rather type in: IR in text or the massive amount of code to build up the object model? Surely, in your head you are imagining the target IR language (we evolved over millions of years to be good at extracting and generating structure from linear sequences of symbols). :slight_smile:

Ter