ni_nitdoc: added fast copy past utility to signatures.
[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 intrude import separate_compiler
19
20 # Add separate erased compiler specific options
21 redef class ToolContext
22 # --erasure
23 var opt_erasure: OptionBool = new OptionBool("Erase generic types", "--erasure")
24 # --no-check-erasure-cast
25 var opt_no_check_erasure_cast: OptionBool = new OptionBool("Disable implicit casts on unsafe return with erasure-typing policy (dangerous)", "--no-check-erasure-cast")
26
27 redef init
28 do
29 super
30 self.option_context.add_option(self.opt_erasure, self.opt_no_check_erasure_cast)
31 end
32 end
33
34 redef class ModelBuilder
35 fun run_separate_erasure_compiler(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis)
36 do
37 var time0 = get_time
38 self.toolcontext.info("*** GENERATING C ***", 1)
39
40 var compiler = new SeparateErasureCompiler(mainmodule, self, runtime_type_analysis)
41 compiler.compile_header
42
43 # compile class structures
44 self.toolcontext.info("Property coloring", 2)
45 compiler.new_file("{mainmodule.name}.tables")
46 compiler.do_property_coloring
47 for m in mainmodule.in_importation.greaters do
48 for mclass in m.intro_mclasses do
49 compiler.compile_class_to_c(mclass)
50 end
51 end
52 compiler.compile_color_consts(compiler.vt_layout.pos)
53
54 # The main function of the C
55 compiler.new_file("{mainmodule.name}.main")
56 compiler.compile_main_function
57
58 # compile methods
59 for m in mainmodule.in_importation.greaters do
60 self.toolcontext.info("Generate C for module {m}", 2)
61 compiler.new_file("{m.name}.sep")
62 compiler.compile_module_to_c(m)
63 end
64
65 compiler.display_stats
66
67 var time1 = get_time
68 self.toolcontext.info("*** END GENERATING C: {time1-time0} ***", 2)
69 write_and_make(compiler)
70 end
71 end
72
73 class SeparateErasureCompiler
74 super SeparateCompiler
75
76 private var class_layout: nullable Layout[MClass]
77 protected var vt_layout: nullable Layout[MVirtualTypeProp]
78
79 init(mainmodule: MModule, mmbuilder: ModelBuilder, runtime_type_analysis: RapidTypeAnalysis) do
80 super
81
82 var mclasses = new HashSet[MClass].from(mmbuilder.model.mclasses)
83
84 var layout_builder: TypingLayoutBuilder[MClass]
85 if modelbuilder.toolcontext.opt_phmod_typing.value then
86 layout_builder = new MClassHasher(new PHModOperator, mainmodule)
87 else if modelbuilder.toolcontext.opt_phand_typing.value then
88 layout_builder = new MClassHasher(new PHAndOperator, mainmodule)
89 else if modelbuilder.toolcontext.opt_bm_typing.value then
90 layout_builder = new MClassBMizer(mainmodule)
91 else
92 layout_builder = new MClassColorer(mainmodule)
93 end
94 self.class_layout = layout_builder.build_layout(mclasses)
95 self.class_tables = self.build_class_typing_tables(mclasses)
96
97 # vt coloration
98 var vt_coloring = new MVirtualTypePropColorer(mainmodule)
99 var vt_layout = vt_coloring.build_layout(mclasses)
100 self.vt_tables = build_vt_tables(mclasses, vt_layout)
101 self.vt_layout = vt_layout
102 end
103
104 fun build_vt_tables(mclasses: Set[MClass], layout: Layout[MProperty]): Map[MClass, Array[nullable MPropDef]] do
105 var tables = new HashMap[MClass, Array[nullable MPropDef]]
106 for mclass in mclasses do
107 var table = new Array[nullable MPropDef]
108 # first, fill table from parents by reverse linearization order
109 var parents = self.mainmodule.super_mclasses(mclass)
110 var lin = self.mainmodule.reverse_linearize_mclasses(parents)
111 for parent in lin do
112 for mproperty in self.mainmodule.properties(parent) do
113 if not mproperty isa MVirtualTypeProp then continue
114 var color = layout.pos[mproperty]
115 if table.length <= color then
116 for i in [table.length .. color[ do
117 table[i] = null
118 end
119 end
120 for mpropdef in mproperty.mpropdefs do
121 if mpropdef.mclassdef.mclass == parent then
122 table[color] = mpropdef
123 end
124 end
125 end
126 end
127
128 # then override with local properties
129 for mproperty in self.mainmodule.properties(mclass) do
130 if not mproperty isa MVirtualTypeProp then continue
131 var color = layout.pos[mproperty]
132 if table.length <= color then
133 for i in [table.length .. color[ do
134 table[i] = null
135 end
136 end
137 for mpropdef in mproperty.mpropdefs do
138 if mpropdef.mclassdef.mclass == mclass then
139 table[color] = mpropdef
140 end
141 end
142 end
143 tables[mclass] = table
144 end
145 return tables
146 end
147
148 # Build class tables
149 fun build_class_typing_tables(mclasses: Set[MClass]): Map[MClass, Array[nullable MClass]] do
150 var tables = new HashMap[MClass, Array[nullable MClass]]
151 var layout = self.class_layout
152 for mclass in mclasses do
153 var table = new Array[nullable MClass]
154 var supers = new HashSet[MClass]
155 supers.add_all(self.mainmodule.super_mclasses(mclass))
156 supers.add(mclass)
157 for sup in supers do
158 var color: Int
159 if layout isa PHLayout[MClass, MClass] then
160 color = layout.hashes[mclass][sup]
161 else
162 color = layout.pos[sup]
163 end
164 if table.length <= color then
165 for i in [table.length .. color[ do
166 table[i] = null
167 end
168 end
169 table[color] = sup
170 end
171 tables[mclass] = table
172 end
173 return tables
174 end
175
176 redef fun compile_header_structs do
177 self.header.add_decl("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
178 self.compile_header_attribute_structs
179 self.header.add_decl("struct class \{ int id; const char *name; int box_kind; int color; const struct vts_table *vts_table; const struct type_table *type_table; nitmethod_t vft[]; \}; /* general C type representing a Nit class. */")
180 self.header.add_decl("struct type_table \{ int size; int table[]; \}; /* colorized type table. */")
181 self.header.add_decl("struct vts_entry \{ short int is_nullable; const struct class *class; \}; /* link (nullable or not) between the vts and is bound. */")
182
183 if self.vt_layout isa PHLayout[MClass, MVirtualTypeProp] then
184 self.header.add_decl("struct vts_table \{ int mask; const struct vts_entry vts[]; \}; /* vts list of a C type representation. */")
185 else
186 self.header.add_decl("struct vts_table \{ int dummy; const struct vts_entry vts[]; \}; /* vts list of a C type representation. */")
187 end
188
189 if modelbuilder.toolcontext.opt_phmod_typing.value then
190 self.header.add_decl("#define HASH(mask, id) ((mask)%(id))")
191 else if modelbuilder.toolcontext.opt_phand_typing.value then
192 self.header.add_decl("#define HASH(mask, id) ((mask)&(id))")
193 end
194
195 self.header.add_decl("typedef struct instance \{ const struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
196 end
197
198 redef fun compile_class_to_c(mclass: MClass)
199 do
200 var mtype = mclass.intro.bound_mtype
201 var c_name = mclass.c_name
202
203 var vft = self.method_tables[mclass]
204 var attrs = self.attr_tables[mclass]
205 var class_table = self.class_tables[mclass]
206 var v = self.new_visitor
207
208 v.add_decl("/* runtime class {c_name} */")
209
210 self.provide_declaration("class_{c_name}", "extern const struct class class_{c_name};")
211 v.add_decl("extern const struct type_table type_table_{c_name};")
212
213 # Build class vft
214 v.add_decl("const struct class class_{c_name} = \{")
215 v.add_decl("{self.class_layout.ids[mclass]},")
216 v.add_decl("\"{mclass.name}\", /* class_name_string */")
217 v.add_decl("{self.box_kind_of(mclass)}, /* box_kind */")
218 var layout = self.class_layout
219 if layout isa PHLayout[MClass, MClass] then
220 v.add_decl("{layout.masks[mclass]},")
221 else
222 v.add_decl("{layout.pos[mclass]},")
223 end
224 if build_class_vts_table(mclass) then
225 v.require_declaration("vts_table_{c_name}")
226 v.add_decl("&vts_table_{c_name},")
227 else
228 v.add_decl("NULL,")
229 end
230 v.add_decl("&type_table_{c_name},")
231 v.add_decl("\{")
232 for i in [0 .. vft.length[ do
233 var mpropdef = vft[i]
234 if mpropdef == null then
235 v.add_decl("NULL, /* empty */")
236 else
237 if true or mpropdef.mclassdef.bound_mtype.ctype != "val*" then
238 v.require_declaration("VIRTUAL_{mpropdef.c_name}")
239 v.add_decl("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
240 else
241 v.require_declaration("{mpropdef.c_name}")
242 v.add_decl("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
243 end
244 end
245 end
246 v.add_decl("\}")
247 v.add_decl("\};")
248
249 # Build class type table
250
251 v.add_decl("const struct type_table type_table_{c_name} = \{")
252 v.add_decl("{class_table.length},")
253 v.add_decl("\{")
254 for msuper in class_table do
255 if msuper == null then
256 v.add_decl("-1, /* empty */")
257 else
258 v.add_decl("{self.class_layout.ids[msuper]}, /* {msuper} */")
259 end
260 end
261 v.add_decl("\}")
262 v.add_decl("\};")
263
264 if mtype.ctype != "val*" then
265 #Build instance struct
266 self.header.add_decl("struct instance_{c_name} \{")
267 self.header.add_decl("const struct class *class;")
268 self.header.add_decl("{mtype.ctype} value;")
269 self.header.add_decl("\};")
270
271 #Build BOX
272 self.header.add_decl("val* BOX_{c_name}({mtype.ctype});")
273 v.add_decl("/* allocate {mtype} */")
274 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
275 v.add("struct instance_{c_name}*res = nit_alloc(sizeof(struct instance_{c_name}));")
276 v.require_declaration("class_{c_name}")
277 v.add("res->class = &class_{c_name};")
278 v.add("res->value = value;")
279 v.add("return (val*)res;")
280 v.add("\}")
281 return
282 else if mclass.name == "NativeArray" then
283 #Build instance struct
284 self.header.add_decl("struct instance_{c_name} \{")
285 self.header.add_decl("const struct class *class;")
286 self.header.add_decl("val* values[];")
287 self.header.add_decl("\};")
288
289 #Build NEW
290 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(int length);")
291 v.add_decl("/* allocate {mtype} */")
292 v.add_decl("{mtype.ctype} NEW_{c_name}(int length) \{")
293 var res = v.new_named_var(mtype, "self")
294 res.is_exact = true
295 var mtype_elt = mtype.arguments.first
296 v.add("{res} = nit_alloc(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
297 v.require_declaration("class_{c_name}")
298 v.add("{res}->class = &class_{c_name};")
299 v.add("return {res};")
300 v.add("\}")
301 return
302 end
303
304 #Build NEW
305 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(void);")
306 v.add_decl("/* allocate {mtype} */")
307 v.add_decl("{mtype.ctype} NEW_{c_name}(void) \{")
308 var res = v.new_named_var(mtype, "self")
309 res.is_exact = true
310 v.add("{res} = nit_alloc(sizeof(struct instance) + {attrs.length}*sizeof(nitattribute_t));")
311 v.require_declaration("class_{c_name}")
312 v.add("{res}->class = &class_{c_name};")
313 self.generate_init_attr(v, res, mtype)
314 v.add("return {res};")
315 v.add("\}")
316
317 generate_check_init_instance(mtype)
318 end
319
320 private fun build_class_vts_table(mclass: MClass): Bool do
321 if self.vt_tables[mclass].is_empty then return false
322
323 self.provide_declaration("vts_table_{mclass.c_name}", "extern const struct vts_table vts_table_{mclass.c_name};")
324
325 var v = new_visitor
326 v.add_decl("const struct vts_table vts_table_{mclass.c_name} = \{")
327 if self.vt_layout isa PHLayout[MClass, MVirtualTypeProp] then
328 #TODO redo this when PHPropertyLayoutBuilder will be implemented
329 #v.add_decl("{vt_masks[mclass]},")
330 else
331 v.add_decl("0, /* dummy */")
332 end
333 v.add_decl("\{")
334
335 for vt in self.vt_tables[mclass] do
336 if vt == null then
337 v.add_decl("\{-1, NULL\}, /* empty */")
338 else
339 var is_null = 0
340 var bound = retrieve_vt_bound(mclass.intro.bound_mtype, vt.as(MVirtualTypeDef).bound)
341 while bound isa MNullableType do
342 bound = retrieve_vt_bound(mclass.intro.bound_mtype, bound.mtype)
343 is_null = 1
344 end
345 var vtclass = bound.as(MClassType).mclass
346 v.require_declaration("class_{vtclass.c_name}")
347 v.add_decl("\{{is_null}, &class_{vtclass.c_name}\}, /* {vt} */")
348 end
349 end
350 v.add_decl("\},")
351 v.add_decl("\};")
352 return true
353 end
354
355 private fun retrieve_vt_bound(anchor: MClassType, mtype: nullable MType): MType do
356 if mtype == null then
357 print "NOT YET IMPLEMENTED: retrieve_vt_bound on null"
358 abort
359 end
360 if mtype isa MVirtualType then
361 return mtype.anchor_to(mainmodule, anchor)
362 else if mtype isa MParameterType then
363 return mtype.anchor_to(mainmodule, anchor)
364 else
365 return mtype
366 end
367 end
368
369 redef fun new_visitor do return new SeparateErasureCompilerVisitor(self)
370
371 # Stats
372
373 private var class_tables: Map[MClass, Array[nullable MClass]]
374 private var vt_tables: Map[MClass, Array[nullable MPropDef]]
375
376 redef fun display_sizes
377 do
378 print "# size of subtyping tables"
379 print "\ttotal \tholes"
380 var total = 0
381 var holes = 0
382 for t, table in class_tables do
383 total += table.length
384 for e in table do if e == null then holes += 1
385 end
386 print "\t{total}\t{holes}"
387
388 print "# size of resolution tables"
389 print "\ttotal \tholes"
390 total = 0
391 holes = 0
392 for t, table in vt_tables do
393 total += table.length
394 for e in table do if e == null then holes += 1
395 end
396 print "\t{total}\t{holes}"
397
398 print "# size of methods tables"
399 print "\ttotal \tholes"
400 total = 0
401 holes = 0
402 for t, table in method_tables do
403 total += table.length
404 for e in table do if e == null then holes += 1
405 end
406 print "\t{total}\t{holes}"
407
408 print "# size of attributes tables"
409 print "\ttotal \tholes"
410 total = 0
411 holes = 0
412 for t, table in attr_tables do
413 total += table.length
414 for e in table do if e == null then holes += 1
415 end
416 print "\t{total}\t{holes}"
417 end
418 end
419
420 class SeparateErasureCompilerVisitor
421 super SeparateCompilerVisitor
422
423 redef fun compile_callsite(callsite, arguments)
424 do
425 var res = super
426 if callsite.erasure_cast and not self.compiler.as(SeparateErasureCompiler).modelbuilder.toolcontext.opt_no_check_erasure_cast.value then
427 assert res != null
428 var mtype = callsite.msignature.return_mtype
429 assert mtype != null
430 self.add("/* Erasure cast for return {res} isa {mtype} */")
431 var cond = self.type_test(res, mtype, "erasure")
432 self.add("if (!{cond}) \{")
433 #var x = self.class_name_string(res)
434 #var y = self.class_name_string(arguments.first)
435 #self.add("fprintf(stderr, \"Erasure cast: expected {mtype} (self is %s), got %s for {res}\\n\", {y}, {x});")
436 self.add_abort("Cast failed")
437 self.add("\}")
438 end
439 return res
440 end
441
442 redef fun init_instance(mtype)
443 do
444 self.require_declaration("NEW_{mtype.mclass.c_name}")
445 return self.new_expr("NEW_{mtype.mclass.c_name}()", mtype)
446 end
447
448 redef fun type_test(value, mtype, tag)
449 do
450 self.add("/* type test for {value.inspect} isa {mtype} */")
451
452 var res = self.new_var(bool_type)
453
454 var cltype = self.get_name("cltype")
455 self.add_decl("int {cltype};")
456 var idtype = self.get_name("idtype")
457 self.add_decl("int {idtype};")
458
459 var maybe_null = self.maybe_null(value)
460 var accept_null = "0"
461 if mtype isa MNullableType then
462 mtype = mtype.mtype
463 accept_null = "1"
464 end
465 if mtype isa MParameterType then
466 # Here we get the bound of the the formal type (eh, erasure...)
467 mtype = mtype.resolve_for(self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.mmodule, false)
468 if mtype isa MNullableType then
469 mtype = mtype.mtype
470 accept_null = "1"
471 end
472 end
473
474 if value.mcasttype.is_subtype(self.frame.mpropdef.mclassdef.mmodule, self.frame.mpropdef.mclassdef.bound_mtype, mtype) then
475 self.add("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
476 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
477 self.compiler.count_type_test_skipped[tag] += 1
478 self.add("count_type_test_skipped_{tag}++;")
479 end
480 return res
481 end
482
483 var class_ptr
484 var type_table
485 if value.mtype.ctype == "val*" then
486 class_ptr = "{value}->class->"
487 else
488 var mclass = value.mtype.as(MClassType).mclass
489 self.require_declaration("class_{mclass.c_name}")
490 class_ptr = "class_{mclass.c_name}."
491 end
492
493 if mtype isa MClassType then
494 self.require_declaration("class_{mtype.mclass.c_name}")
495 self.add("{cltype} = class_{mtype.mclass.c_name}.color;")
496 self.add("{idtype} = class_{mtype.mclass.c_name}.id;")
497 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
498 self.compiler.count_type_test_resolved[tag] += 1
499 self.add("count_type_test_resolved_{tag}++;")
500 end
501 else if mtype isa MVirtualType then
502 var recv = self.frame.arguments.first
503 var recv_ptr
504 if recv.mtype.ctype == "val*" then
505 recv_ptr = "{recv}->class->"
506 else
507 var mclass = recv.mtype.as(MClassType).mclass
508 self.require_declaration("class_{mclass.c_name}")
509 recv_ptr = "class_{mclass.c_name}."
510 end
511 var entry = self.get_name("entry")
512 self.add("struct vts_entry {entry};")
513 self.require_declaration(mtype.mproperty.const_color)
514 if self.compiler.as(SeparateErasureCompiler).vt_layout isa PHLayout[MClass, MVirtualTypeProp] then
515 self.add("{entry} = {recv_ptr}vts_table->vts[HASH({recv_ptr}vts_table->mask, {mtype.mproperty.const_color})];")
516 else
517 self.add("{entry} = {recv_ptr}vts_table->vts[{mtype.mproperty.const_color}];")
518 end
519 self.add("{cltype} = {entry}.class->color;")
520 self.add("{idtype} = {entry}.class->id;")
521 if maybe_null and accept_null == "0" then
522 var is_nullable = self.get_name("is_nullable")
523 self.add_decl("short int {is_nullable};")
524 self.add("{is_nullable} = {entry}.is_nullable;")
525 accept_null = is_nullable.to_s
526 end
527 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
528 self.compiler.count_type_test_unresolved[tag] += 1
529 self.add("count_type_test_unresolved_{tag}++;")
530 end
531 else
532 self.debug("type_test({value.inspect}, {mtype})")
533 abort
534 end
535
536 # check color is in table
537 if maybe_null then
538 self.add("if({value} == NULL) \{")
539 self.add("{res} = {accept_null};")
540 self.add("\} else \{")
541 end
542 if self.compiler.as(SeparateErasureCompiler).class_layout isa PHLayout[MClass, MClass] then
543 self.add("{cltype} = HASH({class_ptr}color, {idtype});")
544 end
545 self.add("if({cltype} >= {class_ptr}type_table->size) \{")
546 self.add("{res} = 0;")
547 self.add("\} else \{")
548 self.add("{res} = {class_ptr}type_table->table[{cltype}] == {idtype};")
549 self.add("\}")
550 if maybe_null then
551 self.add("\}")
552 end
553
554 return res
555 end
556
557 redef fun class_name_string(value)
558 do
559 var res = self.get_name("var_class_name")
560 self.add_decl("const char* {res};")
561 if value.mtype.ctype == "val*" then
562 self.add "{res} = {value} == NULL ? \"null\" : {value}->class->name;"
563 else
564 self.require_declaration("class_{value.mtype.c_name}")
565 self.add "{res} = class_{value.mtype.c_name}.name;"
566 end
567 return res
568 end
569
570 redef fun array_instance(array, elttype)
571 do
572 var nclass = self.get_class("NativeArray")
573 elttype = self.anchor(elttype)
574 var arraytype = self.get_class("Array").get_mtype([elttype])
575 var res = self.init_instance(arraytype)
576 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
577 var nat = self.new_var(self.get_class("NativeArray").get_mtype([elttype]))
578 nat.is_exact = true
579 self.require_declaration("NEW_{nclass.c_name}")
580 self.add("{nat} = NEW_{nclass.c_name}({array.length});")
581 for i in [0..array.length[ do
582 var r = self.autobox(array[i], self.object_type)
583 self.add("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
584 end
585 var length = self.int_instance(array.length)
586 self.send(self.get_property("with_native", arraytype), [res, nat, length])
587 self.check_init_instance(res, arraytype)
588 self.add("\}")
589 return res
590 end
591
592 redef fun calloc_array(ret_type, arguments)
593 do
594 var ret = ret_type.as(MClassType)
595 self.require_declaration("NEW_{ret.mclass.c_name}")
596 self.ret(self.new_expr("NEW_{ret.mclass.c_name}({arguments[1]})", ret_type))
597 end
598 end