3c5409b4db960d5bb0a147a4647c1dd3c8abfa02
[libfirm] / scripts / gen_ir.py
1 #!/usr/bin/env python
2 import sys
3 import re
4 from jinja2 import Environment, Template
5 from jinja2.filters import do_dictsort
6 from spec_util import is_dynamic_pinned, verify_node
7 from ir_spec import nodes
8
9 def format_argdecls(node, first = False, voidwhenempty = False):
10         if not node.has_key("args") or len(node["args"]) == 0:
11                 if voidwhenempty:
12                         return "void"
13                 else:
14                         return ""
15
16         res = ""
17         if not first:
18                 comma = ", "
19         else:
20                 comma = ""
21         for arg in node["args"]:
22                 res = res + (comma + arg["type"] + " " + arg["name"])
23                 comma = ", "
24         return res
25
26 def format_args(node, first = False):
27         if not node.has_key("args"):
28                 return ""
29
30         res = ""
31         if not first:
32                 comma = ", "
33         else:
34                 comma = ""
35         for arg in node["args"]:
36                 res = res + (comma + arg["name"])
37                 comma = ", "
38         return res
39
40 def format_blockdecl(node):
41         if node.get("knownBlock"):
42                 return ""
43         else:
44                 return ", ir_node *block"
45
46 def format_block(node):
47         if node.get("knownBlock"):
48                 return ""
49         else:
50                 return ", block"
51
52 def format_curblock(node):
53         if node.get("knownBlock"):
54                 return ""
55         else:
56                 return ", current_ir_graph->current_block"
57
58 def format_insdecl(node):
59         arity = node["arity"]
60         if arity == "variable" and len(node["ins"]) == 0 or arity == "dynamic" or arity == 0:
61                 return ""
62
63         if arity == "variable":
64                 insarity = len(node["ins"])
65                 res = "int r_arity = arity + " + `insarity` + ";\n\tir_node **r_in;\n\t" \
66                         + "NEW_ARR_A(ir_node *, r_in, r_arity);\n\t"
67                 i = 0
68                 for input in node["ins"]:
69                         res += "r_in[" + `i` + "] = irn_" + input + ";\n\t"
70                         i += 1
71                 res += "memcpy(&r_in[" + `insarity` + "], in, sizeof(ir_node *) * arity);\n\t"
72         else:
73                 res = "ir_node *in[" + `arity` + "];\n\t"
74                 i = 0
75                 for input in node["ins"]:
76                         res += "in[" + `i` + "] = irn_" + input + ";\n\t"
77                         i += 1
78         return res
79
80 def format_arity_and_ins(node):
81         arity = node["arity"]
82         if arity == "dynamic":
83                 return "-1, NULL"
84         elif arity == "variable":
85                 if len(node["ins"]) == 0:
86                         return "arity, in"
87                 else:
88                         return "r_arity, r_in"
89         elif arity == 0:
90                 return "0, NULL"
91         else:
92                 return `arity` + ", in"
93
94 def format_arity(node):
95         arity = node['arity']
96         if arity == "dynamic":
97                 return "oparity_dynamic"
98         if arity == "variable":
99                 return "oparity_variable"
100         if arity == 0:
101                 return "oparity_zero"
102         if arity == 1:
103                 return "oparity_unary"
104         if arity == 2:
105                 return "oparity_binary"
106         if arity == 3:
107                 return "oparity_trinary"
108         return "oparity_any"
109
110 def format_pinned(node):
111         pinned = node["pinned"]
112         if pinned == "yes":
113                 return "op_pin_state_pinned"
114         if pinned == "no":
115                 return "op_pin_state_floats"
116         if pinned == "exception":
117                 return "op_pin_state_exc_pinned"
118         if pinned == "memory":
119                 return "op_pin_state_mem_pinned"
120         print "WARNING: Unknown pinned state %s in format pined" % pinned
121         return ""
122
123 def format_flags(node):
124         flags = node['flags']
125         flags = re.split("\s*,\s*", flags)
126         flags = map(lambda x : "irop_flag_" + x, flags)
127         return " | ".join(flags)
128
129 def format_attr_size(node):
130         if "attr_struct" not in node:
131                 return "0"
132         return "sizeof(%s)" % node['attr_struct']
133
134 def filter_isnot(list, flag):
135         result = []
136         for nodename, node in list:
137                 if flag in node:
138                         continue
139                 result.append((nodename, node))
140         return result
141
142 env = Environment()
143 env.filters['argdecls']  = format_argdecls
144 env.filters['args']      = format_args
145 env.filters['blockdecl'] = format_blockdecl
146 env.filters['block']     = format_block
147 env.filters['curblock']  = format_curblock
148 env.filters['insdecl']       = format_insdecl
149 env.filters['arity_and_ins'] = format_arity_and_ins
150 env.filters['arity']         = format_arity
151 env.filters['pinned']        = format_pinned
152 env.filters['flags']         = format_flags
153 env.filters['attr_size']     = format_attr_size
154 env.filters['isnot']         = filter_isnot
155
156 def add_attr(list, type, name, init = None, initname = None):
157         if initname == None:
158                 initname = "." + name
159         if init != None:
160                 list.append(dict(type = type, name = name, init = init, initname = initname))
161         else:
162                 list.append(dict(type = type, name = name, initname = initname))
163
164 def prepare_attr(attr):
165         if "init" in attr:
166                 return dict(type = attr["type"], name = attr["name"], init = attr["init"])
167         else:
168                 return dict(type = attr["type"], name = attr["name"])
169
170 def preprocess_node(nodename, node):
171         # set default attributes
172         if "is_a" in node:
173                 parent = nodes[node["is_a"]]
174                 node["ins"] = parent["ins"]
175                 if "outs" in parent:
176                         node["outs"] = parent["outs"]
177
178         if "outs" in node:
179                 node["mode"] = "mode_T"
180         node["db"] = "db"
181         node["dbdecl"] = "dbg_info *db, "
182         node["dbdeclnocomma"] = "dbg_info *db"
183
184         if "flags" not in node and "abstract" not in node:
185                 print "WARNING: no flags specified for %s (you should say at least 'none')\n" % nodename
186
187         node.setdefault("ins", [])
188         node.setdefault("arity", len(node["ins"]))
189         node.setdefault("attrs", [])
190         node.setdefault("constrname", nodename);
191         node.setdefault("constructor_args", [])
192         node.setdefault("attrs_name", nodename.lower())
193         node.setdefault("block", "block")
194         node.setdefault("pinned", "no")
195         node.setdefault("flags", "none")
196
197         verify_node(node)
198
199
200         # construct node arguments
201         arguments = [ ]
202         initattrs = [ ]
203         specialconstrs = [ ]
204         for input in node["ins"]:
205                 arguments.append(dict(type = "ir_node *", name = "irn_" + input))
206
207         if node["arity"] == "variable" or node["arity"] == "dynamic":
208                 arguments.append(dict(type = "int", name = "arity"))
209                 arguments.append(dict(type = "ir_node **", name = "in"))
210
211         if "mode" not in node:
212                 arguments.append(dict(type = "ir_mode *", name = "mode"))
213                 node["mode"] = "mode"
214
215         attrs_with_special = 0
216         for attr in node["attrs"]:
217                 attr.setdefault("initname", "." + attr["name"])
218
219                 if "special" in attr:
220                         if not "init" in attr:
221                                 print "Node type %s has an attribute with a \"special\" entry but without \"init\"" % nodename
222                                 sys.exit(1)
223
224                         if attrs_with_special != 0:
225                                 print "Node type %s has more than one attribute with a \"special\" entry" % nodename
226                                 sys.exit(1)
227
228                         attrs_with_special += 1
229
230                         if "prefix" in attr["special"]:
231                                 specialname = attr["special"]["prefix"] + nodename
232                         elif "suffix" in attr["special"]:
233                                 specialname = nodename + attr["special"]["suffix"]
234                         else:
235                                 print "Unknown special constructor type for node type %s" % nodename
236                                 sys.exit(1)
237
238                         specialconstrs.append(
239                                 dict(
240                                         constrname = specialname,
241                                         attr = attr
242                                 )
243                         )
244                 elif not "init" in attr:
245                         arguments.append(prepare_attr(attr))
246
247         # dynamic pin state means more constructor arguments
248         if is_dynamic_pinned(node):
249                 if "pinned_init" in node:
250                         initattrs.append(dict(
251                                 initname = ".exc.pin_state",
252                                 init     = "op_pin_state_" + node["pinned_init"]
253                         ))
254                 else:
255                         node["constructor_args"].append(
256                                 dict(
257                                         name = "pin_state",
258                                         type = "op_pin_state"
259                                 )
260                         )
261                         initattrs.append(dict(
262                                 initname = ".exc.pin_state",
263                                 init     = "pin_state"
264                         ))
265
266         for arg in node["constructor_args"]:
267                 arguments.append(prepare_attr(arg))
268                 if arg["type"] == "ir_cons_flags":
269                         name = arg["name"]
270                         initattrs.append(dict(initname = ".exc.pin_state",
271                                 init = name + " & cons_floats ? op_pin_state_floats : op_pin_state_pinned"))
272                         initattrs.append(dict(initname = ".volatility",
273                                 init = name + " & cons_volatile ? volatility_is_volatile : volatility_non_volatile"))
274                         initattrs.append(dict(initname = ".aligned",
275                                 init = name + " & cons_unaligned ? align_non_aligned : align_is_aligned"))
276
277         node["args"] = arguments
278         node["initattrs"] = initattrs
279         node["special_constructors"] = specialconstrs
280
281 #############################
282
283 constructor_template = env.from_string('''
284
285 ir_node *new_rd_{{node["constrname"]}}({{node["dbdecl"]}}ir_graph *irg{{node|blockdecl}}{{node|argdecls}})
286 {
287         ir_node *res;
288         ir_graph *rem = current_ir_graph;
289         {{node|insdecl}}
290         current_ir_graph = irg;
291         res = new_ir_node({{node["db"]}}, irg, {{node["block"]}}, op_{{nodename}}, {{node["mode"]}}, {{node|arity_and_ins}});
292         {% for attr in node["attrs"] -%}
293                 res->attr.{{node["attrs_name"]}}{{attr["initname"]}} =
294                 {%- if "init" in attr %} {{ attr["init"] -}};
295                 {%- else              %} {{ attr["name"] -}};
296                 {% endif %}
297         {% endfor %}
298         {%- for attr in node["initattrs"] -%}
299                 res->attr.{{node["attrs_name"]}}{{attr["initname"]}} = {{ attr["init"] -}};
300         {%- endfor %}
301         {{- node["init"] }}
302         {% if node["optimize"] != False -%}
303                 res = optimize_node(res);
304         {% endif -%}
305         IRN_VRFY_IRG(res, irg);
306         current_ir_graph = rem;
307         return res;
308 }
309
310 ir_node *new_r_{{node["constrname"]}}(ir_graph *irg{{node|blockdecl}}{{node|argdecls}})
311 {
312         {% if node["nodbginfo"] -%}
313                 return new_rd_{{node["constrname"]}}(irg{{node|block}}{{node|args}});
314         {%- else -%}
315                 return new_rd_{{node["constrname"]}}(NULL, irg{{node|block}}{{node|args}});
316         {%- endif %}
317 }
318
319 ir_node *new_d_{{node["constrname"]}}({{node["dbdeclnocomma"]}}{{node|argdecls(node["nodbginfo"])}})
320 {
321         ir_node *res;
322         {{ node["d_pre"] }}
323         {% if node["nodbginfo"] -%}
324                 res = new_rd_{{node["constrname"]}}(current_ir_graph{{node|curblock}}{{node|args}});
325         {%- else -%}
326                 res = new_rd_{{node["constrname"]}}(db, current_ir_graph{{node|curblock}}{{node|args}});
327         {%- endif %}
328         {{ node["d_post"] }}
329         return res;
330 }
331
332 ir_node *new_{{node["constrname"]}}({{node|argdecls(True, True)}})
333 {
334         {% if node["nodbginfo"] -%}
335                 return new_d_{{node["constrname"]}}({{node|args(True)}});
336         {%- else -%}
337                 return new_d_{{node["constrname"]}}(NULL{{node|args}});
338         {%- endif %}
339 }
340 ''')
341
342 irnode_h_template = env.from_string('''
343 /* Warning: automatically generated code */
344
345 {% for nodename, node in nodes|isnot('custom_is') %}
346 static inline int _is_{{nodename}}(const ir_node *node)
347 {
348         assert(node != NULL);
349         return _get_irn_op(node) == op_{{nodename}};
350 }
351 {% endfor %}
352
353 {% for nodename, node in nodes %}
354 #define is_{{nodename}}(node)    _is_{{nodename}}(node)
355 {%- endfor %}
356 ''')
357
358 irnode_template = env.from_string('''
359 /* Warning: automatically generated code */
360 {% for nodename, node in nodes %}
361 int (is_{{nodename}})(const ir_node *node)
362 {
363         return _is_{{nodename}}(node);
364 }
365 {% endfor %}
366 ''')
367
368 irop_template = env.from_string('''
369 /* Warning: automatically generated code */
370 {% for nodename, node in nodes %}
371 ir_op *op_{{nodename}}; ir_op *get_op_{{nodename}}(void) { return op_{{nodename}}; }
372 {%- endfor %}
373
374 void init_op(void)
375 {
376         {% for nodename, node in nodes %}
377         op_{{nodename}} = new_ir_op(iro_{{nodename}}, "{{nodename}}", {{node|pinned}}, {{node|flags}}, {{node|arity}}, -1, {{node|attr_size}}, NULL);
378         {%- endfor %}
379
380         be_init_op();
381 }
382
383 void finish_op(void)
384 {
385         {% for nodename, node in nodes %}
386         free_ir_op(op_{{nodename}}); op_{{nodename}} = NULL;
387         {%- endfor %}
388 }
389 ''')
390
391 #############################
392
393 def main(argv):
394         """the main function"""
395
396         if len(argv) < 3:
397                 print "usage: %s specname(ignored) destdirectory" % argv[0]
398                 sys.exit(1)
399
400         gendir = argv[2]
401
402         # List of TODOs
403         niymap = ["ASM", "CallBegin", "Const", "Const_type", "Const_long",
404                 "defaultProj", "Dummy", "Phi", "simpleSel", "SymConst", "SymConst_type",
405                 "Sync"]
406
407         file = open(gendir + "/gen_ir_cons.c.inl", "w")
408         for nodename, node in do_dictsort(nodes):
409                 preprocess_node(nodename, node)
410                 if nodename in niymap:
411                         continue
412                 if "abstract" not in node and "singleton" not in node:
413                         file.write(constructor_template.render(vars()))
414
415                         if "special_constructors" in node:
416                                 for special in node["special_constructors"]:
417                                         node["constrname"] = special["constrname"]
418                                         special["attr"]["init"] = special["attr"]["special"]["init"]
419                                         file.write(constructor_template.render(vars()))
420         file.write("\n")
421         file.close()
422
423         real_nodes = dict()
424         for nodename, node in nodes.iteritems():
425                 if "abstract" in node:
426                         continue
427                 real_nodes[nodename] = node
428         real_nodes = do_dictsort(real_nodes)
429
430         file = open(gendir + "/gen_irnode.h", "w")
431         file.write(irnode_h_template.render(nodes = real_nodes))
432         file.close()
433
434         file = open(gendir + "/gen_irnode.c.inl", "w")
435         file.write(irnode_template.render(nodes = real_nodes))
436         file.close()
437
438         file = open(gendir + "/gen_irop.c.inl", "w")
439         file.write(irop_template.render(nodes = real_nodes))
440         file.close()
441
442 if __name__ == "__main__":
443         main(sys.argv)