1 # This file is part of NIT ( http://www.nitlanguage.org ).
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 # Separate compilation of a Nit program with generic type erasure
16 module separate_erasure_compiler
19 import separate_compiler
21 redef class ToolContext
23 var opt_erasure
: OptionBool = new OptionBool("Erase generic types", "--erasure")
25 # --no-check-erasure-cast
26 var opt_no_check_erasure_cast
: OptionBool = new OptionBool("Disable implicit casts on unsafe return with erasure-typing policy (dangerous)", "--no-check-erasure-cast")
31 self.option_context
.add_option
(self.opt_erasure
, self.opt_no_check_erasure_cast
)
35 redef class ModelBuilder
36 fun run_separate_erasure_compiler
(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis)
39 self.toolcontext
.info
("*** COMPILING TO C ***", 1)
41 var compiler
= new SeparateErasureCompiler(mainmodule
, runtime_type_analysis
, self)
42 compiler
.compile_header
44 # compile class structures
46 for m
in mainmodule
.in_importation
.greaters
do
47 for mclass
in m
.intro_mclasses
do
48 compiler
.compile_class_to_c
(mclass
)
52 # The main function of the C
54 compiler
.compile_main_function
57 for m
in mainmodule
.in_importation
.greaters
do
59 compiler
.compile_module_to_c
(m
)
62 compiler
.display_stats
64 write_and_make
(compiler
)
68 class SeparateErasureCompiler
69 super SeparateCompiler
71 private var class_ids
: HashMap[MClass, Int] = new HashMap[MClass, Int]
72 private var class_colors
: Map[MClass, Int]
73 private var class_tables
: Map[MClass, Array[nullable MClass]]
75 init(mainmodule
: MModule, runtime_type_analysis
: RapidTypeAnalysis, mmbuilder
: ModelBuilder) do
76 var mclasses
= new HashSet[MClass]
77 mclasses
.add_all
(mmbuilder
.model
.mclasses
)
80 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
82 for mclass
in mclasses
do
83 self.class_ids
[mclass
] = self.class_ids
.length
+ 1
86 var class_coloring
= new ClassModPerfectHashing(mainmodule
)
87 self.class_colors
= class_coloring
.compute_masks
(mclasses
, class_ids
)
88 self.class_tables
= class_coloring
.hash_type_tables
(mclasses
, class_ids
, class_colors
)
90 self.header
.add_decl
("#define HASH(mask, id) ((mask)%(id))")
91 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
93 for mclass
in mclasses
do
94 self.class_ids
[mclass
] = self.class_ids
.length
+ 1
97 var class_coloring
= new ClassAndPerfectHashing(mainmodule
)
98 self.class_colors
= class_coloring
.compute_masks
(mclasses
, class_ids
)
99 self.class_tables
= class_coloring
.hash_type_tables
(mclasses
, class_ids
, class_colors
)
101 self.header
.add_decl
("#define HASH(mask, id) ((mask)&(id))")
104 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
105 class_coloring
= new NaiveClassColoring(mainmodule
)
107 class_coloring
= new ClassColoring(mainmodule
)
110 for mclass
in mclasses
do
111 self.class_ids
[mclass
] = self.class_ids
.length
+ 1
113 self.class_colors
= class_coloring
.colorize
(modelbuilder
.model
.mclasses
)
114 self.class_tables
= class_coloring
.build_type_tables
(modelbuilder
.model
.mclasses
, class_colors
)
118 redef fun compile_header_structs
do
119 self.header
.add_decl
("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
120 self.compile_header_attribute_structs
121 self.header
.add_decl
("struct class \{ int id; const char *name; 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. */")
122 self.header
.add_decl
("struct type_table \{ int size; int table[1]; \}; /* colorized type table. */")
123 self.header
.add_decl
("struct vts_entry \{ short int is_nullable; struct class *class; \}; /* link (nullable or not) between the vts and is bound. */")
125 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
126 self.header
.add_decl
("struct vts_table \{ int mask; struct vts_entry vts[1]; \}; /* vts list of a C type representation. */")
128 self.header
.add_decl
("struct vts_table \{ struct vts_entry vts[1]; \}; /* vts list of a C type representation. */")
131 self.header
.add_decl
("typedef struct val \{ struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
134 redef fun compile_class_to_c
(mclass
: MClass)
136 var mtype
= mclass
.intro
.bound_mtype
137 var c_name
= mclass
.c_name
139 var vft
= self.method_tables
[mclass
]
140 var attrs
= self.attr_tables
[mclass
]
141 var class_table
= self.class_tables
[mclass
]
142 var v
= self.new_visitor
144 v
.add_decl
("/* runtime class {c_name} */")
145 var idnum
= classids
.length
146 var idname
= "ID_" + c_name
147 self.classids
[mtype
] = idname
148 #self.header.add_decl("#define {idname} {idnum} /* {c_name} */")
150 self.header
.add_decl
("extern const struct class_{c_name} class_{c_name};")
151 self.header
.add_decl
("struct class_{c_name} \{")
152 self.header
.add_decl
("int id;")
153 self.header
.add_decl
("const char *name;")
154 self.header
.add_decl
("int box_kind;")
155 self.header
.add_decl
("int color;")
156 self.header
.add_decl
("const struct vts_table *vts_table;")
157 self.header
.add_decl
("struct type_table *type_table;")
158 self.header
.add_decl
("nitmethod_t vft[{vft.length}];")
159 self.header
.add_decl
("\};")
162 v
.add_decl
("const struct class_{c_name} class_{c_name} = \{")
163 v
.add_decl
("{self.class_ids[mclass]},")
164 v
.add_decl
("\"{mclass.name}\
", /* class_name_string */")
165 v
.add_decl
("{self.box_kind_of(mclass)}, /* box_kind */")
166 v
.add_decl
("{self.class_colors[mclass]},")
167 if build_class_vts_table
(mclass
) then
168 v
.add_decl
("(const struct vts_table*) &vts_table_{c_name},")
172 v
.add_decl
("(struct type_table*) &type_table_{c_name},")
174 for i
in [0 .. vft
.length
[ do
175 var mpropdef
= vft
[i
]
176 if mpropdef
== null then
177 v
.add_decl
("NULL, /* empty */")
179 if true or mpropdef
.mclassdef
.bound_mtype
.ctype
!= "val*" then
180 v
.add_decl
("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
182 v
.add_decl
("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
189 # Build class type table
190 self.header
.add_decl
("extern const struct type_table_{c_name} type_table_{c_name};")
191 self.header
.add_decl
("struct type_table_{c_name} \{")
192 self.header
.add_decl
("int size;")
193 self.header
.add_decl
("int table[{class_table.length}];")
194 self.header
.add_decl
("\};")
196 v
.add_decl
("const struct type_table_{c_name} type_table_{c_name} = \{")
197 v
.add_decl
("{class_table.length},")
199 for msuper
in class_table
do
200 if msuper
== null then
201 v
.add_decl
("-1, /* empty */")
203 v
.add_decl
("{self.class_ids[msuper]}, /* {msuper} */")
209 #Build instance struct
210 if mtype
.ctype
!= "val*" then
211 self.header
.add_decl
("struct instance_{c_name} \{")
212 self.header
.add_decl
("const struct class *class;")
213 self.header
.add_decl
("{mtype.ctype} value;")
214 self.header
.add_decl
("\};")
216 self.header
.add_decl
("val* BOX_{c_name}({mtype.ctype});")
217 v
.add_decl
("/* allocate {mtype} */")
218 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
219 v
.add
("struct instance_{c_name}*res = GC_MALLOC(sizeof(struct instance_{c_name}));")
220 v
.add
("res->class = (struct class*) &class_{c_name};")
221 v
.add
("res->value = value;")
222 v
.add
("return (val*)res;")
227 var is_native_array
= mclass
.name
== "NativeArray"
230 if is_native_array
then
236 #Build instance struct
237 #extern const struct instance_array__NativeArray instance_array__NativeArray;
238 self.header
.add_decl
("struct instance_{c_name} \{")
239 self.header
.add_decl
("const struct class *class;")
240 self.header
.add_decl
("nitattribute_t attrs[{attrs.length}];")
241 if is_native_array
then
242 # NativeArrays are just a instance header followed by an array of values
243 self.header
.add_decl
("val* values[0];")
245 self.header
.add_decl
("\};")
248 self.header
.add_decl
("{mtype.ctype} NEW_{c_name}({sig});")
249 v
.add_decl
("/* allocate {mtype} */")
250 v
.add_decl
("{mtype.ctype} NEW_{c_name}({sig}) \{")
251 var res
= v
.new_named_var
(mtype
, "self")
253 if is_native_array
then
254 var mtype_elt
= mtype
.arguments
.first
255 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
257 v
.add
("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
259 v
.add
("{res}->class = (struct class*) &class_{c_name};")
261 self.generate_init_attr
(v
, res
, mtype
)
262 v
.add
("return {res};")
265 generate_check_init_instance
(mtype
)
268 private fun build_class_vts_table
(mclass
: MClass): Bool do
269 if self.vt_tables
[mclass
].is_empty
then return false
271 self.header
.add_decl
("extern const struct vts_table_{mclass.c_name} vts_table_{mclass.c_name};")
272 self.header
.add_decl
("struct vts_table_{mclass.c_name} \{")
273 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
274 self.header
.add_decl
("int mask;")
276 self.header
.add_decl
("struct vts_entry vts[{self.vt_tables[mclass].length}];")
277 self.header
.add_decl
("\};")
280 v
.add_decl
("const struct vts_table_{mclass.c_name} vts_table_{mclass.c_name} = \{")
281 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
282 v
.add_decl
("{vt_masks[mclass]},")
286 for vt
in self.vt_tables
[mclass
] do
288 v
.add_decl
("\{-1, NULL\}, /* empty */")
291 var bound
= retrieve_vt_bound
(mclass
.intro
.bound_mtype
, vt
.bound
)
292 while bound
isa MNullableType do
293 bound
= retrieve_vt_bound
(mclass
.intro
.bound_mtype
, bound
.mtype
)
296 v
.add_decl
("\{{is_null}, (struct class*)&class_{bound.as(MClassType).mclass.c_name}\}, /* {vt} */")
304 private fun retrieve_vt_bound
(anchor
: MClassType, mtype
: nullable MType): MType do
305 if mtype
== null then
306 print
"NOT YET IMPLEMENTED: retrieve_vt_bound on null"
309 if mtype
isa MVirtualType then
310 return mtype
.anchor_to
(mainmodule
, anchor
)
311 else if mtype
isa MParameterType then
312 return mtype
.anchor_to
(mainmodule
, anchor
)
318 redef fun new_visitor
do return new SeparateErasureCompilerVisitor(self)
321 class SeparateErasureCompilerVisitor
322 super SeparateCompilerVisitor
324 redef fun compile_callsite
(callsite
, arguments
)
327 if callsite
.erasure_cast
and not self.compiler
.as(SeparateErasureCompiler).modelbuilder
.toolcontext
.opt_no_check_erasure_cast
.value
then
329 var mtype
= callsite
.msignature
.return_mtype
331 self.add
("/* Erasure cast for return {res} isa {mtype} */")
332 var cond
= self.type_test
(res
, mtype
, "erasure")
333 self.add
("if (!{cond}) \{")
334 #var x = self.class_name_string(res)
335 #var y = self.class_name_string(arguments.first)
336 #self.add("fprintf(stderr, \"Erasure cast: expected {mtype} (self is %s), got %s for {res}\\n\", {y}, {x});")
337 self.add_abort
("Cast failed")
343 redef fun init_instance
(mtype
)
345 return self.new_expr
("NEW_{mtype.mclass.c_name}()", mtype
)
348 redef fun type_test
(value
, mtype
, tag
)
350 self.add
("/* type test for {value.inspect} isa {mtype} */")
352 var res
= self.new_var
(bool_type
)
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};")
359 var maybe_null
= self.maybe_null
(value
)
360 var accept_null
= "0"
361 if mtype
isa MNullableType then
365 if mtype
isa MParameterType then
366 # Here we get the bound of the the formal type (eh, erasure...)
367 mtype
= mtype
.resolve_for
(self.frame
.mpropdef
.mclassdef
.bound_mtype
, self.frame
.mpropdef
.mclassdef
.bound_mtype
, self.frame
.mpropdef
.mclassdef
.mmodule
, false)
368 if mtype
isa MNullableType then
374 if value
.mcasttype
.is_subtype
(self.frame
.mpropdef
.mclassdef
.mmodule
, self.frame
.mpropdef
.mclassdef
.bound_mtype
, mtype
) then
375 self.add
("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
376 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
377 self.compiler
.count_type_test_skipped
[tag
] += 1
378 self.add
("count_type_test_skipped_{tag}++;")
385 if value
.mtype
.ctype
== "val*" then
386 class_ptr
= "{value}->class->"
388 var mclass
= value
.mtype
.as(MClassType).mclass
389 class_ptr
= "class_{mclass.c_name}."
392 if mtype
isa MClassType then
393 self.add
("{cltype} = class_{mtype.mclass.c_name}.color;")
394 self.add
("{idtype} = class_{mtype.mclass.c_name}.id;")
395 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
396 self.compiler
.count_type_test_resolved
[tag
] += 1
397 self.add
("count_type_test_resolved_{tag}++;")
399 else if mtype
isa MVirtualType then
400 var recv
= self.frame
.arguments
.first
402 if recv
.mtype
.ctype
== "val*" then
403 recv_ptr
= "{recv}->class->"
405 var mclass
= recv
.mtype
.as(MClassType).mclass
406 recv_ptr
= "class_{mclass.c_name}."
408 var entry
= self.get_name
("entry")
409 self.add
("struct vts_entry {entry};")
410 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
411 self.add
("{entry} = {recv_ptr}vts_table->vts[HASH({recv_ptr}vts_table->mask, {mtype.mproperty.const_color})];")
413 self.add
("{entry} = {recv_ptr}vts_table->vts[{mtype.mproperty.const_color}];")
415 self.add
("{cltype} = {entry}.class->color;")
416 self.add
("{idtype} = {entry}.class->id;")
417 if maybe_null
and accept_null
== "0" then
418 var is_nullable
= self.get_name
("is_nullable")
419 self.add_decl
("short int {is_nullable};")
420 self.add
("{is_nullable} = {entry}.is_nullable;")
421 accept_null
= is_nullable
.to_s
423 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
424 self.compiler
.count_type_test_unresolved
[tag
] += 1
425 self.add
("count_type_test_unresolved_{tag}++;")
428 self.debug
("type_test({value.inspect}, {mtype})")
432 # check color is in table
434 self.add
("if({value} == NULL) \{")
435 self.add
("{res} = {accept_null};")
436 self.add
("\} else \{")
438 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
439 self.add
("{cltype} = HASH({class_ptr}color, {idtype});")
441 self.add
("if({cltype} >= {class_ptr}type_table->size) \{")
442 self.add
("{res} = 0;")
443 self.add
("\} else \{")
444 self.add
("{res} = {class_ptr}type_table->table[{cltype}] == {idtype};")
453 redef fun class_name_string
(value
)
455 var res
= self.get_name
("var_class_name")
456 self.add_decl
("const char* {res};")
457 if value
.mtype
.ctype
== "val*" then
458 self.add
"{res} = {value} == NULL ? \"null\
" : {value}->class->name;"
460 self.add
"{res} = class_{value.mtype.c_name}.name;"
465 redef fun array_instance
(array
, elttype
)
467 var nclass
= self.get_class
("NativeArray")
468 elttype
= self.anchor
(elttype
)
469 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
470 var res
= self.init_instance
(arraytype
)
471 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
472 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
474 self.add
("{nat} = NEW_{nclass.c_name}({array.length});")
475 for i
in [0..array
.length
[ do
476 var r
= self.autobox
(array
[i
], self.object_type
)
477 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
479 var length
= self.int_instance
(array
.length
)
480 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
481 self.check_init_instance
(res
, arraytype
)
486 redef fun calloc_array
(ret_type
, arguments
)
488 var ret
= ret_type
.as(MClassType)
489 self.ret
(self.new_expr
("NEW_{ret.mclass.c_name}({arguments[1]})", ret_type
))