Merge remote-tracking branch 'github-privat/master'
[nit.git] / src / separate_erasure_compiler.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Separate compilation of a Nit program with generic type erasure
16 module separate_erasure_compiler
17
18
19 import separate_compiler
20
21 redef class ToolContext
22 # --erasure
23 var opt_erasure: OptionBool = new OptionBool("Erase generic types", "--erasure")
24
25 redef init
26 do
27 super
28 self.option_context.add_option(self.opt_erasure)
29 end
30 end
31
32 redef class ModelBuilder
33 fun run_separate_erasure_compiler(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis)
34 do
35 var time0 = get_time
36 self.toolcontext.info("*** COMPILING TO C ***", 1)
37
38 var compiler = new SeparateErasureCompiler(mainmodule, runtime_type_analysis, self)
39
40 # compile class structures
41 for m in mainmodule.in_importation.greaters do
42 for mclass in m.intro_mclasses do
43 compiler.compile_class_to_c(mclass)
44 end
45 end
46
47 # The main function of the C
48 compiler.compile_main_function
49
50 # compile methods
51 for m in mainmodule.in_importation.greaters do
52 compiler.compile_module_to_c(m)
53 end
54
55 write_and_make(compiler)
56 end
57 end
58
59 class SeparateErasureCompiler
60 super SeparateCompiler
61
62 private var class_ids: HashMap[MClass, Int] = new HashMap[MClass, Int]
63 private var class_colors: Map[MClass, Int]
64 private var class_tables: Map[MClass, Array[nullable MClass]]
65
66 init(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis, mmbuilder: ModelBuilder) do
67 var mclasses = new HashSet[MClass]
68 mclasses.add_all(mmbuilder.model.mclasses)
69
70 # classes coloration
71 if modelbuilder.toolcontext.opt_phmod_typing.value then
72 # set type unique id
73 for mclass in mclasses do
74 self.class_ids[mclass] = self.class_ids.length + 1
75 end
76
77 var class_coloring = new ClassModPerfectHashing(mainmodule)
78 self.class_colors = class_coloring.compute_masks(mclasses, class_ids)
79 self.class_tables = class_coloring.hash_type_tables(mclasses, class_ids, class_colors)
80
81 self.header.add_decl("int HASH(int, int);")
82 var v = new_visitor
83 v.add_decl("int HASH(int mask, int id) \{")
84 v.add_decl("return mask % id;")
85 v.add_decl("\}")
86 else if modelbuilder.toolcontext.opt_phand_typing.value then
87 # set type unique id
88 for mclass in mclasses do
89 self.class_ids[mclass] = self.class_ids.length + 1
90 end
91
92 var class_coloring = new ClassAndPerfectHashing(mainmodule)
93 self.class_colors = class_coloring.compute_masks(mclasses, class_ids)
94 self.class_tables = class_coloring.hash_type_tables(mclasses, class_ids, class_colors)
95
96 self.header.add_decl("int HASH(int, int);")
97 var v = new_visitor
98 v.add_decl("int HASH(int mask, int id) \{")
99 v.add_decl("return mask & id;")
100 v.add_decl("\}")
101 else
102 var class_coloring
103 if modelbuilder.toolcontext.opt_bm_typing.value then
104 class_coloring = new NaiveClassColoring(mainmodule)
105 else
106 class_coloring = new ClassColoring(mainmodule)
107 end
108 # set type unique id
109 for mclass in mclasses do
110 self.class_ids[mclass] = self.class_ids.length + 1
111 end
112 self.class_colors = class_coloring.colorize(modelbuilder.model.mclasses)
113 self.class_tables = class_coloring.build_type_tables(modelbuilder.model.mclasses, class_colors)
114 end
115
116 # for the class_name and output_class_name methods
117 self.compile_class_names
118 end
119
120 redef fun compile_header_structs do
121 self.header.add_decl("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
122 self.header.add_decl("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
123 self.header.add_decl("struct class \{ int id; int box_kind; int color; struct vts_table *vts_table; struct type_table *type_table; nitmethod_t vft[1]; \}; /* general C type representing a Nit class. */")
124 self.header.add_decl("struct type_table \{ int size; int table[1]; \}; /* colorized type table. */")
125 self.header.add_decl("struct vts_entry \{ short int is_nullable; struct class *class; \}; /* link (nullable or not) between the vts and is bound. */")
126
127 if modelbuilder.toolcontext.opt_phmod_typing.value or modelbuilder.toolcontext.opt_phand_typing.value then
128 self.header.add_decl("struct vts_table \{ int mask; struct vts_entry vts[1]; \}; /* vts list of a C type representation. */")
129 else
130 self.header.add_decl("struct vts_table \{ struct vts_entry vts[1]; \}; /* vts list of a C type representation. */")
131 end
132
133 self.header.add_decl("typedef struct \{ struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
134 self.header.add_decl("extern const char const * class_names[];")
135 end
136
137 redef fun compile_class_names do
138 # Build type names table
139 var type_array = new Array[nullable MClass]
140 for t, id in class_ids do
141 if id >= type_array.length then
142 for i in [type_array.length..id[ do
143 type_array[i] = null
144 end
145 end
146 type_array[id] = t
147 end
148
149 var v = self.new_visitor
150 v.add("const char const * class_names[] = \{")
151 for t in type_array do
152 if t == null then
153 v.add("NULL, /* empty */")
154 else
155 v.add("\"{t}\",")
156 end
157 end
158 v.add("\};")
159 end
160
161 redef fun compile_class_to_c(mclass: MClass)
162 do
163 var mtype = mclass.intro.bound_mtype
164 var c_name = mclass.c_name
165
166 var vft = self.method_tables[mclass]
167 var attrs = self.attr_tables[mclass]
168 var class_table = self.class_tables[mclass]
169 var v = self.new_visitor
170
171 v.add_decl("/* runtime class {c_name} */")
172 var idnum = classids.length
173 var idname = "ID_" + c_name
174 self.classids[mtype] = idname
175 #self.header.add_decl("#define {idname} {idnum} /* {c_name} */")
176
177 self.header.add_decl("extern const struct class_{c_name} class_{c_name};")
178 self.header.add_decl("struct class_{c_name} \{")
179 self.header.add_decl("int id;")
180 self.header.add_decl("int box_kind;")
181 self.header.add_decl("int color;")
182 self.header.add_decl("const struct vts_table *vts_table;")
183 self.header.add_decl("struct type_table *type_table;")
184 self.header.add_decl("nitmethod_t vft[{vft.length}];")
185 self.header.add_decl("\};")
186
187 # Build class vft
188 v.add_decl("const struct class_{c_name} class_{c_name} = \{")
189 v.add_decl("{self.class_ids[mclass]},")
190 v.add_decl("{self.box_kind_of(mclass)}, /* box_kind */")
191 v.add_decl("{self.class_colors[mclass]},")
192 v.add_decl("(const struct vts_table*) &vts_table_{c_name},")
193 v.add_decl("(struct type_table*) &type_table_{c_name},")
194 v.add_decl("\{")
195 for i in [0 .. vft.length[ do
196 var mpropdef = vft[i]
197 if mpropdef == null then
198 v.add_decl("NULL, /* empty */")
199 else
200 if true or mpropdef.mclassdef.bound_mtype.ctype != "val*" then
201 v.add_decl("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
202 else
203 v.add_decl("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
204 end
205 end
206 end
207 v.add_decl("\}")
208 v.add_decl("\};")
209
210 build_class_vts_table(mclass, v.as(SeparateErasureCompilerVisitor))
211
212 # Build class type table
213 self.header.add_decl("extern const struct type_table_{c_name} type_table_{c_name};")
214 self.header.add_decl("struct type_table_{c_name} \{")
215 self.header.add_decl("int size;")
216 self.header.add_decl("int table[{class_table.length}];")
217 self.header.add_decl("\};")
218
219 v.add_decl("const struct type_table_{c_name} type_table_{c_name} = \{")
220 v.add_decl("{class_table.length},")
221 v.add_decl("\{")
222 for msuper in class_table do
223 if msuper == null then
224 v.add_decl("-1, /* empty */")
225 else
226 v.add_decl("{self.class_ids[msuper]}, /* {msuper} */")
227 end
228 end
229 v.add_decl("\}")
230 v.add_decl("\};")
231
232 #Build instance struct
233 if mtype.ctype != "val*" then
234 self.header.add_decl("struct instance_{c_name} \{")
235 self.header.add_decl("const struct class *class;")
236 self.header.add_decl("{mtype.ctype} value;")
237 self.header.add_decl("\};")
238
239 self.header.add_decl("val* BOX_{c_name}({mtype.ctype});")
240 v.add_decl("/* allocate {mtype} */")
241 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
242 v.add("struct instance_{c_name}*res = GC_MALLOC(sizeof(struct instance_{c_name}));")
243 v.add("res->class = (struct class*) &class_{c_name};")
244 v.add("res->value = value;")
245 v.add("return (val*)res;")
246 v.add("\}")
247 return
248 end
249
250 var is_native_array = mclass.name == "NativeArray"
251
252 var sig
253 if is_native_array then
254 sig = "int length"
255 else
256 sig = ""
257 end
258
259 #Build instance struct
260 #extern const struct instance_array__NativeArray instance_array__NativeArray;
261 self.header.add_decl("struct instance_{c_name} \{")
262 self.header.add_decl("const struct class *class;")
263 self.header.add_decl("nitattribute_t attrs[{attrs.length}];")
264 if is_native_array then
265 # NativeArrays are just a instance header followed by an array of values
266 self.header.add_decl("val* values[0];")
267 end
268 self.header.add_decl("\};")
269
270
271 self.header.add_decl("{mtype.ctype} NEW_{c_name}({sig});")
272 v.add_decl("/* allocate {mtype} */")
273 v.add_decl("{mtype.ctype} NEW_{c_name}({sig}) \{")
274 var res = v.new_named_var(mtype, "self")
275 res.is_exact = true
276 if is_native_array then
277 var mtype_elt = mtype.arguments.first
278 v.add("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
279 else
280 v.add("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
281 end
282 v.add("{res}->class = (struct class*) &class_{c_name};")
283
284 self.generate_init_attr(v, res, mtype)
285 v.add("return {res};")
286 v.add("\}")
287
288 generate_check_init_instance(mtype)
289 end
290
291 private fun build_class_vts_table(mclass: MClass, v: SeparateCompilerVisitor) do
292 self.header.add_decl("extern const struct vts_table_{mclass.c_name} vts_table_{mclass.c_name};")
293 self.header.add_decl("struct vts_table_{mclass.c_name} \{")
294 if modelbuilder.toolcontext.opt_phmod_typing.value or modelbuilder.toolcontext.opt_phand_typing.value then
295 self.header.add_decl("int mask;")
296 end
297 self.header.add_decl("struct vts_entry vts[{self.vt_tables[mclass].length}];")
298 self.header.add_decl("\};")
299
300 v.add_decl("const struct vts_table_{mclass.c_name} vts_table_{mclass.c_name} = \{")
301 if modelbuilder.toolcontext.opt_phmod_typing.value or modelbuilder.toolcontext.opt_phand_typing.value then
302 v.add_decl("{vt_masks[mclass]},")
303 end
304 v.add_decl("\{")
305
306 for vt in self.vt_tables[mclass] do
307 if vt == null then
308 v.add_decl("\{-1, NULL\}, /* empty */")
309 else
310 var is_null = 0
311 var bound = retrieve_vt_bound(mclass.intro.bound_mtype, vt.bound)
312 while bound isa MNullableType do
313 bound = retrieve_vt_bound(mclass.intro.bound_mtype, bound.mtype)
314 is_null = 1
315 end
316 v.add_decl("\{{is_null}, (struct class*)&class_{bound.as(MClassType).mclass.c_name}\}, /* {vt} */")
317 end
318 end
319 v.add_decl("\},")
320 v.add_decl("\};")
321 end
322
323 private fun retrieve_vt_bound(anchor: MClassType, mtype: nullable MType): MType do
324 if mtype == null then
325 print "NOT YET IMPLEMENTED: retrieve_vt_bound on null"
326 abort
327 end
328 if mtype isa MVirtualType then
329 return mtype.anchor_to(mainmodule, anchor)
330 else if mtype isa MParameterType then
331 return mtype.anchor_to(mainmodule, anchor)
332 else
333 return mtype
334 end
335 end
336
337 redef fun new_visitor do return new SeparateErasureCompilerVisitor(self)
338 end
339
340 class SeparateErasureCompilerVisitor
341 super SeparateCompilerVisitor
342
343 redef fun init_instance(mtype)
344 do
345 return self.new_expr("NEW_{mtype.mclass.c_name}()", mtype)
346 end
347
348 redef fun type_test(value, mtype)
349 do
350 self.add("/* type test for {value.inspect} isa {mtype} */")
351
352 var res = self.new_var(bool_type)
353
354 var cltype = self.get_name("cltype")
355 self.add_decl("int {cltype};")
356 var idtype = self.get_name("idtype")
357 self.add_decl("int {idtype};")
358 var is_nullable = self.get_name("is_nullable")
359 self.add_decl("short int {is_nullable};")
360 var is_null = self.get_name("is_null")
361 self.add_decl("short int {is_null};")
362
363 var maybe_null = 0
364 if mtype isa MNullableType then
365 mtype = mtype.mtype
366 maybe_null = 1
367 self.add("{is_nullable} = 1;")
368 end
369 if mtype isa MParameterType then
370 # Here we get the bound of the the formal type (eh, erasure...)
371 mtype = mtype.resolve_for(self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.mmodule, false)
372 if mtype isa MNullableType then
373 mtype = mtype.mtype
374 maybe_null = 1
375 self.add("{is_nullable} = 1;")
376 end
377 end
378 if mtype isa MVirtualType then
379 # FIXME virtual types should not be erased but got from the class table of the current receiver (self.frame.arguments.first)
380 #mtype = mtype.resolve_for(self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.mmodule, true)
381 #if mtype isa MNullableType then
382 # mtype = mtype.mtype
383 # maybe_null = true
384 #end
385 end
386
387 if value.mcasttype.is_subtype(self.frame.mpropdef.mclassdef.mmodule, self.frame.mpropdef.mclassdef.bound_mtype, mtype) then
388 self.add("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
389 return res
390 end
391
392 var class_ptr
393 var type_table
394 if value.mtype.ctype == "val*" then
395 class_ptr = "{value}->class->"
396 self.add("{is_null} = {value} == NULL;")
397 else
398 var mclass = value.mtype.as(MClassType).mclass
399 class_ptr = "class_{mclass.c_name}."
400 self.add("{is_null} = 0;")
401 end
402
403 if mtype isa MClassType then
404 self.add("{cltype} = class_{mtype.mclass.c_name}.color;")
405 self.add("{idtype} = class_{mtype.mclass.c_name}.id;")
406 if maybe_null == 0 then
407 self.add("{is_nullable} = 0;")
408 end
409 else if mtype isa MVirtualType then
410 var recv = self.frame.arguments.first
411 var recv_boxed = self.autobox(recv, self.object_type)
412 var entry = self.get_name("entry")
413 self.add("struct vts_entry {entry};")
414 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
415 self.add("{entry} = {recv_boxed}->class->vts_table->vts[HASH({recv_boxed}->class->vts_table->mask, {mtype.mproperty.const_color})];")
416 else
417 self.add("{entry} = {recv_boxed}->class->vts_table->vts[{mtype.mproperty.const_color}];")
418 end
419 self.add("{cltype} = {entry}.class->color;")
420 self.add("{idtype} = {entry}.class->id;")
421 if maybe_null == 0 then
422 self.add("{is_nullable} = {entry}.is_nullable;")
423 end
424 else
425 self.debug("type_test({value.inspect}, {mtype})")
426 abort
427 end
428
429 # check color is in table
430 self.add("if({is_null}) \{")
431 self.add("{res} = {is_nullable};")
432 self.add("\} else \{")
433 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
434 self.add("{cltype} = HASH({class_ptr}color, {idtype});")
435 end
436 self.add("if({cltype} >= {class_ptr}type_table->size) \{")
437 self.add("{res} = 0;")
438 self.add("\} else \{")
439 self.add("{res} = {class_ptr}type_table->table[{cltype}] == {idtype};")
440 self.add("\}")
441 self.add("\}")
442
443 return res
444 end
445
446 redef fun class_name_string(value)
447 do
448 var res = self.get_name("var_class_name")
449 self.add_decl("const char *{res};")
450 self.add("{res} = class_names[{value}->class->id];")
451 return res
452 end
453
454 redef fun array_instance(array, elttype)
455 do
456 var nclass = self.get_class("NativeArray")
457 elttype = self.anchor(elttype)
458 var arraytype = self.get_class("Array").get_mtype([elttype])
459 var res = self.init_instance(arraytype)
460 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
461 var nat = self.new_var(self.get_class("NativeArray").get_mtype([elttype]))
462 nat.is_exact = true
463 self.add("{nat} = NEW_{nclass.c_name}({array.length});")
464 for i in [0..array.length[ do
465 var r = self.autobox(array[i], self.object_type)
466 self.add("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
467 end
468 var length = self.int_instance(array.length)
469 self.send(self.get_property("with_native", arraytype), [res, nat, length])
470 self.check_init_instance(res, arraytype)
471 self.add("\}")
472 return res
473 end
474
475 redef fun calloc_array(ret_type, arguments)
476 do
477 var ret = ret_type.as(MClassType)
478 self.ret(self.new_expr("NEW_{ret.mclass.c_name}({arguments[1]})", ret_type))
479 end
480 end