model: try_get_primitive_method asks for a MClass (and not a MType)
[nit.git] / src / separate_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
16 module separate_compiler
17
18 import abstract_compiler
19 import layout_builders
20 import rapid_type_analysis
21
22 # Add separate compiler specific options
23 redef class ToolContext
24 # --separate
25 var opt_separate: OptionBool = new OptionBool("Use separate compilation", "--separate")
26 # --no-inline-intern
27 var opt_no_inline_intern: OptionBool = new OptionBool("Do not inline call to intern methods", "--no-inline-intern")
28 # --no-union-attribute
29 var opt_no_union_attribute: OptionBool = new OptionBool("Put primitive attibutes in a box instead of an union", "--no-union-attribute")
30 # --no-shortcut-equate
31 var opt_no_shortcut_equate: OptionBool = new OptionBool("Always call == in a polymorphic way", "--no-shortcut-equal")
32 # --inline-coloring-numbers
33 var opt_inline_coloring_numbers: OptionBool = new OptionBool("Inline colors and ids", "--inline-coloring-numbers")
34 # --use-naive-coloring
35 var opt_bm_typing: OptionBool = new OptionBool("Colorize items incrementaly, used to simulate binary matrix typing", "--bm-typing")
36 # --use-mod-perfect-hashing
37 var opt_phmod_typing: OptionBool = new OptionBool("Replace coloration by perfect hashing (with mod operator)", "--phmod-typing")
38 # --use-and-perfect-hashing
39 var opt_phand_typing: OptionBool = new OptionBool("Replace coloration by perfect hashing (with and operator)", "--phand-typing")
40 # --tables-metrics
41 var opt_tables_metrics: OptionBool = new OptionBool("Enable static size measuring of tables used for vft, typing and resolution", "--tables-metrics")
42
43 redef init
44 do
45 super
46 self.option_context.add_option(self.opt_separate)
47 self.option_context.add_option(self.opt_no_inline_intern)
48 self.option_context.add_option(self.opt_no_union_attribute)
49 self.option_context.add_option(self.opt_no_shortcut_equate)
50 self.option_context.add_option(self.opt_inline_coloring_numbers)
51 self.option_context.add_option(self.opt_bm_typing)
52 self.option_context.add_option(self.opt_phmod_typing)
53 self.option_context.add_option(self.opt_phand_typing)
54 self.option_context.add_option(self.opt_tables_metrics)
55 end
56 end
57
58 redef class ModelBuilder
59 fun run_separate_compiler(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis)
60 do
61 var time0 = get_time
62 self.toolcontext.info("*** GENERATING C ***", 1)
63
64 var compiler = new SeparateCompiler(mainmodule, self, runtime_type_analysis)
65 compiler.compile_header
66
67 # compile class structures
68 self.toolcontext.info("Property coloring", 2)
69 compiler.new_file("{mainmodule.name}.classes")
70 compiler.do_property_coloring
71 for m in mainmodule.in_importation.greaters do
72 for mclass in m.intro_mclasses do
73 if mclass.kind == abstract_kind or mclass.kind == interface_kind then continue
74 compiler.compile_class_to_c(mclass)
75 end
76 end
77
78 # The main function of the C
79 compiler.new_file("{mainmodule.name}.main")
80 compiler.compile_main_function
81
82 # compile methods
83 for m in mainmodule.in_importation.greaters do
84 self.toolcontext.info("Generate C for module {m}", 2)
85 compiler.new_file("{m.name}.sep")
86 compiler.compile_module_to_c(m)
87 end
88
89 # compile live & cast type structures
90 self.toolcontext.info("Type coloring", 2)
91 compiler.new_file("{mainmodule.name}.types")
92 var mtypes = compiler.do_type_coloring
93 for t in mtypes do
94 compiler.compile_type_to_c(t)
95 end
96
97 compiler.display_stats
98
99 var time1 = get_time
100 self.toolcontext.info("*** END GENERATING C: {time1-time0} ***", 2)
101 write_and_make(compiler)
102 end
103 end
104
105 # Singleton that store the knowledge about the separate compilation process
106 class SeparateCompiler
107 super AbstractCompiler
108
109 # The result of the RTA (used to know live types and methods)
110 var runtime_type_analysis: RapidTypeAnalysis
111
112 private var undead_types: Set[MType] = new HashSet[MType]
113 private var partial_types: Set[MType] = new HashSet[MType]
114 private var live_unresolved_types: Map[MClassDef, Set[MType]] = new HashMap[MClassDef, HashSet[MType]]
115
116 private var type_layout: nullable Layout[MType]
117 private var resolution_layout: nullable Layout[MType]
118 protected var method_layout: nullable Layout[MMethod]
119 protected var attr_layout: nullable Layout[MAttribute]
120
121 init(mainmodule: MModule, mmbuilder: ModelBuilder, runtime_type_analysis: RapidTypeAnalysis) do
122 super(mainmodule, mmbuilder)
123 var file = new_file("nit.common")
124 self.header = new CodeWriter(file)
125 self.runtime_type_analysis = runtime_type_analysis
126 self.compile_box_kinds
127 end
128
129 redef fun compile_header_structs do
130 self.header.add_decl("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
131 self.compile_header_attribute_structs
132 self.header.add_decl("struct class \{ int box_kind; nitmethod_t vft[]; \}; /* general C type representing a Nit class. */")
133
134 # With resolution_table_table, all live type resolution are stored in a big table: resolution_table
135 self.header.add_decl("struct type \{ int id; const char *name; int color; short int is_nullable; const struct types *resolution_table; int table_size; int type_table[]; \}; /* general C type representing a Nit type. */")
136 self.header.add_decl("struct instance \{ const struct type *type; const struct class *class; nitattribute_t attrs[]; \}; /* general C type representing a Nit instance. */")
137
138 if modelbuilder.toolcontext.opt_phmod_typing.value or modelbuilder.toolcontext.opt_phand_typing.value then
139 self.header.add_decl("struct types \{ int mask; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
140 else
141 self.header.add_decl("struct types \{ int dummy; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
142 end
143
144 if modelbuilder.toolcontext.opt_phmod_typing.value then
145 self.header.add_decl("#define HASH(mask, id) ((mask)%(id))")
146 else if modelbuilder.toolcontext.opt_phand_typing.value then
147 self.header.add_decl("#define HASH(mask, id) ((mask)&(id))")
148 end
149
150 self.header.add_decl("typedef struct instance val; /* general C type representing a Nit instance. */")
151 end
152
153 fun compile_header_attribute_structs
154 do
155 if modelbuilder.toolcontext.opt_no_union_attribute.value then
156 self.header.add_decl("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
157 else
158 self.header.add_decl("typedef union \{")
159 self.header.add_decl("void* val;")
160 for c, v in self.box_kinds do
161 var t = c.mclass_type
162 self.header.add_decl("{t.ctype} {t.ctypename};")
163 end
164 self.header.add_decl("\} nitattribute_t; /* general C type representing a Nit attribute. */")
165 end
166 end
167
168 fun compile_box_kinds
169 do
170 # Collect all bas box class
171 # FIXME: this is not completely fine with a separate compilation scheme
172 for classname in ["Int", "Bool", "Char", "Float", "NativeString", "Pointer"] do
173 var classes = self.mainmodule.model.get_mclasses_by_name(classname)
174 if classes == null then continue
175 assert classes.length == 1 else print classes.join(", ")
176 self.box_kinds[classes.first] = self.box_kinds.length + 1
177 end
178 end
179
180 var box_kinds = new HashMap[MClass, Int]
181
182 fun box_kind_of(mclass: MClass): Int
183 do
184 if mclass.mclass_type.ctype == "val*" then
185 return 0
186 else if mclass.kind == extern_kind then
187 return self.box_kinds[self.mainmodule.get_primitive_class("Pointer")]
188 else
189 return self.box_kinds[mclass]
190 end
191
192 end
193
194 fun compile_color_consts(colors: Map[Object, Int]) do
195 var v = new_visitor
196 for m, c in colors do
197 if color_consts_done.has(m) then continue
198 if m isa MProperty then
199 if modelbuilder.toolcontext.opt_inline_coloring_numbers.value then
200 self.provide_declaration(m.const_color, "#define {m.const_color} {c}")
201 else
202 self.provide_declaration(m.const_color, "extern const int {m.const_color};")
203 v.add("const int {m.const_color} = {c};")
204 end
205 else if m isa MType then
206 if modelbuilder.toolcontext.opt_inline_coloring_numbers.value then
207 self.provide_declaration(m.const_color, "#define {m.const_color} {c}")
208 else
209 self.provide_declaration(m.const_color, "extern const int {m.const_color};")
210 v.add("const int {m.const_color} = {c};")
211 end
212 end
213 color_consts_done.add(m)
214 end
215 end
216
217 private var color_consts_done = new HashSet[Object]
218
219 # colorize classe properties
220 fun do_property_coloring do
221 var mclasses = new HashSet[MClass].from(modelbuilder.model.mclasses)
222
223 # Layouts
224 var method_layout_builder: PropertyLayoutBuilder[MMethod]
225 var attribute_layout_builder: PropertyLayoutBuilder[MAttribute]
226 #FIXME PH and BM layouts too slow for large programs
227 #if modelbuilder.toolcontext.opt_bm_typing.value then
228 # method_layout_builder = new MMethodBMizer(self.mainmodule)
229 # attribute_layout_builder = new MAttributeBMizer(self.mainmodule)
230 #else if modelbuilder.toolcontext.opt_phmod_typing.value then
231 # method_layout_builder = new MMethodHasher(new PHModOperator, self.mainmodule)
232 # attribute_layout_builder = new MAttributeHasher(new PHModOperator, self.mainmodule)
233 #else if modelbuilder.toolcontext.opt_phand_typing.value then
234 # method_layout_builder = new MMethodHasher(new PHAndOperator, self.mainmodule)
235 # attribute_layout_builder = new MAttributeHasher(new PHAndOperator, self.mainmodule)
236 #else
237
238 var class_layout_builder = new MClassColorer(self.mainmodule)
239 class_layout_builder.build_layout(mclasses)
240 method_layout_builder = new MMethodColorer(self.mainmodule, class_layout_builder)
241 attribute_layout_builder = new MAttributeColorer(self.mainmodule, class_layout_builder)
242 #end
243
244 # methods coloration
245 var method_layout = method_layout_builder.build_layout(mclasses)
246 self.method_tables = build_method_tables(mclasses, method_layout)
247 self.compile_color_consts(method_layout.pos)
248 self.method_layout = method_layout
249
250 # attributes coloration
251 var attr_layout = attribute_layout_builder.build_layout(mclasses)
252 self.attr_tables = build_attr_tables(mclasses, attr_layout)
253 self.compile_color_consts(attr_layout.pos)
254 self.attr_layout = attr_layout
255 end
256
257 fun build_method_tables(mclasses: Set[MClass], layout: Layout[MProperty]): Map[MClass, Array[nullable MPropDef]] do
258 var tables = new HashMap[MClass, Array[nullable MPropDef]]
259 for mclass in mclasses do
260 var table = new Array[nullable MPropDef]
261 # first, fill table from parents by reverse linearization order
262 var parents = new Array[MClass]
263 if mainmodule.flatten_mclass_hierarchy.has(mclass) then
264 parents = mclass.in_hierarchy(mainmodule).greaters.to_a
265 self.mainmodule.linearize_mclasses(parents)
266 end
267 for parent in parents do
268 if parent == mclass then continue
269 for mproperty in self.mainmodule.properties(parent) do
270 if not mproperty isa MMethod then continue
271 var color = layout.pos[mproperty]
272 if table.length <= color then
273 for i in [table.length .. color[ do
274 table[i] = null
275 end
276 end
277 for mpropdef in mproperty.mpropdefs do
278 if mpropdef.mclassdef.mclass == parent then
279 table[color] = mpropdef
280 end
281 end
282 end
283 end
284
285 # then override with local properties
286 for mproperty in self.mainmodule.properties(mclass) do
287 if not mproperty isa MMethod then continue
288 var color = layout.pos[mproperty]
289 if table.length <= color then
290 for i in [table.length .. color[ do
291 table[i] = null
292 end
293 end
294 for mpropdef in mproperty.mpropdefs do
295 if mpropdef.mclassdef.mclass == mclass then
296 table[color] = mpropdef
297 end
298 end
299 end
300 tables[mclass] = table
301 end
302 return tables
303 end
304
305 fun build_attr_tables(mclasses: Set[MClass], layout: Layout[MProperty]): Map[MClass, Array[nullable MPropDef]] do
306 var tables = new HashMap[MClass, Array[nullable MPropDef]]
307 for mclass in mclasses do
308 var table = new Array[nullable MPropDef]
309 # first, fill table from parents by reverse linearization order
310 var parents = new Array[MClass]
311 if mainmodule.flatten_mclass_hierarchy.has(mclass) then
312 parents = mclass.in_hierarchy(mainmodule).greaters.to_a
313 self.mainmodule.linearize_mclasses(parents)
314 end
315 for parent in parents do
316 if parent == mclass then continue
317 for mproperty in self.mainmodule.properties(parent) do
318 if not mproperty isa MAttribute then continue
319 var color = layout.pos[mproperty]
320 if table.length <= color then
321 for i in [table.length .. color[ do
322 table[i] = null
323 end
324 end
325 for mpropdef in mproperty.mpropdefs do
326 if mpropdef.mclassdef.mclass == parent then
327 table[color] = mpropdef
328 end
329 end
330 end
331 end
332
333 # then override with local properties
334 for mproperty in self.mainmodule.properties(mclass) do
335 if not mproperty isa MAttribute then continue
336 var color = layout.pos[mproperty]
337 if table.length <= color then
338 for i in [table.length .. color[ do
339 table[i] = null
340 end
341 end
342 for mpropdef in mproperty.mpropdefs do
343 if mpropdef.mclassdef.mclass == mclass then
344 table[color] = mpropdef
345 end
346 end
347 end
348 tables[mclass] = table
349 end
350 return tables
351 end
352
353 # colorize live types of the program
354 private fun do_type_coloring: POSet[MType] do
355 var mtypes = new HashSet[MType]
356 mtypes.add_all(self.runtime_type_analysis.live_types)
357 mtypes.add_all(self.runtime_type_analysis.live_cast_types)
358 mtypes.add_all(self.undead_types)
359 for c in self.box_kinds.keys do
360 mtypes.add(c.mclass_type)
361 end
362
363 for mtype in mtypes do
364 retrieve_partial_types(mtype)
365 end
366 mtypes.add_all(self.partial_types)
367
368 # Typing Layout
369 var layout_builder: TypingLayoutBuilder[MType]
370 if modelbuilder.toolcontext.opt_bm_typing.value then
371 layout_builder = new MTypeBMizer(self.mainmodule)
372 else if modelbuilder.toolcontext.opt_phmod_typing.value then
373 layout_builder = new MTypeHasher(new PHModOperator, self.mainmodule)
374 else if modelbuilder.toolcontext.opt_phand_typing.value then
375 layout_builder = new MTypeHasher(new PHAndOperator, self.mainmodule)
376 else
377 layout_builder = new MTypeColorer(self.mainmodule)
378 end
379
380 # colorize types
381 self.type_layout = layout_builder.build_layout(mtypes)
382 var poset = layout_builder.poset.as(not null)
383 self.type_tables = self.build_type_tables(poset)
384
385 # VT and FT are stored with other unresolved types in the big resolution_tables
386 self.compile_resolution_tables(mtypes)
387
388 return poset
389 end
390
391 # Build type tables
392 fun build_type_tables(mtypes: POSet[MType]): Map[MType, Array[nullable MType]] do
393 var tables = new HashMap[MType, Array[nullable MType]]
394 var layout = self.type_layout
395 for mtype in mtypes do
396 var table = new Array[nullable MType]
397 for sup in mtypes[mtype].greaters do
398 var color: Int
399 if layout isa PHLayout[MType, MType] then
400 color = layout.hashes[mtype][sup]
401 else
402 color = layout.pos[sup]
403 end
404 if table.length <= color then
405 for i in [table.length .. color[ do
406 table[i] = null
407 end
408 end
409 table[color] = sup
410 end
411 tables[mtype] = table
412 end
413 return tables
414 end
415
416 protected fun compile_resolution_tables(mtypes: Set[MType]) do
417 # resolution_tables is used to perform a type resolution at runtime in O(1)
418
419 # During the visit of the body of classes, live_unresolved_types are collected
420 # and associated to
421 # Collect all live_unresolved_types (visited in the body of classes)
422
423 # Determinate fo each livetype what are its possible requested anchored types
424 var mtype2unresolved = new HashMap[MClassType, Set[MType]]
425 for mtype in self.runtime_type_analysis.live_types do
426 var set = new HashSet[MType]
427 for cd in mtype.collect_mclassdefs(self.mainmodule) do
428 if self.live_unresolved_types.has_key(cd) then
429 set.add_all(self.live_unresolved_types[cd])
430 end
431 end
432 mtype2unresolved[mtype] = set
433 end
434
435 # Compute the table layout with the prefered method
436 var resolution_builder: ResolutionLayoutBuilder
437 if modelbuilder.toolcontext.opt_bm_typing.value then
438 resolution_builder = new ResolutionBMizer
439 else if modelbuilder.toolcontext.opt_phmod_typing.value then
440 resolution_builder = new ResolutionHasher(new PHModOperator)
441 else if modelbuilder.toolcontext.opt_phand_typing.value then
442 resolution_builder = new ResolutionHasher(new PHAndOperator)
443 else
444 resolution_builder = new ResolutionColorer
445 end
446 self.resolution_layout = resolution_builder.build_layout(mtype2unresolved)
447 self.resolution_tables = self.build_resolution_tables(mtype2unresolved)
448
449 # Compile a C constant for each collected unresolved type.
450 # Either to a color, or to -1 if the unresolved type is dead (no live receiver can require it)
451 var all_unresolved = new HashSet[MType]
452 for t in self.live_unresolved_types.values do
453 all_unresolved.add_all(t)
454 end
455 var all_unresolved_types_colors = new HashMap[MType, Int]
456 for t in all_unresolved do
457 if self.resolution_layout.pos.has_key(t) then
458 all_unresolved_types_colors[t] = self.resolution_layout.pos[t]
459 else
460 all_unresolved_types_colors[t] = -1
461 end
462 end
463 self.compile_color_consts(all_unresolved_types_colors)
464
465 #print "tables"
466 #for k, v in unresolved_types_tables.as(not null) do
467 # print "{k}: {v.join(", ")}"
468 #end
469 #print ""
470 end
471
472 fun build_resolution_tables(elements: Map[MClassType, Set[MType]]): Map[MClassType, Array[nullable MType]] do
473 var tables = new HashMap[MClassType, Array[nullable MType]]
474 var layout = self.resolution_layout
475 for mclasstype, mtypes in elements do
476 var table = new Array[nullable MType]
477 for mtype in mtypes do
478 var color: Int
479 if layout isa PHLayout[MClassType, MType] then
480 color = layout.hashes[mclasstype][mtype]
481 else
482 color = layout.pos[mtype]
483 end
484 if table.length <= color then
485 for i in [table.length .. color[ do
486 table[i] = null
487 end
488 end
489 table[color] = mtype
490 end
491 tables[mclasstype] = table
492 end
493 return tables
494 end
495
496 fun retrieve_partial_types(mtype: MType) do
497 # add formal types arguments to mtypes
498 if mtype isa MGenericType then
499 for ft in mtype.arguments do
500 if ft.need_anchor then
501 print("Why do we need anchor here ?")
502 abort
503 end
504 self.partial_types.add(ft)
505 retrieve_partial_types(ft)
506 end
507 end
508 var mclass_type: MClassType
509 if mtype isa MNullableType then
510 mclass_type = mtype.mtype.as(MClassType)
511 else
512 mclass_type = mtype.as(MClassType)
513 end
514
515 # add virtual types to mtypes
516 for vt in self.mainmodule.properties(mclass_type.mclass) do
517 if vt isa MVirtualTypeProp then
518 var anchored = vt.mvirtualtype.lookup_bound(self.mainmodule, mclass_type).anchor_to(self.mainmodule, mclass_type)
519 self.partial_types.add(anchored)
520 end
521 end
522 end
523
524 # Separately compile all the method definitions of the module
525 fun compile_module_to_c(mmodule: MModule)
526 do
527 var old_module = self.mainmodule
528 self.mainmodule = mmodule
529 for cd in mmodule.mclassdefs do
530 for pd in cd.mpropdefs do
531 if not pd isa MMethodDef then continue
532 #print "compile {pd} @ {cd} @ {mmodule}"
533 var r = pd.separate_runtime_function
534 r.compile_to_c(self)
535 var r2 = pd.virtual_runtime_function
536 r2.compile_to_c(self)
537 end
538 end
539 self.mainmodule = old_module
540 end
541
542 # Globaly compile the type structure of a live type
543 fun compile_type_to_c(mtype: MType)
544 do
545 var c_name = mtype.c_name
546 var v = new SeparateCompilerVisitor(self)
547 v.add_decl("/* runtime type {mtype} */")
548
549 # extern const struct type_X
550 self.provide_declaration("type_{c_name}", "extern const struct type type_{c_name};")
551
552 # const struct type_X
553 v.add_decl("const struct type type_{c_name} = \{")
554 v.add_decl("{self.type_layout.ids[mtype]},")
555 v.add_decl("\"{mtype}\", /* class_name_string */")
556 var layout = self.type_layout
557 if layout isa PHLayout[MType, MType] then
558 v.add_decl("{layout.masks[mtype]},")
559 else
560 v.add_decl("{layout.pos[mtype]},")
561 end
562 if mtype isa MNullableType then
563 v.add_decl("1,")
564 else
565 v.add_decl("0,")
566 end
567 if compile_type_resolution_table(mtype) then
568 v.require_declaration("resolution_table_{c_name}")
569 v.add_decl("&resolution_table_{c_name},")
570 else
571 v.add_decl("NULL,")
572 end
573 v.add_decl("{self.type_tables[mtype].length},")
574 v.add_decl("\{")
575 for stype in self.type_tables[mtype] do
576 if stype == null then
577 v.add_decl("-1, /* empty */")
578 else
579 v.add_decl("{self.type_layout.ids[stype]}, /* {stype} */")
580 end
581 end
582 v.add_decl("\},")
583 v.add_decl("\};")
584 end
585
586 fun compile_type_resolution_table(mtype: MType): Bool do
587
588 var mclass_type: MClassType
589 if mtype isa MNullableType then
590 mclass_type = mtype.mtype.as(MClassType)
591 else
592 mclass_type = mtype.as(MClassType)
593 end
594 if not self.resolution_tables.has_key(mclass_type) then return false
595
596 var layout = self.resolution_layout
597
598 # extern const struct resolution_table_X resolution_table_X
599 self.provide_declaration("resolution_table_{mtype.c_name}", "extern const struct types resolution_table_{mtype.c_name};")
600
601 # const struct fts_table_X fts_table_X
602 var v = new_visitor
603 v.add_decl("const struct types resolution_table_{mtype.c_name} = \{")
604 if layout isa PHLayout[MClassType, MType] then
605 v.add_decl("{layout.masks[mclass_type]},")
606 else
607 v.add_decl("0, /* dummy */")
608 end
609 v.add_decl("\{")
610 for t in self.resolution_tables[mclass_type] do
611 if t == null then
612 v.add_decl("NULL, /* empty */")
613 else
614 # The table stores the result of the type resolution
615 # Therefore, for a receiver `mclass_type`, and a unresolved type `t`
616 # the value stored is tv.
617 var tv = t.resolve_for(mclass_type, mclass_type, self.mainmodule, true)
618 # FIXME: What typeids means here? How can a tv not be live?
619 if self.type_layout.ids.has_key(tv) then
620 v.require_declaration("type_{tv.c_name}")
621 v.add_decl("&type_{tv.c_name}, /* {t}: {tv} */")
622 else
623 v.add_decl("NULL, /* empty ({t}: {tv} not a live type) */")
624 end
625 end
626 end
627 v.add_decl("\}")
628 v.add_decl("\};")
629 return true
630 end
631
632 # Globally compile the table of the class mclass
633 # In a link-time optimisation compiler, tables are globally computed
634 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
635 fun compile_class_to_c(mclass: MClass)
636 do
637 var mtype = mclass.intro.bound_mtype
638 var c_name = mclass.c_name
639
640 var vft = self.method_tables[mclass]
641 var attrs = self.attr_tables[mclass]
642 var v = new_visitor
643
644 var is_dead = not runtime_type_analysis.live_classes.has(mclass) and mtype.ctype == "val*" and mclass.name != "NativeArray"
645
646 v.add_decl("/* runtime class {c_name} */")
647
648 # Build class vft
649 if not is_dead then
650 self.provide_declaration("class_{c_name}", "extern const struct class class_{c_name};")
651 v.add_decl("const struct class class_{c_name} = \{")
652 v.add_decl("{self.box_kind_of(mclass)}, /* box_kind */")
653 v.add_decl("\{")
654 for i in [0 .. vft.length[ do
655 var mpropdef = vft[i]
656 if mpropdef == null then
657 v.add_decl("NULL, /* empty */")
658 else
659 assert mpropdef isa MMethodDef
660 var rf = mpropdef.virtual_runtime_function
661 v.require_declaration(rf.c_name)
662 v.add_decl("(nitmethod_t){rf.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
663 end
664 end
665 v.add_decl("\}")
666 v.add_decl("\};")
667 end
668
669 if mtype.ctype != "val*" then
670 #Build instance struct
671 self.header.add_decl("struct instance_{c_name} \{")
672 self.header.add_decl("const struct type *type;")
673 self.header.add_decl("const struct class *class;")
674 self.header.add_decl("{mtype.ctype} value;")
675 self.header.add_decl("\};")
676
677 if not self.runtime_type_analysis.live_types.has(mtype) then return
678
679 #Build BOX
680 self.header.add_decl("val* BOX_{c_name}({mtype.ctype});")
681 v.add_decl("/* allocate {mtype} */")
682 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
683 v.add("struct instance_{c_name}*res = nit_alloc(sizeof(struct instance_{c_name}));")
684 v.require_declaration("type_{c_name}")
685 v.add("res->type = &type_{c_name};")
686 v.require_declaration("class_{c_name}")
687 v.add("res->class = &class_{c_name};")
688 v.add("res->value = value;")
689 v.add("return (val*)res;")
690 v.add("\}")
691 return
692 else if mclass.name == "NativeArray" then
693 #Build instance struct
694 self.header.add_decl("struct instance_{c_name} \{")
695 self.header.add_decl("const struct type *type;")
696 self.header.add_decl("const struct class *class;")
697 # NativeArrays are just a instance header followed by an array of values
698 self.header.add_decl("val* values[0];")
699 self.header.add_decl("\};")
700
701 #Build NEW
702 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(int length, const struct type* type);")
703 v.add_decl("/* allocate {mtype} */")
704 v.add_decl("{mtype.ctype} NEW_{c_name}(int length, const struct type* type) \{")
705 var res = v.new_named_var(mtype, "self")
706 res.is_exact = true
707 var mtype_elt = mtype.arguments.first
708 v.add("{res} = nit_alloc(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
709 v.add("{res}->type = type;")
710 hardening_live_type(v, "type")
711 v.require_declaration("class_{c_name}")
712 v.add("{res}->class = &class_{c_name};")
713 v.add("return {res};")
714 v.add("\}")
715 return
716 end
717
718 #Build NEW
719 self.provide_declaration("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(const struct type* type);")
720 v.add_decl("/* allocate {mtype} */")
721 v.add_decl("{mtype.ctype} NEW_{c_name}(const struct type* type) \{")
722 if is_dead then
723 v.add_abort("{mclass} is DEAD")
724 else
725 var res = v.new_named_var(mtype, "self")
726 res.is_exact = true
727 v.add("{res} = nit_alloc(sizeof(struct instance) + {attrs.length}*sizeof(nitattribute_t));")
728 v.add("{res}->type = type;")
729 hardening_live_type(v, "type")
730 v.require_declaration("class_{c_name}")
731 v.add("{res}->class = &class_{c_name};")
732 self.generate_init_attr(v, res, mtype)
733 v.add("return {res};")
734 end
735 v.add("\}")
736
737 generate_check_init_instance(mtype)
738 end
739
740 # Add a dynamic test to ensure that the type referenced by `t` is a live type
741 fun hardening_live_type(v: VISITOR, t: String)
742 do
743 if not v.compiler.modelbuilder.toolcontext.opt_hardening.value then return
744 v.add("if({t} == NULL) \{")
745 v.add_abort("type null")
746 v.add("\}")
747 v.add("if({t}->resolution_table == NULL) \{")
748 v.add("fprintf(stderr, \"Insantiation of a dead type: %s\\n\", {t}->name);")
749 v.add_abort("type dead")
750 v.add("\}")
751 end
752
753 redef fun generate_check_init_instance(mtype)
754 do
755 if self.modelbuilder.toolcontext.opt_no_check_initialization.value then return
756
757 var v = self.new_visitor
758 var c_name = mtype.mclass.c_name
759 var res = new RuntimeVariable("self", mtype, mtype)
760 self.provide_declaration("CHECK_NEW_{c_name}", "void CHECK_NEW_{c_name}({mtype.ctype});")
761 v.add_decl("/* allocate {mtype} */")
762 v.add_decl("void CHECK_NEW_{c_name}({mtype.ctype} {res}) \{")
763 if runtime_type_analysis.live_classes.has(mtype.mclass) then
764 self.generate_check_attr(v, res, mtype)
765 else
766 v.add_abort("{mtype.mclass} is DEAD")
767 end
768 v.add("\}")
769 end
770
771 redef fun new_visitor do return new SeparateCompilerVisitor(self)
772
773 # Stats
774
775 private var type_tables: Map[MType, Array[nullable MType]] = new HashMap[MType, Array[nullable MType]]
776 private var resolution_tables: Map[MClassType, Array[nullable MType]] = new HashMap[MClassType, Array[nullable MType]]
777 protected var method_tables: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
778 protected var attr_tables: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
779
780 redef fun display_stats
781 do
782 super
783 if self.modelbuilder.toolcontext.opt_tables_metrics.value then
784 display_sizes
785 end
786 end
787
788 fun display_sizes
789 do
790 print "# size of subtyping tables"
791 print "\ttotal \tholes"
792 var total = 0
793 var holes = 0
794 for t, table in type_tables do
795 total += table.length
796 for e in table do if e == null then holes += 1
797 end
798 print "\t{total}\t{holes}"
799
800 print "# size of resolution tables"
801 print "\ttotal \tholes"
802 total = 0
803 holes = 0
804 for t, table in resolution_tables do
805 total += table.length
806 for e in table do if e == null then holes += 1
807 end
808 print "\t{total}\t{holes}"
809
810 print "# size of methods tables"
811 print "\ttotal \tholes"
812 total = 0
813 holes = 0
814 for t, table in method_tables do
815 total += table.length
816 for e in table do if e == null then holes += 1
817 end
818 print "\t{total}\t{holes}"
819
820 print "# size of attributes tables"
821 print "\ttotal \tholes"
822 total = 0
823 holes = 0
824 for t, table in attr_tables do
825 total += table.length
826 for e in table do if e == null then holes += 1
827 end
828 print "\t{total}\t{holes}"
829 end
830 end
831
832 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
833 class SeparateCompilerVisitor
834 super AbstractCompilerVisitor
835
836 redef type COMPILER: SeparateCompiler
837
838 redef fun adapt_signature(m, args)
839 do
840 var msignature = m.msignature.resolve_for(m.mclassdef.bound_mtype, m.mclassdef.bound_mtype, m.mclassdef.mmodule, true)
841 var recv = args.first
842 if recv.mtype.ctype != m.mclassdef.mclass.mclass_type.ctype then
843 args.first = self.autobox(args.first, m.mclassdef.mclass.mclass_type)
844 end
845 for i in [0..msignature.arity[ do
846 var t = msignature.mparameters[i].mtype
847 if i == msignature.vararg_rank then
848 t = args[i+1].mtype
849 end
850 args[i+1] = self.autobox(args[i+1], t)
851 end
852 end
853
854 redef fun autobox(value, mtype)
855 do
856 if value.mtype == mtype then
857 return value
858 else if value.mtype.ctype == "val*" and mtype.ctype == "val*" then
859 return value
860 else if value.mtype.ctype == "val*" then
861 return self.new_expr("((struct instance_{mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype)
862 else if mtype.ctype == "val*" then
863 var valtype = value.mtype.as(MClassType)
864 var res = self.new_var(mtype)
865 if not compiler.runtime_type_analysis.live_types.has(valtype) then
866 self.add("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
867 self.add("printf(\"Dead code executed!\\n\"); exit(1);")
868 return res
869 end
870 self.add("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
871 return res
872 else
873 # Bad things will appen!
874 var res = self.new_var(mtype)
875 self.add("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
876 self.add("printf(\"Cast error: Cannot cast %s to %s.\\n\", \"{value.mtype}\", \"{mtype}\"); exit(1);")
877 return res
878 end
879 end
880
881 # Return a C expression returning the runtime type structure of the value
882 # The point of the method is to works also with primitives types.
883 fun type_info(value: RuntimeVariable): String
884 do
885 if value.mtype.ctype == "val*" then
886 return "{value}->type"
887 else
888 self.require_declaration("type_{value.mtype.c_name}")
889 return "(&type_{value.mtype.c_name})"
890 end
891 end
892
893 redef fun send(mmethod, arguments)
894 do
895 if arguments.first.mcasttype.ctype != "val*" then
896 # In order to shortcut the primitive, we need to find the most specific method
897 # Howverr, because of performance (no flattening), we always work on the realmainmodule
898 var m = self.compiler.mainmodule
899 self.compiler.mainmodule = self.compiler.realmainmodule
900 var res = self.monomorphic_send(mmethod, arguments.first.mcasttype, arguments)
901 self.compiler.mainmodule = m
902 return res
903 end
904
905 var res: nullable RuntimeVariable
906 var msignature = mmethod.intro.msignature.resolve_for(mmethod.intro.mclassdef.bound_mtype, mmethod.intro.mclassdef.bound_mtype, mmethod.intro.mclassdef.mmodule, true)
907 var ret = msignature.return_mtype
908 if mmethod.is_new then
909 ret = arguments.first.mtype
910 res = self.new_var(ret)
911 else if ret == null then
912 res = null
913 else
914 res = self.new_var(ret)
915 end
916
917 var s = new Buffer
918 var ss = new Buffer
919
920 var recv = arguments.first
921 s.append("val*")
922 ss.append("{recv}")
923 self.varargize(mmethod.intro, mmethod.intro.msignature.as(not null), arguments)
924 for i in [0..msignature.arity[ do
925 var a = arguments[i+1]
926 var t = msignature.mparameters[i].mtype
927 if i == msignature.vararg_rank then
928 t = arguments[i+1].mcasttype
929 end
930 s.append(", {t.ctype}")
931 a = self.autobox(a, t)
932 ss.append(", {a}")
933 end
934
935 var consider_null = not self.compiler.modelbuilder.toolcontext.opt_no_check_other.value or mmethod.name == "==" or mmethod.name == "!="
936 var maybenull = recv.mcasttype isa MNullableType and consider_null
937 if maybenull then
938 self.add("if ({recv} == NULL) \{")
939 if mmethod.name == "==" then
940 assert res != null
941 var arg = arguments[1]
942 if arg.mcasttype isa MNullableType then
943 self.add("{res} = ({arg} == NULL);")
944 else if arg.mcasttype isa MNullType then
945 self.add("{res} = 1; /* is null */")
946 else
947 self.add("{res} = 0; /* {arg.inspect} cannot be null */")
948 end
949 else if mmethod.name == "!=" then
950 assert res != null
951 var arg = arguments[1]
952 if arg.mcasttype isa MNullableType then
953 self.add("{res} = ({arg} != NULL);")
954 else if arg.mcasttype isa MNullType then
955 self.add("{res} = 0; /* is null */")
956 else
957 self.add("{res} = 1; /* {arg.inspect} cannot be null */")
958 end
959 else
960 self.add_abort("Reciever is null")
961 end
962 self.add("\} else \{")
963 end
964 if not self.compiler.modelbuilder.toolcontext.opt_no_shortcut_equate.value and (mmethod.name == "==" or mmethod.name == "!=") then
965 assert res != null
966 # Recv is not null, thus is arg is, it is easy to conclude (and respect the invariants)
967 var arg = arguments[1]
968 if arg.mcasttype isa MNullType then
969 if mmethod.name == "==" then
970 self.add("{res} = 0; /* arg is null but recv is not */")
971 else
972 self.add("{res} = 1; /* arg is null and recv is not */")
973 end
974 if maybenull then
975 self.add("\}")
976 end
977 return res
978 end
979 end
980
981 var r
982 if ret == null then r = "void" else r = ret.ctype
983 self.require_declaration(mmethod.const_color)
984 var call = "(({r} (*)({s}))({arguments.first}->class->vft[{mmethod.const_color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
985
986 if res != null then
987 self.add("{res} = {call};")
988 else
989 self.add("{call};")
990 end
991
992 if maybenull then
993 self.add("\}")
994 end
995
996 return res
997 end
998
999 redef fun call(mmethoddef, recvtype, arguments)
1000 do
1001 var res: nullable RuntimeVariable
1002 var ret = mmethoddef.msignature.return_mtype
1003 if mmethoddef.mproperty.is_new then
1004 ret = arguments.first.mtype
1005 res = self.new_var(ret)
1006 else if ret == null then
1007 res = null
1008 else
1009 ret = ret.resolve_for(mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.mmodule, true)
1010 res = self.new_var(ret)
1011 end
1012
1013 if self.compiler.modelbuilder.mpropdef2npropdef.has_key(mmethoddef) and
1014 self.compiler.modelbuilder.mpropdef2npropdef[mmethoddef] isa AInternMethPropdef and
1015 not compiler.modelbuilder.toolcontext.opt_no_inline_intern.value then
1016 var frame = new Frame(self, mmethoddef, recvtype, arguments)
1017 frame.returnlabel = self.get_name("RET_LABEL")
1018 frame.returnvar = res
1019 var old_frame = self.frame
1020 self.frame = frame
1021 self.add("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
1022 mmethoddef.compile_inside_to_c(self, arguments)
1023 self.add("{frame.returnlabel.as(not null)}:(void)0;")
1024 self.add("\}")
1025 self.frame = old_frame
1026 return res
1027 end
1028
1029 # Autobox arguments
1030 self.adapt_signature(mmethoddef, arguments)
1031
1032 self.require_declaration(mmethoddef.c_name)
1033 if res == null then
1034 self.add("{mmethoddef.c_name}({arguments.join(", ")});")
1035 return null
1036 else
1037 self.add("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
1038 end
1039
1040 return res
1041 end
1042
1043 redef fun supercall(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
1044 do
1045 # FIXME implements a polymorphic access in tables
1046 m = m.lookup_next_definition(m.mclassdef.mmodule, m.mclassdef.bound_mtype)
1047 return self.call(m, recvtype, args)
1048 end
1049
1050 redef fun vararg_instance(mpropdef, recv, varargs, elttype)
1051 do
1052 # A vararg must be stored into an new array
1053 # The trick is that the dymaic type of the array may depends on the receiver
1054 # of the method (ie recv) if the static type is unresolved
1055 # This is more complex than usual because the unresolved type must not be resolved
1056 # with the current receiver (ie self).
1057 # Therefore to isolate the resolution from self, a local Frame is created.
1058 # One can see this implementation as an inlined method of the receiver whose only
1059 # job is to allocate the array
1060 var old_frame = self.frame
1061 var frame = new Frame(self, mpropdef, mpropdef.mclassdef.bound_mtype, [recv])
1062 self.frame = frame
1063 #print "required Array[{elttype}] for recv {recv.inspect}. bound=Array[{self.resolve_for(elttype, recv)}]. selfvar={frame.arguments.first.inspect}"
1064 var res = self.array_instance(varargs, elttype)
1065 self.frame = old_frame
1066 return res
1067 end
1068
1069 redef fun isset_attribute(a, recv)
1070 do
1071 self.check_recv_notnull(recv)
1072 var res = self.new_var(bool_type)
1073
1074 # What is the declared type of the attribute?
1075 var mtype = a.intro.static_mtype.as(not null)
1076 var intromclassdef = a.intro.mclassdef
1077 mtype = mtype.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
1078
1079 if mtype isa MNullableType then
1080 self.add("{res} = 1; /* easy isset: {a} on {recv.inspect} */")
1081 return res
1082 end
1083
1084 self.require_declaration(a.const_color)
1085 if self.compiler.modelbuilder.toolcontext.opt_no_union_attribute.value then
1086 self.add("{res} = {recv}->attrs[{a.const_color}] != NULL; /* {a} on {recv.inspect}*/")
1087 else
1088
1089 if mtype.ctype == "val*" then
1090 self.add("{res} = {recv}->attrs[{a.const_color}].val != NULL; /* {a} on {recv.inspect} */")
1091 else
1092 self.add("{res} = 1; /* NOT YET IMPLEMENTED: isset of primitives: {a} on {recv.inspect} */")
1093 end
1094 end
1095 return res
1096 end
1097
1098 redef fun read_attribute(a, recv)
1099 do
1100 self.check_recv_notnull(recv)
1101
1102 # What is the declared type of the attribute?
1103 var ret = a.intro.static_mtype.as(not null)
1104 var intromclassdef = a.intro.mclassdef
1105 ret = ret.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
1106
1107 self.require_declaration(a.const_color)
1108 if self.compiler.modelbuilder.toolcontext.opt_no_union_attribute.value then
1109 # Get the attribute or a box (ie. always a val*)
1110 var cret = self.object_type.as_nullable
1111 var res = self.new_var(cret)
1112 res.mcasttype = ret
1113
1114 self.add("{res} = {recv}->attrs[{a.const_color}]; /* {a} on {recv.inspect} */")
1115
1116 # Check for Uninitialized attribute
1117 if not ret isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_initialization.value then
1118 self.add("if ({res} == NULL) \{")
1119 self.add_abort("Uninitialized attribute {a.name}")
1120 self.add("\}")
1121 end
1122
1123 # Return the attribute or its unboxed version
1124 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
1125 return self.autobox(res, ret)
1126 else
1127 var res = self.new_var(ret)
1128 self.add("{res} = {recv}->attrs[{a.const_color}].{ret.ctypename}; /* {a} on {recv.inspect} */")
1129
1130 # Check for Uninitialized attribute
1131 if ret.ctype == "val*" and not ret isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_initialization.value then
1132 self.add("if ({res} == NULL) \{")
1133 self.add_abort("Uninitialized attribute {a.name}")
1134 self.add("\}")
1135 end
1136
1137 return res
1138 end
1139 end
1140
1141 redef fun write_attribute(a, recv, value)
1142 do
1143 self.check_recv_notnull(recv)
1144
1145 # What is the declared type of the attribute?
1146 var mtype = a.intro.static_mtype.as(not null)
1147 var intromclassdef = a.intro.mclassdef
1148 mtype = mtype.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
1149
1150 # Adapt the value to the declared type
1151 value = self.autobox(value, mtype)
1152
1153 self.require_declaration(a.const_color)
1154 if self.compiler.modelbuilder.toolcontext.opt_no_union_attribute.value then
1155 var attr = "{recv}->attrs[{a.const_color}]"
1156 if mtype.ctype != "val*" then
1157 assert mtype isa MClassType
1158 # The attribute is primitive, thus we store it in a box
1159 # The trick is to create the box the first time then resuse the box
1160 self.add("if ({attr} != NULL) \{")
1161 self.add("((struct instance_{mtype.c_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
1162 self.add("\} else \{")
1163 value = self.autobox(value, self.object_type.as_nullable)
1164 self.add("{attr} = {value}; /* {a} on {recv.inspect} */")
1165 self.add("\}")
1166 else
1167 # The attribute is not primitive, thus store it direclty
1168 self.add("{attr} = {value}; /* {a} on {recv.inspect} */")
1169 end
1170 else
1171 self.add("{recv}->attrs[{a.const_color}].{mtype.ctypename} = {value}; /* {a} on {recv.inspect} */")
1172 end
1173 end
1174
1175 redef fun init_instance(mtype)
1176 do
1177 self.require_declaration("NEW_{mtype.mclass.c_name}")
1178 var compiler = self.compiler
1179 if mtype isa MGenericType and mtype.need_anchor then
1180 link_unresolved_type(self.frame.mpropdef.mclassdef, mtype)
1181 var recv = self.frame.arguments.first
1182 var recv_type_info = self.type_info(recv)
1183 self.require_declaration(mtype.const_color)
1184 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
1185 return self.new_expr("NEW_{mtype.mclass.c_name}({recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})])", mtype)
1186 else
1187 return self.new_expr("NEW_{mtype.mclass.c_name}({recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype)
1188 end
1189 end
1190 compiler.undead_types.add(mtype)
1191 self.require_declaration("type_{mtype.c_name}")
1192 return self.new_expr("NEW_{mtype.mclass.c_name}(&type_{mtype.c_name})", mtype)
1193 end
1194
1195 redef fun check_init_instance(value, mtype)
1196 do
1197 if self.compiler.modelbuilder.toolcontext.opt_no_check_initialization.value then return
1198 self.require_declaration("CHECK_NEW_{mtype.mclass.c_name}")
1199 self.add("CHECK_NEW_{mtype.mclass.c_name}({value});")
1200 end
1201
1202 redef fun type_test(value, mtype, tag)
1203 do
1204 self.add("/* {value.inspect} isa {mtype} */")
1205 var compiler = self.compiler
1206
1207 var recv = self.frame.arguments.first
1208 var recv_type_info = self.type_info(recv)
1209
1210 var res = self.new_var(bool_type)
1211
1212 var cltype = self.get_name("cltype")
1213 self.add_decl("int {cltype};")
1214 var idtype = self.get_name("idtype")
1215 self.add_decl("int {idtype};")
1216
1217 var maybe_null = self.maybe_null(value)
1218 var accept_null = "0"
1219 var ntype = mtype
1220 if ntype isa MNullableType then
1221 ntype = ntype.mtype
1222 accept_null = "1"
1223 end
1224
1225 if value.mcasttype.is_subtype(self.frame.mpropdef.mclassdef.mmodule, self.frame.mpropdef.mclassdef.bound_mtype, mtype) then
1226 self.add("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
1227 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
1228 self.compiler.count_type_test_skipped[tag] += 1
1229 self.add("count_type_test_skipped_{tag}++;")
1230 end
1231 return res
1232 end
1233
1234 if ntype.need_anchor then
1235 var type_struct = self.get_name("type_struct")
1236 self.add_decl("const struct type* {type_struct};")
1237
1238 # Either with resolution_table with a direct resolution
1239 link_unresolved_type(self.frame.mpropdef.mclassdef, ntype)
1240 self.require_declaration(ntype.const_color)
1241 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
1242 self.add("{type_struct} = {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {ntype.const_color})];")
1243 else
1244 self.add("{type_struct} = {recv_type_info}->resolution_table->types[{ntype.const_color}];")
1245 end
1246 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
1247 self.compiler.count_type_test_unresolved[tag] += 1
1248 self.add("count_type_test_unresolved_{tag}++;")
1249 end
1250 self.add("{cltype} = {type_struct}->color;")
1251 self.add("{idtype} = {type_struct}->id;")
1252 if maybe_null and accept_null == "0" then
1253 var is_nullable = self.get_name("is_nullable")
1254 self.add_decl("short int {is_nullable};")
1255 self.add("{is_nullable} = {type_struct}->is_nullable;")
1256 accept_null = is_nullable.to_s
1257 end
1258 else if ntype isa MClassType then
1259 compiler.undead_types.add(mtype)
1260 self.require_declaration("type_{mtype.c_name}")
1261 self.add("{cltype} = type_{mtype.c_name}.color;")
1262 self.add("{idtype} = type_{mtype.c_name}.id;")
1263 if compiler.modelbuilder.toolcontext.opt_typing_test_metrics.value then
1264 self.compiler.count_type_test_resolved[tag] += 1
1265 self.add("count_type_test_resolved_{tag}++;")
1266 end
1267 else
1268 self.add("printf(\"NOT YET IMPLEMENTED: type_test(%s, {mtype}).\\n\", \"{value.inspect}\"); exit(1);")
1269 end
1270
1271 # check color is in table
1272 if maybe_null then
1273 self.add("if({value} == NULL) \{")
1274 self.add("{res} = {accept_null};")
1275 self.add("\} else \{")
1276 end
1277 var value_type_info = self.type_info(value)
1278 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
1279 self.add("{cltype} = HASH({value_type_info}->color, {idtype});")
1280 end
1281 self.add("if({cltype} >= {value_type_info}->table_size) \{")
1282 self.add("{res} = 0;")
1283 self.add("\} else \{")
1284 self.add("{res} = {value_type_info}->type_table[{cltype}] == {idtype};")
1285 self.add("\}")
1286 if maybe_null then
1287 self.add("\}")
1288 end
1289
1290 return res
1291 end
1292
1293 redef fun is_same_type_test(value1, value2)
1294 do
1295 var res = self.new_var(bool_type)
1296 # Swap values to be symetric
1297 if value2.mtype.ctype != "val*" and value1.mtype.ctype == "val*" then
1298 var tmp = value1
1299 value1 = value2
1300 value2 = tmp
1301 end
1302 if value1.mtype.ctype != "val*" then
1303 if value2.mtype == value1.mtype then
1304 self.add("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1305 else if value2.mtype.ctype != "val*" then
1306 self.add("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1307 else
1308 var mtype1 = value1.mtype.as(MClassType)
1309 self.require_declaration("class_{mtype1.c_name}")
1310 self.add("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name}); /* is_same_type_test */")
1311 end
1312 else
1313 self.add("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1314 end
1315 return res
1316 end
1317
1318 redef fun class_name_string(value)
1319 do
1320 var res = self.get_name("var_class_name")
1321 self.add_decl("const char* {res};")
1322 if value.mtype.ctype == "val*" then
1323 self.add "{res} = {value} == NULL ? \"null\" : {value}->type->name;"
1324 else
1325 self.require_declaration("type_{value.mtype.c_name}")
1326 self.add "{res} = type_{value.mtype.c_name}.name;"
1327 end
1328 return res
1329 end
1330
1331 redef fun equal_test(value1, value2)
1332 do
1333 var res = self.new_var(bool_type)
1334 if value2.mtype.ctype != "val*" and value1.mtype.ctype == "val*" then
1335 var tmp = value1
1336 value1 = value2
1337 value2 = tmp
1338 end
1339 if value1.mtype.ctype != "val*" then
1340 if value2.mtype == value1.mtype then
1341 self.add("{res} = {value1} == {value2};")
1342 else if value2.mtype.ctype != "val*" then
1343 self.add("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1344 else
1345 var mtype1 = value1.mtype.as(MClassType)
1346 self.require_declaration("class_{mtype1.c_name}")
1347 self.add("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name});")
1348 self.add("if ({res}) \{")
1349 self.add("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1350 self.add("\}")
1351 end
1352 return res
1353 end
1354 var maybe_null = true
1355 var test = new Array[String]
1356 var t1 = value1.mcasttype
1357 if t1 isa MNullableType then
1358 test.add("{value1} != NULL")
1359 t1 = t1.mtype
1360 else
1361 maybe_null = false
1362 end
1363 var t2 = value2.mcasttype
1364 if t2 isa MNullableType then
1365 test.add("{value2} != NULL")
1366 t2 = t2.mtype
1367 else
1368 maybe_null = false
1369 end
1370
1371 var incompatible = false
1372 var primitive
1373 if t1.ctype != "val*" then
1374 primitive = t1
1375 if t1 == t2 then
1376 # No need to compare class
1377 else if t2.ctype != "val*" then
1378 incompatible = true
1379 else if can_be_primitive(value2) then
1380 test.add("{value1}->class == {value2}->class")
1381 else
1382 incompatible = true
1383 end
1384 else if t2.ctype != "val*" then
1385 primitive = t2
1386 if can_be_primitive(value1) then
1387 test.add("{value1}->class == {value2}->class")
1388 else
1389 incompatible = true
1390 end
1391 else
1392 primitive = null
1393 end
1394
1395 if incompatible then
1396 if maybe_null then
1397 self.add("{res} = {value1} == {value2}; /* incompatible types {t1} vs. {t2}; but may be NULL*/")
1398 return res
1399 else
1400 self.add("{res} = 0; /* incompatible types {t1} vs. {t2}; cannot be NULL */")
1401 return res
1402 end
1403 end
1404 if primitive != null then
1405 test.add("((struct instance_{primitive.c_name}*){value1})->value == ((struct instance_{primitive.c_name}*){value2})->value")
1406 else if can_be_primitive(value1) and can_be_primitive(value2) then
1407 test.add("{value1}->class == {value2}->class")
1408 var s = new Array[String]
1409 for t, v in self.compiler.box_kinds do
1410 s.add "({value1}->class->box_kind == {v} && ((struct instance_{t.c_name}*){value1})->value == ((struct instance_{t.c_name}*){value2})->value)"
1411 end
1412 test.add("({s.join(" || ")})")
1413 else
1414 self.add("{res} = {value1} == {value2};")
1415 return res
1416 end
1417 self.add("{res} = {value1} == {value2} || ({test.join(" && ")});")
1418 return res
1419 end
1420
1421 fun can_be_primitive(value: RuntimeVariable): Bool
1422 do
1423 var t = value.mcasttype
1424 if t isa MNullableType then t = t.mtype
1425 if not t isa MClassType then return false
1426 var k = t.mclass.kind
1427 return k == interface_kind or t.ctype != "val*"
1428 end
1429
1430 fun maybe_null(value: RuntimeVariable): Bool
1431 do
1432 var t = value.mcasttype
1433 return t isa MNullableType or t isa MNullType
1434 end
1435
1436 redef fun array_instance(array, elttype)
1437 do
1438 var nclass = self.get_class("NativeArray")
1439 var arrayclass = self.get_class("Array")
1440 var arraytype = arrayclass.get_mtype([elttype])
1441 var res = self.init_instance(arraytype)
1442 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
1443 var length = self.int_instance(array.length)
1444 var nat = native_array_instance(elttype, length)
1445 for i in [0..array.length[ do
1446 var r = self.autobox(array[i], self.object_type)
1447 self.add("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1448 end
1449 self.send(self.get_property("with_native", arrayclass.intro.bound_mtype), [res, nat, length])
1450 self.check_init_instance(res, arraytype)
1451 self.add("\}")
1452 return res
1453 end
1454
1455 fun native_array_instance(elttype: MType, length: RuntimeVariable): RuntimeVariable
1456 do
1457 var mtype = self.get_class("NativeArray").get_mtype([elttype])
1458 self.require_declaration("NEW_{mtype.mclass.c_name}")
1459 assert mtype isa MGenericType
1460 var compiler = self.compiler
1461 if mtype.need_anchor then
1462 link_unresolved_type(self.frame.mpropdef.mclassdef, mtype)
1463 var recv = self.frame.arguments.first
1464 var recv_type_info = self.type_info(recv)
1465 self.require_declaration(mtype.const_color)
1466 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
1467 return self.new_expr("NEW_{mtype.mclass.c_name}({length}, {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})])", mtype)
1468 else
1469 return self.new_expr("NEW_{mtype.mclass.c_name}({length}, {recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype)
1470 end
1471 end
1472 compiler.undead_types.add(mtype)
1473 self.require_declaration("type_{mtype.c_name}")
1474 return self.new_expr("NEW_{mtype.mclass.c_name}({length}, &type_{mtype.c_name})", mtype)
1475 end
1476
1477 redef fun native_array_def(pname, ret_type, arguments)
1478 do
1479 var elttype = arguments.first.mtype
1480 var nclass = self.get_class("NativeArray")
1481 var recv = "((struct instance_{nclass.c_name}*){arguments[0]})->values"
1482 if pname == "[]" then
1483 self.ret(self.new_expr("{recv}[{arguments[1]}]", ret_type.as(not null)))
1484 return
1485 else if pname == "[]=" then
1486 self.add("{recv}[{arguments[1]}]={arguments[2]};")
1487 return
1488 else if pname == "copy_to" then
1489 var recv1 = "((struct instance_{nclass.c_name}*){arguments[1]})->values"
1490 self.add("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1491 return
1492 end
1493 end
1494
1495 redef fun calloc_array(ret_type, arguments)
1496 do
1497 var mclass = self.get_class("ArrayCapable")
1498 var ft = mclass.mclass_type.arguments.first.as(MParameterType)
1499 var res = self.native_array_instance(ft, arguments[1])
1500 self.ret(res)
1501 end
1502
1503 fun link_unresolved_type(mclassdef: MClassDef, mtype: MType) do
1504 assert mtype.need_anchor
1505 var compiler = self.compiler
1506 if not compiler.live_unresolved_types.has_key(self.frame.mpropdef.mclassdef) then
1507 compiler.live_unresolved_types[self.frame.mpropdef.mclassdef] = new HashSet[MType]
1508 end
1509 compiler.live_unresolved_types[self.frame.mpropdef.mclassdef].add(mtype)
1510 end
1511 end
1512
1513 redef class MMethodDef
1514 fun separate_runtime_function: AbstractRuntimeFunction
1515 do
1516 var res = self.separate_runtime_function_cache
1517 if res == null then
1518 res = new SeparateRuntimeFunction(self)
1519 self.separate_runtime_function_cache = res
1520 end
1521 return res
1522 end
1523 private var separate_runtime_function_cache: nullable SeparateRuntimeFunction
1524
1525 fun virtual_runtime_function: AbstractRuntimeFunction
1526 do
1527 var res = self.virtual_runtime_function_cache
1528 if res == null then
1529 res = new VirtualRuntimeFunction(self)
1530 self.virtual_runtime_function_cache = res
1531 end
1532 return res
1533 end
1534 private var virtual_runtime_function_cache: nullable VirtualRuntimeFunction
1535 end
1536
1537 # The C function associated to a methoddef separately compiled
1538 class SeparateRuntimeFunction
1539 super AbstractRuntimeFunction
1540
1541 redef fun build_c_name: String do return "{mmethoddef.c_name}"
1542
1543 redef fun to_s do return self.mmethoddef.to_s
1544
1545 redef fun compile_to_c(compiler)
1546 do
1547 var mmethoddef = self.mmethoddef
1548
1549 var recv = self.mmethoddef.mclassdef.bound_mtype
1550 var v = compiler.new_visitor
1551 var selfvar = new RuntimeVariable("self", recv, recv)
1552 var arguments = new Array[RuntimeVariable]
1553 var frame = new Frame(v, mmethoddef, recv, arguments)
1554 v.frame = frame
1555
1556 var msignature = mmethoddef.msignature.resolve_for(mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.mmodule, true)
1557
1558 var sig = new Buffer
1559 var comment = new Buffer
1560 var ret = msignature.return_mtype
1561 if ret != null then
1562 sig.append("{ret.ctype} ")
1563 else if mmethoddef.mproperty.is_new then
1564 ret = recv
1565 sig.append("{ret.ctype} ")
1566 else
1567 sig.append("void ")
1568 end
1569 sig.append(self.c_name)
1570 sig.append("({selfvar.mtype.ctype} {selfvar}")
1571 comment.append("({selfvar}: {selfvar.mtype}")
1572 arguments.add(selfvar)
1573 for i in [0..msignature.arity[ do
1574 var mtype = msignature.mparameters[i].mtype
1575 if i == msignature.vararg_rank then
1576 mtype = v.get_class("Array").get_mtype([mtype])
1577 end
1578 comment.append(", {mtype}")
1579 sig.append(", {mtype.ctype} p{i}")
1580 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
1581 arguments.add(argvar)
1582 end
1583 sig.append(")")
1584 comment.append(")")
1585 if ret != null then
1586 comment.append(": {ret}")
1587 end
1588 compiler.provide_declaration(self.c_name, "{sig};")
1589
1590 v.add_decl("/* method {self} for {comment} */")
1591 v.add_decl("{sig} \{")
1592 if ret != null then
1593 frame.returnvar = v.new_var(ret)
1594 end
1595 frame.returnlabel = v.get_name("RET_LABEL")
1596
1597 if recv != arguments.first.mtype then
1598 #print "{self} {recv} {arguments.first}"
1599 end
1600 mmethoddef.compile_inside_to_c(v, arguments)
1601
1602 v.add("{frame.returnlabel.as(not null)}:;")
1603 if ret != null then
1604 v.add("return {frame.returnvar.as(not null)};")
1605 end
1606 v.add("\}")
1607 end
1608 end
1609
1610 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
1611 # The first parameter (the reciever) is always typed by val* in order to accept an object value
1612 class VirtualRuntimeFunction
1613 super AbstractRuntimeFunction
1614
1615 redef fun build_c_name: String do return "VIRTUAL_{mmethoddef.c_name}"
1616
1617 redef fun to_s do return self.mmethoddef.to_s
1618
1619 redef fun compile_to_c(compiler)
1620 do
1621 var mmethoddef = self.mmethoddef
1622
1623 var recv = self.mmethoddef.mclassdef.bound_mtype
1624 var v = compiler.new_visitor
1625 var selfvar = new RuntimeVariable("self", v.object_type, recv)
1626 var arguments = new Array[RuntimeVariable]
1627 var frame = new Frame(v, mmethoddef, recv, arguments)
1628 v.frame = frame
1629
1630 var sig = new Buffer
1631 var comment = new Buffer
1632
1633 # Because the function is virtual, the signature must match the one of the original class
1634 var intromclassdef = self.mmethoddef.mproperty.intro.mclassdef
1635 var msignature = mmethoddef.mproperty.intro.msignature.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
1636 var ret = msignature.return_mtype
1637 if ret != null then
1638 sig.append("{ret.ctype} ")
1639 else if mmethoddef.mproperty.is_new then
1640 ret = recv
1641 sig.append("{ret.ctype} ")
1642 else
1643 sig.append("void ")
1644 end
1645 sig.append(self.c_name)
1646 sig.append("({selfvar.mtype.ctype} {selfvar}")
1647 comment.append("({selfvar}: {selfvar.mtype}")
1648 arguments.add(selfvar)
1649 for i in [0..msignature.arity[ do
1650 var mtype = msignature.mparameters[i].mtype
1651 if i == msignature.vararg_rank then
1652 mtype = v.get_class("Array").get_mtype([mtype])
1653 end
1654 comment.append(", {mtype}")
1655 sig.append(", {mtype.ctype} p{i}")
1656 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
1657 arguments.add(argvar)
1658 end
1659 sig.append(")")
1660 comment.append(")")
1661 if ret != null then
1662 comment.append(": {ret}")
1663 end
1664 compiler.provide_declaration(self.c_name, "{sig};")
1665
1666 v.add_decl("/* method {self} for {comment} */")
1667 v.add_decl("{sig} \{")
1668 if ret != null then
1669 frame.returnvar = v.new_var(ret)
1670 end
1671 frame.returnlabel = v.get_name("RET_LABEL")
1672
1673 var subret = v.call(mmethoddef, recv, arguments)
1674 if ret != null then
1675 assert subret != null
1676 v.assign(frame.returnvar.as(not null), subret)
1677 end
1678
1679 v.add("{frame.returnlabel.as(not null)}:;")
1680 if ret != null then
1681 v.add("return {frame.returnvar.as(not null)};")
1682 end
1683 v.add("\}")
1684 end
1685
1686 # TODO ?
1687 redef fun call(v, arguments) do abort
1688 end
1689
1690 redef class MType
1691 fun const_color: String do return "COLOR_{c_name}"
1692 end
1693
1694 redef class MProperty
1695 fun const_color: String do return "COLOR_{c_name}"
1696 end