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