8607f71b9e45250819e432891208a4d359c2889c
[libfirm] / scripts / gen_ir.py
1 #!/usr/bin/env python
2 import sys
3 from jinja2 import Environment, Template
4 from jinja2.filters import do_dictsort
5 import ir_spec
6
7 def format_argdecls(node, first = False, voidwhenempty = False):
8         if not node.has_key("args") or len(node["args"]) == 0:
9                 if voidwhenempty:
10                         return "void"
11                 else:
12                         return ""
13
14         res = ""
15         if not first:
16                 comma = ", "
17         else:
18                 comma = ""
19         for arg in node["args"]:
20                 res = res + (comma + arg["type"] + " " + arg["name"])
21                 comma = ", "
22         return res
23
24 def format_args(node, first = False):
25         if not node.has_key("args"):
26                 return ""
27
28         res = ""
29         if not first:
30                 comma = ", "
31         else:
32                 comma = ""
33         for arg in node["args"]:
34                 res = res + (comma + arg["name"])
35                 comma = ", "
36         return res
37
38 def format_blockdecl(node):
39         if node.get("knownBlock"):
40                 return ""
41         else:
42                 return ", ir_node *block"
43
44 def format_block(node):
45         if node.get("knownBlock"):
46                 return ""
47         else:
48                 return ", block"
49
50 def format_curblock(node):
51         if node.get("knownBlock"):
52                 return ""
53         else:
54                 return ", current_ir_graph->current_block"
55
56 def format_insdecl(node):
57         arity = node["arity"]
58         if arity == "variable" and len(node["ins"]) == 0 or arity == "dynamic" or arity == 0:
59                 return ""
60
61         if arity == "variable":
62                 insarity = len(node["ins"])
63                 res = "int r_arity = arity + " + `insarity` + ";\n\tir_node **r_in;\n\t" \
64                         + "NEW_ARR_A(ir_node *, r_in, r_arity);\n\t"
65                 i = 0
66                 for input in node["ins"]:
67                         res += "r_in[" + `i` + "] = irn_" + input + ";\n\t"
68                         i += 1
69                 res += "memcpy(&r_in[" + `insarity` + "], in, sizeof(ir_node *) * arity);\n\t"
70         else:
71                 res = "ir_node *in[" + `arity` + "];\n\t"
72                 i = 0
73                 for input in node["ins"]:
74                         res += "in[" + `i` + "] = irn_" + input + ";\n\t"
75                         i += 1
76         return res
77
78 def format_arity_and_ins(node):
79         arity = node["arity"]
80         if arity == "dynamic":
81                 return "-1, NULL"
82         elif arity == "variable":
83                 if len(node["ins"]) == 0:
84                         return "arity, in"
85                 else:
86                         return "r_arity, r_in"
87         elif arity == 0:
88                 return "0, NULL"
89         else:
90                 return `arity` + ", in"
91
92 env = Environment()
93 env.filters['argdecls']  = format_argdecls
94 env.filters['args']      = format_args
95 env.filters['blockdecl'] = format_blockdecl
96 env.filters['block']     = format_block
97 env.filters['curblock']  = format_curblock
98 env.filters['insdecl']       = format_insdecl
99 env.filters['arity_and_ins'] = format_arity_and_ins
100
101 def add_attr(list, type, name, init = None, initname = None):
102         if initname == None:
103                 initname = "." + name
104         if init != None:
105                 list.append(dict(type = type, name = name, init = init, initname = initname))
106         else:
107                 list.append(dict(type = type, name = name, initname = initname))
108
109 def prepare_attr(attr):
110         if "init" in attr:
111                 return dict(type = attr["type"], name = attr["name"], init = attr["init"])
112         else:
113                 return dict(type = attr["type"], name = attr["name"])
114
115 def preprocess_node(nodename, node):
116         # set default attributes
117         if "is_a" in node:
118                 parent = ir_spec.nodes[node["is_a"]]
119                 node["ins"] = parent["ins"]
120                 if "outs" in parent:
121                         node["outs"] = parent["outs"]
122
123         if "outs" in node:
124                 node["mode"] = "mode_T"
125         if "nodbginfo" in node:
126                 node["db"] = "NULL"
127                 node["dbdecl"] = ""
128                 node["dbdeclnocomma"] = ""
129         else:
130                 node["db"] = "db"
131                 node["dbdecl"] = "dbg_info *db, "
132                 node["dbdeclnocomma"] = "dbg_info *db"
133
134         node.setdefault("ins", [])
135         node.setdefault("arity", len(node["ins"]))
136         node.setdefault("attrs", [])
137         node.setdefault("constrname", nodename);
138         node.setdefault("constructor_args", [])
139         node.setdefault("attrs_name", nodename.lower())
140         node.setdefault("block", "block")
141
142         # construct node arguments
143         arguments = [ ]
144         initattrs = [ ]
145         specialconstrs = [ ]
146         for input in node["ins"]:
147                 arguments.append(dict(type = "ir_node *", name = "irn_" + input))
148
149         # Special case for Builtin...
150         if nodename == "Builtin":
151                 for attr in node["attrs"]:
152                         if attr["name"] == "kind":
153                                 attr.setdefault("initname", "." + attr["name"])
154                                 arguments.append(prepare_attr(attr))
155
156         if node["arity"] == "variable":
157                 arguments.append(dict(type = "int", name = "arity"))
158                 arguments.append(dict(type = "ir_node **", name = "in"))
159
160         if "mode" not in node:
161                 arguments.append(dict(type = "ir_mode *", name = "mode"))
162                 node["mode"] = "mode"
163
164         attrs_with_special = 0
165         for attr in node["attrs"]:
166                 if nodename == "Builtin" and attr["name"] == "kind":
167                         continue
168
169                 attr.setdefault("initname", "." + attr["name"])
170
171                 if "special" in attr:
172                         if not "init" in attr:
173                                 print "Node type %s has an attribute with a \"special\" entry but without \"init\"" % nodename
174                                 sys.exit(1)
175
176                         if attrs_with_special != 0:
177                                 print "Node type %s has more than one attribute with a \"special\" entry" % nodename
178                                 sys.exit(1)
179
180                         attrs_with_special += 1
181
182                         if "prefix" in attr["special"]:
183                                 specialname = attr["special"]["prefix"] + nodename
184                         elif "suffix" in attr["special"]:
185                                 specialname = nodename + attr["special"]["suffix"]
186                         else:
187                                 print "Unknown special constructor type for node type %s" % nodename
188                                 sys.exit(1)
189
190                         specialconstrs.append(
191                                 dict(
192                                         constrname = specialname,
193                                         attr = attr
194                                 )
195                         )
196                 elif not "init" in attr:
197                         arguments.append(prepare_attr(attr))
198
199         for arg in node["constructor_args"]:
200                 arguments.append(prepare_attr(arg))
201                 if arg["type"] == "ir_cons_flags":
202                         name = arg["name"]
203                         initattrs.append(dict(initname = ".exc.pin_state",
204                                 init = name + " & cons_floats ? op_pin_state_floats : op_pin_state_pinned"))
205                         initattrs.append(dict(initname = ".volatility",
206                                 init = name + " & cons_volatile ? volatility_is_volatile : volatility_non_volatile"))
207                         initattrs.append(dict(initname = ".aligned",
208                                 init = name + " & cons_unaligned ? align_non_aligned : align_is_aligned"))
209
210         node["args"] = arguments
211         node["initattrs"] = initattrs
212         node["special_constructors"] = specialconstrs
213
214 #############################
215
216 node_template = env.from_string('''
217 ir_node *new_rd_{{node["constrname"]}}({{node["dbdecl"]}}ir_graph *irg{{node|blockdecl}}{{node|argdecls}})
218 {
219         ir_node *res;
220         ir_graph *rem = current_ir_graph;
221         {{node|insdecl}}
222         current_ir_graph = irg;
223         res = new_ir_node({{node["db"]}}, irg, {{node["block"]}}, op_{{nodename}}, {{node["mode"]}}, {{node|arity_and_ins}});
224         {% for attr in node["attrs"] -%}
225                 res->attr.{{node["attrs_name"]}}{{attr["initname"]}} =
226                 {%- if "init" in attr %} {{ attr["init"] -}};
227                 {%- else              %} {{ attr["name"] -}};
228                 {% endif %}
229         {% endfor %}
230         {%- for attr in node["initattrs"] -%}
231                 res->attr.{{node["attrs_name"]}}{{attr["initname"]}} = {{ attr["init"] -}};
232         {% endfor %}
233         {{- node["init"] }}
234         {% if node["optimize"] != False -%}
235                 res = optimize_node(res);
236         {% endif -%}
237         IRN_VRFY_IRG(res, irg);
238         current_ir_graph = rem;
239         return res;
240 }
241
242 ir_node *new_r_{{node["constrname"]}}(ir_graph *irg{{node|blockdecl}}{{node|argdecls}})
243 {
244         {% if node["nodbginfo"] -%}
245                 return new_rd_{{node["constrname"]}}(irg{{node|block}}{{node|args}});
246         {%- else -%}
247                 return new_rd_{{node["constrname"]}}(NULL, irg{{node|block}}{{node|args}});
248         {%- endif %}
249 }
250
251 ir_node *new_d_{{node["constrname"]}}({{node["dbdeclnocomma"]}}{{node|argdecls(node["nodbginfo"])}})
252 {
253         ir_node *res;
254         {{ node["d_pre"] }}
255         {% if node["nodbginfo"] -%}
256                 res = new_rd_{{node["constrname"]}}(current_ir_graph{{node|curblock}}{{node|args}});
257         {%- else -%}
258                 res = new_rd_{{node["constrname"]}}(db, current_ir_graph{{node|curblock}}{{node|args}});
259         {%- endif %}
260         {{ node["d_post"] }}
261         return res;
262 }
263
264 ir_node *new_{{node["constrname"]}}({{node|argdecls(True, True)}})
265 {
266         {% if node["nodbginfo"] -%}
267                 return new_d_{{node["constrname"]}}({{node|args(True)}});
268         {%- else -%}
269                 return new_d_{{node["constrname"]}}(NULL{{node|args}});
270         {%- endif %}
271 }
272
273 ''')
274
275 #############################
276
277 def main(argv):
278         """the main function"""
279
280         if len(argv) < 3:
281                 print "usage: %s specname(ignored) destdirectory" % argv[0]
282                 sys.exit(1)
283
284         gendir = argv[2]
285
286         # List of TODOs
287         niymap = ["Anchor", "ASM", "Bad", "Bound", "Break",
288                 "CallBegin", "Const", "Const_type", "Const_long", "CopyB",
289                 "defaultProj", "Dummy", "EndReg", "EndExcept",
290                 "Filter", "InstOf", "NoMem", "Phi", "Raise",
291                 "simpleSel", "SymConst", "SymConst_type", "Sync"]
292
293         file = open(gendir + "/gen_ir_cons.c.inl", "w")
294         for nodename, node in do_dictsort(ir_spec.nodes):
295                 if nodename in niymap:
296                         continue
297                 preprocess_node(nodename, node)
298                 if not "abstract" in node:
299                         file.write(node_template.render(vars()))
300
301                         if "special_constructors" in node:
302                                 for special in node["special_constructors"]:
303                                         node["constrname"] = special["constrname"]
304                                         special["attr"]["init"] = special["attr"]["special"]["init"]
305                                         file.write(node_template.render(vars()))
306         file.write("\n")
307         file.close()
308
309 if __name__ == "__main__":
310         main(sys.argv)