1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Separate compilation of a Nit program
16 module separate_compiler
18 import abstract_compiler
19 import layout_builders
20 import rapid_type_analysis
23 # Add separate compiler specific options
24 redef class ToolContext
26 var opt_separate
: OptionBool = new OptionBool("Use separate compilation", "--separate")
28 var opt_no_inline_intern
: OptionBool = new OptionBool("Do not inline call to intern methods", "--no-inline-intern")
29 # --no-union-attribute
30 var opt_no_union_attribute
: OptionBool = new OptionBool("Put primitive attibutes in a box instead of an union", "--no-union-attribute")
31 # --no-shortcut-equate
32 var opt_no_shortcut_equate
: OptionBool = new OptionBool("Always call == in a polymorphic way", "--no-shortcut-equal")
33 # --inline-coloring-numbers
34 var opt_inline_coloring_numbers
: OptionBool = new OptionBool("Inline colors and ids", "--inline-coloring-numbers")
35 # --use-naive-coloring
36 var opt_bm_typing
: OptionBool = new OptionBool("Colorize items incrementaly, used to simulate binary matrix typing", "--bm-typing")
37 # --use-mod-perfect-hashing
38 var opt_phmod_typing
: OptionBool = new OptionBool("Replace coloration by perfect hashing (with mod operator)", "--phmod-typing")
39 # --use-and-perfect-hashing
40 var opt_phand_typing
: OptionBool = new OptionBool("Replace coloration by perfect hashing (with and operator)", "--phand-typing")
42 var opt_tables_metrics
: OptionBool = new OptionBool("Enable static size measuring of tables used for vft, typing and resolution", "--tables-metrics")
47 self.option_context
.add_option
(self.opt_separate
)
48 self.option_context
.add_option
(self.opt_no_inline_intern
)
49 self.option_context
.add_option
(self.opt_no_union_attribute
)
50 self.option_context
.add_option
(self.opt_no_shortcut_equate
)
51 self.option_context
.add_option
(self.opt_inline_coloring_numbers
)
52 self.option_context
.add_option
(self.opt_bm_typing
)
53 self.option_context
.add_option
(self.opt_phmod_typing
)
54 self.option_context
.add_option
(self.opt_phand_typing
)
55 self.option_context
.add_option
(self.opt_tables_metrics
)
59 redef class ModelBuilder
60 fun run_separate_compiler
(mainmodule
: MModule, runtime_type_analysis
: nullable RapidTypeAnalysis)
63 self.toolcontext
.info
("*** GENERATING C ***", 1)
65 var compiler
= new SeparateCompiler(mainmodule
, self, runtime_type_analysis
)
66 compiler
.compile_header
68 # compile class structures
69 self.toolcontext
.info
("Property coloring", 2)
70 compiler
.new_file
("{mainmodule.name}.classes")
71 compiler
.do_property_coloring
72 for m
in mainmodule
.in_importation
.greaters
do
73 for mclass
in m
.intro_mclasses
do
74 if mclass
.kind
== abstract_kind
or mclass
.kind
== interface_kind
then continue
75 compiler
.compile_class_to_c
(mclass
)
79 # The main function of the C
80 compiler
.new_file
("{mainmodule.name}.main")
81 compiler
.compile_main_function
84 for m
in mainmodule
.in_importation
.greaters
do
85 self.toolcontext
.info
("Generate C for module {m}", 2)
86 compiler
.new_file
("{m.name}.sep")
87 compiler
.compile_module_to_c
(m
)
90 # compile live & cast type structures
91 self.toolcontext
.info
("Type coloring", 2)
92 compiler
.new_file
("{mainmodule.name}.types")
93 var mtypes
= compiler
.do_type_coloring
95 compiler
.compile_type_to_c
(t
)
97 # compile remaining types structures (useless but needed for the symbol resolution at link-time)
98 for t
in compiler
.undead_types
do
99 if mtypes
.has
(t
) then continue
100 compiler
.compile_type_to_c
(t
)
103 compiler
.display_stats
106 self.toolcontext
.info
("*** END GENERATING C: {time1-time0} ***", 2)
107 write_and_make
(compiler
)
111 # Singleton that store the knowledge about the separate compilation process
112 class SeparateCompiler
113 super AbstractCompiler
115 redef type VISITOR: SeparateCompilerVisitor
117 # The result of the RTA (used to know live types and methods)
118 var runtime_type_analysis
: nullable RapidTypeAnalysis
120 private var undead_types
: Set[MType] = new HashSet[MType]
121 private var live_unresolved_types
: Map[MClassDef, Set[MType]] = new HashMap[MClassDef, HashSet[MType]]
123 private var type_layout
: nullable Layout[MType]
124 private var resolution_layout
: nullable Layout[MType]
125 protected var method_layout
: nullable Layout[PropertyLayoutElement]
126 protected var attr_layout
: nullable Layout[MAttribute]
128 init(mainmodule
: MModule, mmbuilder
: ModelBuilder, runtime_type_analysis
: nullable RapidTypeAnalysis) do
129 super(mainmodule
, mmbuilder
)
130 var file
= new_file
("nit.common")
131 self.header
= new CodeWriter(file
)
132 self.runtime_type_analysis
= runtime_type_analysis
133 self.compile_box_kinds
136 redef fun compile_header_structs
do
137 self.header
.add_decl
("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
138 self.compile_header_attribute_structs
139 self.header
.add_decl
("struct class \{ int box_kind; nitmethod_t vft[]; \}; /* general C type representing a Nit class. */")
141 # With resolution_table_table, all live type resolution are stored in a big table: resolution_table
142 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. */")
143 self.header
.add_decl
("struct instance \{ const struct type *type; const struct class *class; nitattribute_t attrs[]; \}; /* general C type representing a Nit instance. */")
145 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
or modelbuilder
.toolcontext
.opt_phand_typing
.value
then
146 self.header
.add_decl
("struct types \{ int mask; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
148 self.header
.add_decl
("struct types \{ int dummy; const struct type *types[]; \}; /* a list types (used for vts, fts and unresolved lists). */")
151 if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
152 self.header
.add_decl
("#define HASH(mask, id) ((mask)%(id))")
153 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
154 self.header
.add_decl
("#define HASH(mask, id) ((mask)&(id))")
157 self.header
.add_decl
("typedef struct instance val; /* general C type representing a Nit instance. */")
160 fun compile_header_attribute_structs
162 if modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
163 self.header
.add_decl
("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
165 self.header
.add_decl
("typedef union \{")
166 self.header
.add_decl
("void* val;")
167 for c
, v
in self.box_kinds
do
168 var t
= c
.mclass_type
169 self.header
.add_decl
("{t.ctype} {t.ctypename};")
171 self.header
.add_decl
("\} nitattribute_t; /* general C type representing a Nit attribute. */")
175 fun compile_box_kinds
177 # Collect all bas box class
178 # FIXME: this is not completely fine with a separate compilation scheme
179 for classname
in ["Int", "Bool", "Char", "Float", "NativeString", "Pointer"] do
180 var classes
= self.mainmodule
.model
.get_mclasses_by_name
(classname
)
181 if classes
== null then continue
182 assert classes
.length
== 1 else print classes
.join
(", ")
183 self.box_kinds
[classes
.first
] = self.box_kinds
.length
+ 1
187 var box_kinds
= new HashMap[MClass, Int]
189 fun box_kind_of
(mclass
: MClass): Int
191 if mclass
.mclass_type
.ctype
== "val*" then
193 else if mclass
.kind
== extern_kind
then
194 return self.box_kinds
[self.mainmodule
.get_primitive_class
("Pointer")]
196 return self.box_kinds
[mclass
]
201 fun compile_color_consts
(colors
: Map[Object, Int]) do
203 for m
, c
in colors
do
204 compile_color_const
(v
, m
, c
)
208 fun compile_color_const
(v
: SeparateCompilerVisitor, m
: Object, color
: Int) do
209 if color_consts_done
.has
(m
) then return
210 if m
isa MProperty then
211 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
212 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {color}")
214 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
215 v
.add
("const int {m.const_color} = {color};")
217 else if m
isa MPropDef then
218 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
219 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {color}")
221 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
222 v
.add
("const int {m.const_color} = {color};")
224 else if m
isa MType then
225 if modelbuilder
.toolcontext
.opt_inline_coloring_numbers
.value
then
226 self.provide_declaration
(m
.const_color
, "#define {m.const_color} {color}")
228 self.provide_declaration
(m
.const_color
, "extern const int {m.const_color};")
229 v
.add
("const int {m.const_color} = {color};")
232 color_consts_done
.add
(m
)
235 private var color_consts_done
= new HashSet[Object]
237 # colorize classe properties
238 fun do_property_coloring
do
239 var mclasses
= new HashSet[MClass].from
(modelbuilder
.model
.mclasses
)
242 var method_layout_builder
: PropertyLayoutBuilder[PropertyLayoutElement]
243 var attribute_layout_builder
: PropertyLayoutBuilder[MAttribute]
244 #FIXME PH and BM layouts too slow for large programs
245 #if modelbuilder.toolcontext.opt_bm_typing.value then
246 # method_layout_builder = new MMethodBMizer(self.mainmodule)
247 # attribute_layout_builder = new MAttributeBMizer(self.mainmodule)
248 #else if modelbuilder.toolcontext.opt_phmod_typing.value then
249 # method_layout_builder = new MMethodHasher(new PHModOperator, self.mainmodule)
250 # attribute_layout_builder = new MAttributeHasher(new PHModOperator, self.mainmodule)
251 #else if modelbuilder.toolcontext.opt_phand_typing.value then
252 # method_layout_builder = new MMethodHasher(new PHAndOperator, self.mainmodule)
253 # attribute_layout_builder = new MAttributeHasher(new PHAndOperator, self.mainmodule)
256 var class_layout_builder
= new MClassColorer(self.mainmodule
)
257 class_layout_builder
.build_layout
(mclasses
)
258 method_layout_builder
= new MPropertyColorer[PropertyLayoutElement](self.mainmodule
, class_layout_builder
)
259 attribute_layout_builder
= new MPropertyColorer[MAttribute](self.mainmodule
, class_layout_builder
)
262 # lookup properties to build layout with
263 var mmethods
= new HashMap[MClass, Set[PropertyLayoutElement]]
264 var mattributes
= new HashMap[MClass, Set[MAttribute]]
265 for mclass
in mclasses
do
266 mmethods
[mclass
] = new HashSet[PropertyLayoutElement]
267 mattributes
[mclass
] = new HashSet[MAttribute]
268 for mprop
in self.mainmodule
.properties
(mclass
) do
269 if mprop
isa MMethod then
270 mmethods
[mclass
].add
(mprop
)
271 else if mprop
isa MAttribute then
272 mattributes
[mclass
].add
(mprop
)
277 # Collect all super calls (dead or not)
278 var all_super_calls
= new HashSet[MMethodDef]
279 for mmodule
in self.mainmodule
.in_importation
.greaters
do
280 for mclassdef
in mmodule
.mclassdefs
do
281 for mpropdef
in mclassdef
.mpropdefs
do
282 if not mpropdef
isa MMethodDef then continue
283 if mpropdef
.has_supercall
then
284 all_super_calls
.add
(mpropdef
)
290 # lookup super calls and add it to the list of mmethods to build layout with
292 if runtime_type_analysis
!= null then
293 super_calls
= runtime_type_analysis
.live_super_sends
295 super_calls
= all_super_calls
298 for mmethoddef
in super_calls
do
299 var mclass
= mmethoddef
.mclassdef
.mclass
300 mmethods
[mclass
].add
(mmethoddef
)
301 for descendant
in mclass
.in_hierarchy
(self.mainmodule
).smallers
do
302 mmethods
[descendant
].add
(mmethoddef
)
307 self.method_layout
= method_layout_builder
.build_layout
(mmethods
)
308 self.method_tables
= build_method_tables
(mclasses
, super_calls
)
309 self.compile_color_consts
(method_layout
.pos
)
311 # attribute null color to dead supercalls
312 for mpropdef
in all_super_calls
do
313 if super_calls
.has
(mpropdef
) then continue
314 compile_color_const
(new_visitor
, mpropdef
, -1)
317 # attributes coloration
318 self.attr_layout
= attribute_layout_builder
.build_layout
(mattributes
)
319 self.attr_tables
= build_attr_tables
(mclasses
)
320 self.compile_color_consts
(attr_layout
.pos
)
323 fun build_method_tables
(mclasses
: Set[MClass], super_calls
: Set[MMethodDef]): Map[MClass, Array[nullable MPropDef]] do
324 var layout
= self.method_layout
325 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
326 for mclass
in mclasses
do
327 var table
= new Array[nullable MPropDef]
328 var supercalls
= new List[MMethodDef]
330 # first, fill table from parents by reverse linearization order
331 var parents
= new Array[MClass]
332 if mainmodule
.flatten_mclass_hierarchy
.has
(mclass
) then
333 parents
= mclass
.in_hierarchy
(mainmodule
).greaters
.to_a
334 self.mainmodule
.linearize_mclasses
(parents
)
337 for parent
in parents
do
338 if parent
== mclass
then continue
339 for mproperty
in self.mainmodule
.properties
(parent
) do
340 if not mproperty
isa MMethod then continue
341 var color
= layout
.pos
[mproperty
]
342 if table
.length
<= color
then
343 for i
in [table
.length
.. color
[ do
347 for mpropdef
in mproperty
.mpropdefs
do
348 if mpropdef
.mclassdef
.mclass
== parent
then
349 table
[color
] = mpropdef
354 # lookup for super calls in super classes
355 for mmethoddef
in super_calls
do
356 for mclassdef
in parent
.mclassdefs
do
357 if mclassdef
.mpropdefs
.has
(mmethoddef
) then
358 supercalls
.add
(mmethoddef
)
364 # then override with local properties
365 for mproperty
in self.mainmodule
.properties
(mclass
) do
366 if not mproperty
isa MMethod then continue
367 var color
= layout
.pos
[mproperty
]
368 if table
.length
<= color
then
369 for i
in [table
.length
.. color
[ do
373 for mpropdef
in mproperty
.mpropdefs
do
374 if mpropdef
.mclassdef
.mclass
== mclass
then
375 table
[color
] = mpropdef
380 # lookup for super calls in local class
381 for mmethoddef
in super_calls
do
382 for mclassdef
in mclass
.mclassdefs
do
383 if mclassdef
.mpropdefs
.has
(mmethoddef
) then
384 supercalls
.add
(mmethoddef
)
388 # insert super calls in table according to receiver
389 for supercall
in supercalls
do
390 var color
= layout
.pos
[supercall
]
391 if table
.length
<= color
then
392 for i
in [table
.length
.. color
[ do
396 var mmethoddef
= supercall
.lookup_next_definition
(self.mainmodule
, mclass
.intro
.bound_mtype
)
397 table
[color
] = mmethoddef
399 tables
[mclass
] = table
404 fun build_attr_tables
(mclasses
: Set[MClass]): Map[MClass, Array[nullable MPropDef]] do
405 var layout
= self.attr_layout
406 var tables
= new HashMap[MClass, Array[nullable MPropDef]]
407 for mclass
in mclasses
do
408 var table
= new Array[nullable MPropDef]
409 # first, fill table from parents by reverse linearization order
410 var parents
= new Array[MClass]
411 if mainmodule
.flatten_mclass_hierarchy
.has
(mclass
) then
412 parents
= mclass
.in_hierarchy
(mainmodule
).greaters
.to_a
413 self.mainmodule
.linearize_mclasses
(parents
)
415 for parent
in parents
do
416 if parent
== mclass
then continue
417 for mproperty
in self.mainmodule
.properties
(parent
) do
418 if not mproperty
isa MAttribute then continue
419 var color
= layout
.pos
[mproperty
]
420 if table
.length
<= color
then
421 for i
in [table
.length
.. color
[ do
425 for mpropdef
in mproperty
.mpropdefs
do
426 if mpropdef
.mclassdef
.mclass
== parent
then
427 table
[color
] = mpropdef
433 # then override with local properties
434 for mproperty
in self.mainmodule
.properties
(mclass
) do
435 if not mproperty
isa MAttribute then continue
436 var color
= layout
.pos
[mproperty
]
437 if table
.length
<= color
then
438 for i
in [table
.length
.. color
[ do
442 for mpropdef
in mproperty
.mpropdefs
do
443 if mpropdef
.mclassdef
.mclass
== mclass
then
444 table
[color
] = mpropdef
448 tables
[mclass
] = table
453 # colorize live types of the program
454 private fun do_type_coloring
: POSet[MType] do
455 var mtypes
= new HashSet[MType]
456 mtypes
.add_all
(self.runtime_type_analysis
.live_types
)
457 mtypes
.add_all
(self.runtime_type_analysis
.live_cast_types
)
458 for c
in self.box_kinds
.keys
do
459 mtypes
.add
(c
.mclass_type
)
463 var layout_builder
: TypingLayoutBuilder[MType]
464 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
465 layout_builder
= new MTypeBMizer(self.mainmodule
)
466 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
467 layout_builder
= new MTypeHasher(new PHModOperator, self.mainmodule
)
468 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
469 layout_builder
= new MTypeHasher(new PHAndOperator, self.mainmodule
)
471 layout_builder
= new MTypeColorer(self.mainmodule
)
475 self.type_layout
= layout_builder
.build_layout
(mtypes
)
476 var poset
= layout_builder
.poset
.as(not null)
477 self.type_tables
= self.build_type_tables
(poset
)
479 # VT and FT are stored with other unresolved types in the big resolution_tables
480 self.compile_resolution_tables
(mtypes
)
486 fun build_type_tables
(mtypes
: POSet[MType]): Map[MType, Array[nullable MType]] do
487 var tables
= new HashMap[MType, Array[nullable MType]]
488 var layout
= self.type_layout
489 for mtype
in mtypes
do
490 var table
= new Array[nullable MType]
491 for sup
in mtypes
[mtype
].greaters
do
493 if layout
isa PHLayout[MType, MType] then
494 color
= layout
.hashes
[mtype
][sup
]
496 color
= layout
.pos
[sup
]
498 if table
.length
<= color
then
499 for i
in [table
.length
.. color
[ do
505 tables
[mtype
] = table
510 protected fun compile_resolution_tables
(mtypes
: Set[MType]) do
511 # resolution_tables is used to perform a type resolution at runtime in O(1)
513 # During the visit of the body of classes, live_unresolved_types are collected
515 # Collect all live_unresolved_types (visited in the body of classes)
517 # Determinate fo each livetype what are its possible requested anchored types
518 var mtype2unresolved
= new HashMap[MClassType, Set[MType]]
519 for mtype
in self.runtime_type_analysis
.live_types
do
520 var set
= new HashSet[MType]
521 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
522 if self.live_unresolved_types
.has_key
(cd
) then
523 set
.add_all
(self.live_unresolved_types
[cd
])
526 mtype2unresolved
[mtype
] = set
529 # Compute the table layout with the prefered method
530 var resolution_builder
: ResolutionLayoutBuilder
531 if modelbuilder
.toolcontext
.opt_bm_typing
.value
then
532 resolution_builder
= new ResolutionBMizer
533 else if modelbuilder
.toolcontext
.opt_phmod_typing
.value
then
534 resolution_builder
= new ResolutionHasher(new PHModOperator)
535 else if modelbuilder
.toolcontext
.opt_phand_typing
.value
then
536 resolution_builder
= new ResolutionHasher(new PHAndOperator)
538 resolution_builder
= new ResolutionColorer
540 self.resolution_layout
= resolution_builder
.build_layout
(mtype2unresolved
)
541 self.resolution_tables
= self.build_resolution_tables
(mtype2unresolved
)
543 # Compile a C constant for each collected unresolved type.
544 # Either to a color, or to -1 if the unresolved type is dead (no live receiver can require it)
545 var all_unresolved
= new HashSet[MType]
546 for t
in self.live_unresolved_types
.values
do
547 all_unresolved
.add_all
(t
)
549 var all_unresolved_types_colors
= new HashMap[MType, Int]
550 for t
in all_unresolved
do
551 if self.resolution_layout
.pos
.has_key
(t
) then
552 all_unresolved_types_colors
[t
] = self.resolution_layout
.pos
[t
]
554 all_unresolved_types_colors
[t
] = -1
557 self.compile_color_consts
(all_unresolved_types_colors
)
560 #for k, v in unresolved_types_tables.as(not null) do
561 # print "{k}: {v.join(", ")}"
566 fun build_resolution_tables
(elements
: Map[MClassType, Set[MType]]): Map[MClassType, Array[nullable MType]] do
567 var tables
= new HashMap[MClassType, Array[nullable MType]]
568 var layout
= self.resolution_layout
569 for mclasstype
, mtypes
in elements
do
570 var table
= new Array[nullable MType]
571 for mtype
in mtypes
do
573 if layout
isa PHLayout[MClassType, MType] then
574 color
= layout
.hashes
[mclasstype
][mtype
]
576 color
= layout
.pos
[mtype
]
578 if table
.length
<= color
then
579 for i
in [table
.length
.. color
[ do
585 tables
[mclasstype
] = table
590 # Separately compile all the method definitions of the module
591 fun compile_module_to_c
(mmodule
: MModule)
593 var old_module
= self.mainmodule
594 self.mainmodule
= mmodule
595 for cd
in mmodule
.mclassdefs
do
596 for pd
in cd
.mpropdefs
do
597 if not pd
isa MMethodDef then continue
598 #print "compile {pd} @ {cd} @ {mmodule}"
599 var r
= pd
.separate_runtime_function
601 var r2
= pd
.virtual_runtime_function
602 r2
.compile_to_c
(self)
605 self.mainmodule
= old_module
608 # Globaly compile the type structure of a live type
609 fun compile_type_to_c
(mtype
: MType)
611 assert not mtype
.need_anchor
612 var layout
= self.type_layout
613 var is_live
= mtype
isa MClassType and runtime_type_analysis
.live_types
.has
(mtype
)
614 var is_cast_live
= runtime_type_analysis
.live_cast_types
.has
(mtype
)
615 var c_name
= mtype
.c_name
616 var v
= new SeparateCompilerVisitor(self)
617 v
.add_decl
("/* runtime type {mtype} */")
619 # extern const struct type_X
620 self.provide_declaration
("type_{c_name}", "extern const struct type type_{c_name};")
622 # const struct type_X
623 v
.add_decl
("const struct type type_{c_name} = \{")
625 # type id (for cast target)
627 v
.add_decl
("{layout.ids[mtype]},")
629 v
.add_decl
("-1, /*CAST DEAD*/")
633 v
.add_decl
("\"{mtype}\
", /* class_name_string */")
635 # type color (for cast target)
637 if layout
isa PHLayout[MType, MType] then
638 v
.add_decl
("{layout.masks[mtype]},")
640 v
.add_decl
("{layout.pos[mtype]},")
643 v
.add_decl
("-1, /*CAST DEAD*/")
647 if mtype
isa MNullableType then
653 # resolution table (for receiver)
655 var mclass_type
= mtype
656 if mclass_type
isa MNullableType then mclass_type
= mclass_type
.mtype
657 assert mclass_type
isa MClassType
658 if resolution_tables
[mclass_type
].is_empty
then
659 v
.add_decl
("NULL, /*NO RESOLUTIONS*/")
661 compile_type_resolution_table
(mtype
)
662 v
.require_declaration
("resolution_table_{c_name}")
663 v
.add_decl
("&resolution_table_{c_name},")
666 v
.add_decl
("NULL, /*DEAD*/")
669 # cast table (for receiver)
671 v
.add_decl
("{self.type_tables[mtype].length},")
673 for stype
in self.type_tables
[mtype
] do
674 if stype
== null then
675 v
.add_decl
("-1, /* empty */")
677 v
.add_decl
("{layout.ids[stype]}, /* {stype} */")
682 v
.add_decl
("0, \{\}, /*DEAD TYPE*/")
687 fun compile_type_resolution_table
(mtype
: MType) do
689 var mclass_type
: MClassType
690 if mtype
isa MNullableType then
691 mclass_type
= mtype
.mtype
.as(MClassType)
693 mclass_type
= mtype
.as(MClassType)
696 var layout
= self.resolution_layout
698 # extern const struct resolution_table_X resolution_table_X
699 self.provide_declaration
("resolution_table_{mtype.c_name}", "extern const struct types resolution_table_{mtype.c_name};")
701 # const struct fts_table_X fts_table_X
703 v
.add_decl
("const struct types resolution_table_{mtype.c_name} = \{")
704 if layout
isa PHLayout[MClassType, MType] then
705 v
.add_decl
("{layout.masks[mclass_type]},")
707 v
.add_decl
("0, /* dummy */")
710 for t
in self.resolution_tables
[mclass_type
] do
712 v
.add_decl
("NULL, /* empty */")
714 # The table stores the result of the type resolution
715 # Therefore, for a receiver `mclass_type`, and a unresolved type `t`
716 # the value stored is tv.
717 var tv
= t
.resolve_for
(mclass_type
, mclass_type
, self.mainmodule
, true)
718 # FIXME: What typeids means here? How can a tv not be live?
719 if self.type_layout
.ids
.has_key
(tv
) then
720 v
.require_declaration
("type_{tv.c_name}")
721 v
.add_decl
("&type_{tv.c_name}, /* {t}: {tv} */")
723 v
.add_decl
("NULL, /* empty ({t}: {tv} not a live type) */")
731 # Globally compile the table of the class mclass
732 # In a link-time optimisation compiler, tables are globally computed
733 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
734 fun compile_class_to_c
(mclass
: MClass)
736 var mtype
= mclass
.intro
.bound_mtype
737 var c_name
= mclass
.c_name
738 var c_instance_name
= mclass
.c_instance_name
740 var vft
= self.method_tables
[mclass
]
741 var attrs
= self.attr_tables
[mclass
]
744 var is_dead
= runtime_type_analysis
!= null and not runtime_type_analysis
.live_classes
.has
(mclass
) and mtype
.ctype
== "val*" and mclass
.name
!= "NativeArray"
746 v
.add_decl
("/* runtime class {c_name} */")
750 self.provide_declaration
("class_{c_name}", "extern const struct class class_{c_name};")
751 v
.add_decl
("const struct class class_{c_name} = \{")
752 v
.add_decl
("{self.box_kind_of(mclass)}, /* box_kind */")
754 for i
in [0 .. vft
.length
[ do
755 var mpropdef
= vft
[i
]
756 if mpropdef
== null then
757 v
.add_decl
("NULL, /* empty */")
759 assert mpropdef
isa MMethodDef
760 var rf
= mpropdef
.virtual_runtime_function
761 v
.require_declaration
(rf
.c_name
)
762 v
.add_decl
("(nitmethod_t){rf.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
769 if mtype
.ctype
!= "val*" then
770 if mtype
.mclass
.name
== "Pointer" or mtype
.mclass
.kind
!= extern_kind
then
771 #Build instance struct
772 self.header
.add_decl
("struct instance_{c_instance_name} \{")
773 self.header
.add_decl
("const struct type *type;")
774 self.header
.add_decl
("const struct class *class;")
775 self.header
.add_decl
("{mtype.ctype} value;")
776 self.header
.add_decl
("\};")
779 if not self.runtime_type_analysis
.live_types
.has
(mtype
) then return
782 self.provide_declaration
("BOX_{c_name}", "val* BOX_{c_name}({mtype.ctype});")
783 v
.add_decl
("/* allocate {mtype} */")
784 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
785 v
.add
("struct instance_{c_instance_name}*res = nit_alloc(sizeof(struct instance_{c_instance_name}));")
786 v
.require_declaration
("type_{c_name}")
787 v
.add
("res->type = &type_{c_name};")
788 v
.require_declaration
("class_{c_name}")
789 v
.add
("res->class = &class_{c_name};")
790 v
.add
("res->value = value;")
791 v
.add
("return (val*)res;")
794 else if mclass
.name
== "NativeArray" then
795 #Build instance struct
796 self.header
.add_decl
("struct instance_{c_instance_name} \{")
797 self.header
.add_decl
("const struct type *type;")
798 self.header
.add_decl
("const struct class *class;")
799 # NativeArrays are just a instance header followed by an array of values
800 self.header
.add_decl
("val* values[0];")
801 self.header
.add_decl
("\};")
804 self.provide_declaration
("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(int length, const struct type* type);")
805 v
.add_decl
("/* allocate {mtype} */")
806 v
.add_decl
("{mtype.ctype} NEW_{c_name}(int length, const struct type* type) \{")
807 var res
= v
.new_named_var
(mtype
, "self")
809 var mtype_elt
= mtype
.arguments
.first
810 v
.add
("{res} = nit_alloc(sizeof(struct instance_{c_instance_name}) + length*sizeof({mtype_elt.ctype}));")
811 v
.add
("{res}->type = type;")
812 hardening_live_type
(v
, "type")
813 v
.require_declaration
("class_{c_name}")
814 v
.add
("{res}->class = &class_{c_name};")
815 v
.add
("return {res};")
821 self.provide_declaration
("NEW_{c_name}", "{mtype.ctype} NEW_{c_name}(const struct type* type);")
822 v
.add_decl
("/* allocate {mtype} */")
823 v
.add_decl
("{mtype.ctype} NEW_{c_name}(const struct type* type) \{")
825 v
.add_abort
("{mclass} is DEAD")
827 var res
= v
.new_named_var
(mtype
, "self")
829 v
.add
("{res} = nit_alloc(sizeof(struct instance) + {attrs.length}*sizeof(nitattribute_t));")
830 v
.add
("{res}->type = type;")
831 hardening_live_type
(v
, "type")
832 v
.require_declaration
("class_{c_name}")
833 v
.add
("{res}->class = &class_{c_name};")
834 self.generate_init_attr
(v
, res
, mtype
)
835 v
.add
("return {res};")
840 # Add a dynamic test to ensure that the type referenced by `t` is a live type
841 fun hardening_live_type
(v
: VISITOR, t
: String)
843 if not v
.compiler
.modelbuilder
.toolcontext
.opt_hardening
.value
then return
844 v
.add
("if({t} == NULL) \{")
845 v
.add_abort
("type null")
847 v
.add
("if({t}->table_size == 0) \{")
848 v
.add
("fprintf(stderr, \"Insantiation of a dead
type: %s\\n\
", {t}->name);")
849 v
.add_abort
("type dead")
853 redef fun new_visitor
do return new SeparateCompilerVisitor(self)
857 private var type_tables
: Map[MType, Array[nullable MType]] = new HashMap[MType, Array[nullable MType]]
858 private var resolution_tables
: Map[MClassType, Array[nullable MType]] = new HashMap[MClassType, Array[nullable MType]]
859 protected var method_tables
: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
860 protected var attr_tables
: Map[MClass, Array[nullable MPropDef]] = new HashMap[MClass, Array[nullable MPropDef]]
862 redef fun display_stats
865 if self.modelbuilder
.toolcontext
.opt_tables_metrics
.value
then
872 print
"# size of subtyping tables"
873 print
"\ttotal \tholes"
876 for t
, table
in type_tables
do
877 total
+= table
.length
878 for e
in table
do if e
== null then holes
+= 1
880 print
"\t{total}\t{holes}"
882 print
"# size of resolution tables"
883 print
"\ttotal \tholes"
886 for t
, table
in resolution_tables
do
887 total
+= table
.length
888 for e
in table
do if e
== null then holes
+= 1
890 print
"\t{total}\t{holes}"
892 print
"# size of methods tables"
893 print
"\ttotal \tholes"
896 for t
, table
in method_tables
do
897 total
+= table
.length
898 for e
in table
do if e
== null then holes
+= 1
900 print
"\t{total}\t{holes}"
902 print
"# size of attributes tables"
903 print
"\ttotal \tholes"
906 for t
, table
in attr_tables
do
907 total
+= table
.length
908 for e
in table
do if e
== null then holes
+= 1
910 print
"\t{total}\t{holes}"
913 redef fun compile_nitni_structs
915 self.header
.add_decl
("struct nitni_instance \{struct instance *value;\};")
918 redef fun finalize_ffi_for_module
(nmodule
)
920 var old_module
= self.mainmodule
921 self.mainmodule
= nmodule
.mmodule
.as(not null)
923 self.mainmodule
= old_module
927 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
928 class SeparateCompilerVisitor
929 super AbstractCompilerVisitor
931 redef type COMPILER: SeparateCompiler
933 redef fun adapt_signature
(m
, args
)
935 var msignature
= m
.msignature
.resolve_for
(m
.mclassdef
.bound_mtype
, m
.mclassdef
.bound_mtype
, m
.mclassdef
.mmodule
, true)
936 var recv
= args
.first
937 if recv
.mtype
.ctype
!= m
.mclassdef
.mclass
.mclass_type
.ctype
then
938 args
.first
= self.autobox
(args
.first
, m
.mclassdef
.mclass
.mclass_type
)
940 for i
in [0..msignature
.arity
[ do
941 var t
= msignature
.mparameters
[i
].mtype
942 if i
== msignature
.vararg_rank
then
945 args
[i
+1] = self.autobox
(args
[i
+1], t
)
949 redef fun autobox
(value
, mtype
)
951 if value
.mtype
== mtype
then
953 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
955 else if value
.mtype
.ctype
== "val*" then
956 return self.new_expr
("((struct instance_{mtype.c_instance_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
957 else if mtype
.ctype
== "val*" then
958 var valtype
= value
.mtype
.as(MClassType)
959 var res
= self.new_var
(mtype
)
960 if compiler
.runtime_type_analysis
!= null and not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
961 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
962 self.add
("printf(\"Dead code executed
!\\n\
"); show_backtrace(1);")
965 self.require_declaration
("BOX_{valtype.c_name}")
966 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
968 else if value
.mtype
.cname_blind
== "void*" and mtype
.cname_blind
== "void*" then
971 # Bad things will appen!
972 var res
= self.new_var
(mtype
)
973 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
974 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); show_backtrace(1);")
979 # Return a C expression returning the runtime type structure of the value
980 # The point of the method is to works also with primitives types.
981 fun type_info
(value
: RuntimeVariable): String
983 if value
.mtype
.ctype
== "val*" then
984 return "{value}->type"
986 compiler
.undead_types
.add
(value
.mtype
)
987 self.require_declaration
("type_{value.mtype.c_name}")
988 return "(&type_{value.mtype.c_name})"
992 redef fun send
(mmethod
, arguments
)
994 self.varargize
(mmethod
.intro
, mmethod
.intro
.msignature
.as(not null), arguments
)
996 if arguments
.first
.mcasttype
.ctype
!= "val*" then
997 # In order to shortcut the primitive, we need to find the most specific method
998 # Howverr, because of performance (no flattening), we always work on the realmainmodule
999 var m
= self.compiler
.mainmodule
1000 self.compiler
.mainmodule
= self.compiler
.realmainmodule
1001 var res
= self.monomorphic_send
(mmethod
, arguments
.first
.mcasttype
, arguments
)
1002 self.compiler
.mainmodule
= m
1006 return table_send
(mmethod
, arguments
, mmethod
.const_color
)
1009 private fun table_send
(mmethod
: MMethod, arguments
: Array[RuntimeVariable], const_color
: String): nullable RuntimeVariable
1011 assert arguments
.length
== mmethod
.intro
.msignature
.arity
+ 1 else debug
("Invalid arity for {mmethod}. {arguments.length} arguments given.")
1013 var res
: nullable RuntimeVariable
1014 var msignature
= mmethod
.intro
.msignature
.resolve_for
(mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.bound_mtype
, mmethod
.intro
.mclassdef
.mmodule
, true)
1015 var ret
= msignature
.return_mtype
1016 if mmethod
.is_new
then
1017 ret
= arguments
.first
.mtype
1018 res
= self.new_var
(ret
)
1019 else if ret
== null then
1022 res
= self.new_var
(ret
)
1025 var s
= new FlatBuffer
1026 var ss
= new FlatBuffer
1028 var recv
= arguments
.first
1031 for i
in [0..msignature
.arity
[ do
1032 var a
= arguments
[i
+1]
1033 var t
= msignature
.mparameters
[i
].mtype
1034 if i
== msignature
.vararg_rank
then
1035 t
= arguments
[i
+1].mcasttype
1037 s
.append
(", {t.ctype}")
1038 a
= self.autobox
(a
, t
)
1042 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or mmethod
.name
== "==" or mmethod
.name
== "!="
1043 var maybenull
= recv
.mcasttype
isa MNullableType and consider_null
1045 self.add
("if ({recv} == NULL) \{")
1046 if mmethod
.name
== "==" then
1048 var arg
= arguments
[1]
1049 if arg
.mcasttype
isa MNullableType then
1050 self.add
("{res} = ({arg} == NULL);")
1051 else if arg
.mcasttype
isa MNullType then
1052 self.add
("{res} = 1; /* is null */")
1054 self.add
("{res} = 0; /* {arg.inspect} cannot be null */")
1056 else if mmethod
.name
== "!=" then
1058 var arg
= arguments
[1]
1059 if arg
.mcasttype
isa MNullableType then
1060 self.add
("{res} = ({arg} != NULL);")
1061 else if arg
.mcasttype
isa MNullType then
1062 self.add
("{res} = 0; /* is null */")
1064 self.add
("{res} = 1; /* {arg.inspect} cannot be null */")
1067 self.add_abort
("Receiver is null")
1069 self.add
("\} else \{")
1071 if not self.compiler
.modelbuilder
.toolcontext
.opt_no_shortcut_equate
.value
and (mmethod
.name
== "==" or mmethod
.name
== "!=") then
1073 # Recv is not null, thus is arg is, it is easy to conclude (and respect the invariants)
1074 var arg
= arguments
[1]
1075 if arg
.mcasttype
isa MNullType then
1076 if mmethod
.name
== "==" then
1077 self.add
("{res} = 0; /* arg is null but recv is not */")
1079 self.add
("{res} = 1; /* arg is null and recv is not */")
1089 if ret
== null then r
= "void" else r
= ret
.ctype
1090 self.require_declaration
(const_color
)
1091 var call
= "(({r} (*)({s}))({arguments.first}->class->vft[{const_color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
1094 self.add
("{res} = {call};")
1106 redef fun call
(mmethoddef
, recvtype
, arguments
)
1108 assert arguments
.length
== mmethoddef
.msignature
.arity
+ 1 else debug
("Invalid arity for {mmethoddef}. {arguments.length} arguments given.")
1110 var res
: nullable RuntimeVariable
1111 var ret
= mmethoddef
.msignature
.return_mtype
1112 if mmethoddef
.mproperty
.is_new
then
1113 ret
= arguments
.first
.mtype
1114 res
= self.new_var
(ret
)
1115 else if ret
== null then
1118 ret
= ret
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1119 res
= self.new_var
(ret
)
1122 if self.compiler
.modelbuilder
.mpropdef2npropdef
.has_key
(mmethoddef
) and
1123 self.compiler
.modelbuilder
.mpropdef2npropdef
[mmethoddef
] isa AInternMethPropdef and
1124 not compiler
.modelbuilder
.toolcontext
.opt_no_inline_intern
.value
then
1125 var frame
= new Frame(self, mmethoddef
, recvtype
, arguments
)
1126 frame
.returnlabel
= self.get_name
("RET_LABEL")
1127 frame
.returnvar
= res
1128 var old_frame
= self.frame
1130 self.add
("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
1131 mmethoddef
.compile_inside_to_c
(self, arguments
)
1132 self.add
("{frame.returnlabel.as(not null)}:(void)0;")
1134 self.frame
= old_frame
1139 self.adapt_signature
(mmethoddef
, arguments
)
1141 self.require_declaration
(mmethoddef
.c_name
)
1143 self.add
("{mmethoddef.c_name}({arguments.join(", ")});")
1146 self.add
("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
1152 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1154 if arguments
.first
.mcasttype
.ctype
!= "val*" then
1155 # In order to shortcut the primitive, we need to find the most specific method
1156 # However, because of performance (no flattening), we always work on the realmainmodule
1157 var main
= self.compiler
.mainmodule
1158 self.compiler
.mainmodule
= self.compiler
.realmainmodule
1159 var res
= self.monomorphic_super_send
(m
, recvtype
, arguments
)
1160 self.compiler
.mainmodule
= main
1163 return table_send
(m
.mproperty
, arguments
, m
.const_color
)
1166 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
1168 # A vararg must be stored into an new array
1169 # The trick is that the dymaic type of the array may depends on the receiver
1170 # of the method (ie recv) if the static type is unresolved
1171 # This is more complex than usual because the unresolved type must not be resolved
1172 # with the current receiver (ie self).
1173 # Therefore to isolate the resolution from self, a local Frame is created.
1174 # One can see this implementation as an inlined method of the receiver whose only
1175 # job is to allocate the array
1176 var old_frame
= self.frame
1177 var frame
= new Frame(self, mpropdef
, mpropdef
.mclassdef
.bound_mtype
, [recv
])
1179 #print "required Array[{elttype}] for recv {recv.inspect}. bound=Array[{self.resolve_for(elttype, recv)}]. selfvar={frame.arguments.first.inspect}"
1180 var res
= self.array_instance
(varargs
, elttype
)
1181 self.frame
= old_frame
1185 redef fun isset_attribute
(a
, recv
)
1187 self.check_recv_notnull
(recv
)
1188 var res
= self.new_var
(bool_type
)
1190 # What is the declared type of the attribute?
1191 var mtype
= a
.intro
.static_mtype
.as(not null)
1192 var intromclassdef
= a
.intro
.mclassdef
1193 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1195 if mtype
isa MNullableType then
1196 self.add
("{res} = 1; /* easy isset: {a} on {recv.inspect} */")
1200 self.require_declaration
(a
.const_color
)
1201 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1202 self.add
("{res} = {recv}->attrs[{a.const_color}] != NULL; /* {a} on {recv.inspect}*/")
1205 if mtype
.ctype
== "val*" then
1206 self.add
("{res} = {recv}->attrs[{a.const_color}].val != NULL; /* {a} on {recv.inspect} */")
1208 self.add
("{res} = 1; /* NOT YET IMPLEMENTED: isset of primitives: {a} on {recv.inspect} */")
1214 redef fun read_attribute
(a
, recv
)
1216 self.check_recv_notnull
(recv
)
1218 # What is the declared type of the attribute?
1219 var ret
= a
.intro
.static_mtype
.as(not null)
1220 var intromclassdef
= a
.intro
.mclassdef
1221 ret
= ret
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1223 self.require_declaration
(a
.const_color
)
1224 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1225 # Get the attribute or a box (ie. always a val*)
1226 var cret
= self.object_type
.as_nullable
1227 var res
= self.new_var
(cret
)
1230 self.add
("{res} = {recv}->attrs[{a.const_color}]; /* {a} on {recv.inspect} */")
1232 # Check for Uninitialized attribute
1233 if not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1234 self.add
("if ({res} == NULL) \{")
1235 self.add_abort
("Uninitialized attribute {a.name}")
1239 # Return the attribute or its unboxed version
1240 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
1241 return self.autobox
(res
, ret
)
1243 var res
= self.new_var
(ret
)
1244 self.add
("{res} = {recv}->attrs[{a.const_color}].{ret.ctypename}; /* {a} on {recv.inspect} */")
1246 # Check for Uninitialized attribute
1247 if ret
.ctype
== "val*" and not ret
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then
1248 self.add
("if ({res} == NULL) \{")
1249 self.add_abort
("Uninitialized attribute {a.name}")
1257 redef fun write_attribute
(a
, recv
, value
)
1259 self.check_recv_notnull
(recv
)
1261 # What is the declared type of the attribute?
1262 var mtype
= a
.intro
.static_mtype
.as(not null)
1263 var intromclassdef
= a
.intro
.mclassdef
1264 mtype
= mtype
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1266 # Adapt the value to the declared type
1267 value
= self.autobox
(value
, mtype
)
1269 self.require_declaration
(a
.const_color
)
1270 if self.compiler
.modelbuilder
.toolcontext
.opt_no_union_attribute
.value
then
1271 var attr
= "{recv}->attrs[{a.const_color}]"
1272 if mtype
.ctype
!= "val*" then
1273 assert mtype
isa MClassType
1274 # The attribute is primitive, thus we store it in a box
1275 # The trick is to create the box the first time then resuse the box
1276 self.add
("if ({attr} != NULL) \{")
1277 self.add
("((struct instance_{mtype.c_instance_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
1278 self.add
("\} else \{")
1279 value
= self.autobox
(value
, self.object_type
.as_nullable
)
1280 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1283 # The attribute is not primitive, thus store it direclty
1284 self.add
("{attr} = {value}; /* {a} on {recv.inspect} */")
1287 self.add
("{recv}->attrs[{a.const_color}].{mtype.ctypename} = {value}; /* {a} on {recv.inspect} */")
1291 # Check that mtype is a live open type
1292 fun hardening_live_open_type
(mtype
: MType)
1294 if not compiler
.modelbuilder
.toolcontext
.opt_hardening
.value
then return
1295 self.require_declaration
(mtype
.const_color
)
1296 var col
= mtype
.const_color
1297 self.add
("if({col} == -1) \{")
1298 self.add
("fprintf(stderr, \"Resolution of a dead open
type: %s\\n\
", \"{mtype.to_s.escape_to_c}\
");")
1299 self.add_abort
("open type dead")
1303 # Check that mtype it a pointer to a live cast type
1304 fun hardening_cast_type
(t
: String)
1306 if not compiler
.modelbuilder
.toolcontext
.opt_hardening
.value
then return
1307 add
("if({t} == NULL) \{")
1308 add_abort
("cast type null")
1310 add
("if({t}->id == -1 || {t}->color == -1) \{")
1311 add
("fprintf(stderr, \"Try to cast on a dead cast
type: %s\\n\
", {t}->name);")
1312 add_abort
("cast type dead")
1316 redef fun init_instance
(mtype
)
1318 self.require_declaration
("NEW_{mtype.mclass.c_name}")
1319 var compiler
= self.compiler
1320 if mtype
isa MGenericType and mtype
.need_anchor
then
1321 hardening_live_open_type
(mtype
)
1322 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1323 var recv
= self.frame
.arguments
.first
1324 var recv_type_info
= self.type_info
(recv
)
1325 self.require_declaration
(mtype
.const_color
)
1326 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1327 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
)
1329 return self.new_expr
("NEW_{mtype.mclass.c_name}({recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype
)
1332 compiler
.undead_types
.add
(mtype
)
1333 self.require_declaration
("type_{mtype.c_name}")
1334 return self.new_expr
("NEW_{mtype.mclass.c_name}(&type_{mtype.c_name})", mtype
)
1337 redef fun type_test
(value
, mtype
, tag
)
1339 self.add
("/* {value.inspect} isa {mtype} */")
1340 var compiler
= self.compiler
1342 var recv
= self.frame
.arguments
.first
1343 var recv_type_info
= self.type_info
(recv
)
1345 var res
= self.new_var
(bool_type
)
1347 var cltype
= self.get_name
("cltype")
1348 self.add_decl
("int {cltype};")
1349 var idtype
= self.get_name
("idtype")
1350 self.add_decl
("int {idtype};")
1352 var maybe_null
= self.maybe_null
(value
)
1353 var accept_null
= "0"
1355 if ntype
isa MNullableType then
1360 if value
.mcasttype
.is_subtype
(self.frame
.mpropdef
.mclassdef
.mmodule
, self.frame
.mpropdef
.mclassdef
.bound_mtype
, mtype
) then
1361 self.add
("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
1362 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1363 self.compiler
.count_type_test_skipped
[tag
] += 1
1364 self.add
("count_type_test_skipped_{tag}++;")
1369 if ntype
.need_anchor
then
1370 var type_struct
= self.get_name
("type_struct")
1371 self.add_decl
("const struct type* {type_struct};")
1373 # Either with resolution_table with a direct resolution
1374 hardening_live_open_type
(mtype
)
1375 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1376 self.require_declaration
(mtype
.const_color
)
1377 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1378 self.add
("{type_struct} = {recv_type_info}->resolution_table->types[HASH({recv_type_info}->resolution_table->mask, {mtype.const_color})];")
1380 self.add
("{type_struct} = {recv_type_info}->resolution_table->types[{mtype.const_color}];")
1382 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1383 self.compiler
.count_type_test_unresolved
[tag
] += 1
1384 self.add
("count_type_test_unresolved_{tag}++;")
1386 hardening_cast_type
(type_struct
)
1387 self.add
("{cltype} = {type_struct}->color;")
1388 self.add
("{idtype} = {type_struct}->id;")
1389 if maybe_null
and accept_null
== "0" then
1390 var is_nullable
= self.get_name
("is_nullable")
1391 self.add_decl
("short int {is_nullable};")
1392 self.add
("{is_nullable} = {type_struct}->is_nullable;")
1393 accept_null
= is_nullable
.to_s
1395 else if ntype
isa MClassType then
1396 compiler
.undead_types
.add
(mtype
)
1397 self.require_declaration
("type_{mtype.c_name}")
1398 hardening_cast_type
("(&type_{mtype.c_name})")
1399 self.add
("{cltype} = type_{mtype.c_name}.color;")
1400 self.add
("{idtype} = type_{mtype.c_name}.id;")
1401 if compiler
.modelbuilder
.toolcontext
.opt_typing_test_metrics
.value
then
1402 self.compiler
.count_type_test_resolved
[tag
] += 1
1403 self.add
("count_type_test_resolved_{tag}++;")
1406 self.add
("printf(\"NOT YET IMPLEMENTED: type_test
(%s
, {mtype}).\\n\
", \"{value.inspect}\
"); show_backtrace(1);")
1409 # check color is in table
1411 self.add
("if({value} == NULL) \{")
1412 self.add
("{res} = {accept_null};")
1413 self.add
("\} else \{")
1415 var value_type_info
= self.type_info
(value
)
1416 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1417 self.add
("{cltype} = HASH({value_type_info}->color, {idtype});")
1419 self.add
("if({cltype} >= {value_type_info}->table_size) \{")
1420 self.add
("{res} = 0;")
1421 self.add
("\} else \{")
1422 self.add
("{res} = {value_type_info}->type_table[{cltype}] == {idtype};")
1431 redef fun is_same_type_test
(value1
, value2
)
1433 var res
= self.new_var
(bool_type
)
1434 # Swap values to be symetric
1435 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1440 if value1
.mtype
.ctype
!= "val*" then
1441 if value2
.mtype
== value1
.mtype
then
1442 self.add
("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1443 else if value2
.mtype
.ctype
!= "val*" then
1444 self.add
("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1446 var mtype1
= value1
.mtype
.as(MClassType)
1447 self.require_declaration
("class_{mtype1.c_name}")
1448 self.add
("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name}); /* is_same_type_test */")
1451 self.add
("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1456 redef fun class_name_string
(value
)
1458 var res
= self.get_name
("var_class_name")
1459 self.add_decl
("const char* {res};")
1460 if value
.mtype
.ctype
== "val*" then
1461 self.add
"{res} = {value} == NULL ? \"null\
" : {value}->type->name;"
1462 else if value
.mtype
isa MClassType and value
.mtype
.as(MClassType).mclass
.kind
== extern_kind
then
1463 self.add
"{res} = \"{value.mtype.as(MClassType).mclass}\
";"
1465 self.require_declaration
("type_{value.mtype.c_name}")
1466 self.add
"{res} = type_{value.mtype.c_name}.name;"
1471 redef fun equal_test
(value1
, value2
)
1473 var res
= self.new_var
(bool_type
)
1474 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
1479 if value1
.mtype
.ctype
!= "val*" then
1480 if value2
.mtype
== value1
.mtype
then
1481 self.add
("{res} = {value1} == {value2};")
1482 else if value2
.mtype
.ctype
!= "val*" then
1483 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1485 var mtype1
= value1
.mtype
.as(MClassType)
1486 self.require_declaration
("class_{mtype1.c_name}")
1487 self.add
("{res} = ({value2} != NULL) && ({value2}->class == &class_{mtype1.c_name});")
1488 self.add
("if ({res}) \{")
1489 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1494 var maybe_null
= true
1495 var test
= new Array[String]
1496 var t1
= value1
.mcasttype
1497 if t1
isa MNullableType then
1498 test
.add
("{value1} != NULL")
1503 var t2
= value2
.mcasttype
1504 if t2
isa MNullableType then
1505 test
.add
("{value2} != NULL")
1511 var incompatible
= false
1513 if t1
.ctype
!= "val*" then
1516 # No need to compare class
1517 else if t2
.ctype
!= "val*" then
1519 else if can_be_primitive
(value2
) then
1520 test
.add
("{value1}->class == {value2}->class")
1524 else if t2
.ctype
!= "val*" then
1526 if can_be_primitive
(value1
) then
1527 test
.add
("{value1}->class == {value2}->class")
1535 if incompatible
then
1537 self.add
("{res} = {value1} == {value2}; /* incompatible types {t1} vs. {t2}; but may be NULL*/")
1540 self.add
("{res} = 0; /* incompatible types {t1} vs. {t2}; cannot be NULL */")
1544 if primitive
!= null then
1545 test
.add
("((struct instance_{primitive.c_instance_name}*){value1})->value == ((struct instance_{primitive.c_instance_name}*){value2})->value")
1546 else if can_be_primitive
(value1
) and can_be_primitive
(value2
) then
1547 test
.add
("{value1}->class == {value2}->class")
1548 var s
= new Array[String]
1549 for t
, v
in self.compiler
.box_kinds
do
1550 s
.add
"({value1}->class->box_kind == {v} && ((struct instance_{t.c_instance_name}*){value1})->value == ((struct instance_{t.c_instance_name}*){value2})->value)"
1552 test
.add
("({s.join(" || ")})")
1554 self.add
("{res} = {value1} == {value2};")
1557 self.add
("{res} = {value1} == {value2} || ({test.join(" && ")});")
1561 fun can_be_primitive
(value
: RuntimeVariable): Bool
1563 var t
= value
.mcasttype
1564 if t
isa MNullableType then t
= t
.mtype
1565 if not t
isa MClassType then return false
1566 var k
= t
.mclass
.kind
1567 return k
== interface_kind
or t
.ctype
!= "val*"
1570 fun maybe_null
(value
: RuntimeVariable): Bool
1572 var t
= value
.mcasttype
1573 return t
isa MNullableType or t
isa MNullType
1576 redef fun array_instance
(array
, elttype
)
1578 var nclass
= self.get_class
("NativeArray")
1579 var arrayclass
= self.get_class
("Array")
1580 var arraytype
= arrayclass
.get_mtype
([elttype
])
1581 var res
= self.init_instance
(arraytype
)
1582 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
1583 var length
= self.int_instance
(array
.length
)
1584 var nat
= native_array_instance
(elttype
, length
)
1585 for i
in [0..array
.length
[ do
1586 var r
= self.autobox
(array
[i
], self.object_type
)
1587 self.add
("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1589 self.send
(self.get_property
("with_native", arrayclass
.intro
.bound_mtype
), [res
, nat
, length
])
1594 fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
1596 var mtype
= self.get_class
("NativeArray").get_mtype
([elttype
])
1597 self.require_declaration
("NEW_{mtype.mclass.c_name}")
1598 assert mtype
isa MGenericType
1599 var compiler
= self.compiler
1600 if mtype
.need_anchor
then
1601 hardening_live_open_type
(mtype
)
1602 link_unresolved_type
(self.frame
.mpropdef
.mclassdef
, mtype
)
1603 var recv
= self.frame
.arguments
.first
1604 var recv_type_info
= self.type_info
(recv
)
1605 self.require_declaration
(mtype
.const_color
)
1606 if compiler
.modelbuilder
.toolcontext
.opt_phmod_typing
.value
or compiler
.modelbuilder
.toolcontext
.opt_phand_typing
.value
then
1607 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
)
1609 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, {recv_type_info}->resolution_table->types[{mtype.const_color}])", mtype
)
1612 compiler
.undead_types
.add
(mtype
)
1613 self.require_declaration
("type_{mtype.c_name}")
1614 return self.new_expr
("NEW_{mtype.mclass.c_name}({length}, &type_{mtype.c_name})", mtype
)
1617 redef fun native_array_def
(pname
, ret_type
, arguments
)
1619 var elttype
= arguments
.first
.mtype
1620 var nclass
= self.get_class
("NativeArray")
1621 var recv
= "((struct instance_{nclass.c_instance_name}*){arguments[0]})->values"
1622 if pname
== "[]" then
1623 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
1625 else if pname
== "[]=" then
1626 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
1628 else if pname
== "copy_to" then
1629 var recv1
= "((struct instance_{nclass.c_instance_name}*){arguments[1]})->values"
1630 self.add
("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1635 redef fun calloc_array
(ret_type
, arguments
)
1637 var mclass
= self.get_class
("ArrayCapable")
1638 var ft
= mclass
.mclass_type
.arguments
.first
.as(MParameterType)
1639 var res
= self.native_array_instance
(ft
, arguments
[1])
1643 fun link_unresolved_type
(mclassdef
: MClassDef, mtype
: MType) do
1644 assert mtype
.need_anchor
1645 var compiler
= self.compiler
1646 if not compiler
.live_unresolved_types
.has_key
(self.frame
.mpropdef
.mclassdef
) then
1647 compiler
.live_unresolved_types
[self.frame
.mpropdef
.mclassdef
] = new HashSet[MType]
1649 compiler
.live_unresolved_types
[self.frame
.mpropdef
.mclassdef
].add
(mtype
)
1653 redef class MMethodDef
1654 fun separate_runtime_function
: AbstractRuntimeFunction
1656 var res
= self.separate_runtime_function_cache
1658 res
= new SeparateRuntimeFunction(self)
1659 self.separate_runtime_function_cache
= res
1663 private var separate_runtime_function_cache
: nullable SeparateRuntimeFunction
1665 fun virtual_runtime_function
: AbstractRuntimeFunction
1667 var res
= self.virtual_runtime_function_cache
1669 res
= new VirtualRuntimeFunction(self)
1670 self.virtual_runtime_function_cache
= res
1674 private var virtual_runtime_function_cache
: nullable VirtualRuntimeFunction
1677 # The C function associated to a methoddef separately compiled
1678 class SeparateRuntimeFunction
1679 super AbstractRuntimeFunction
1681 redef fun build_c_name
: String do return "{mmethoddef.c_name}"
1683 redef fun to_s
do return self.mmethoddef
.to_s
1685 redef fun compile_to_c
(compiler
)
1687 var mmethoddef
= self.mmethoddef
1689 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1690 var v
= compiler
.new_visitor
1691 var selfvar
= new RuntimeVariable("self", recv
, recv
)
1692 var arguments
= new Array[RuntimeVariable]
1693 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1696 var msignature
= mmethoddef
.msignature
.resolve_for
(mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.bound_mtype
, mmethoddef
.mclassdef
.mmodule
, true)
1698 var sig
= new FlatBuffer
1699 var comment
= new FlatBuffer
1700 var ret
= msignature
.return_mtype
1702 sig
.append
("{ret.ctype} ")
1703 else if mmethoddef
.mproperty
.is_new
then
1705 sig
.append
("{ret.ctype} ")
1709 sig
.append
(self.c_name
)
1710 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1711 comment
.append
("({selfvar}: {selfvar.mtype}")
1712 arguments
.add
(selfvar
)
1713 for i
in [0..msignature
.arity
[ do
1714 var mtype
= msignature
.mparameters
[i
].mtype
1715 if i
== msignature
.vararg_rank
then
1716 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1718 comment
.append
(", {mtype}")
1719 sig
.append
(", {mtype.ctype} p{i}")
1720 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1721 arguments
.add
(argvar
)
1726 comment
.append
(": {ret}")
1728 compiler
.provide_declaration
(self.c_name
, "{sig};")
1730 v
.add_decl
("/* method {self} for {comment} */")
1731 v
.add_decl
("{sig} \{")
1733 frame
.returnvar
= v
.new_var
(ret
)
1735 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1737 if recv
!= arguments
.first
.mtype
then
1738 #print "{self} {recv} {arguments.first}"
1740 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1742 v
.add
("{frame.returnlabel.as(not null)}:;")
1744 v
.add
("return {frame.returnvar.as(not null)};")
1747 if not self.c_name
.has_substring
("VIRTUAL", 0) then compiler
.names
[self.c_name
] = "{mmethoddef.mclassdef.mmodule.name}::{mmethoddef.mclassdef.mclass.name}::{mmethoddef.mproperty.name} ({mmethoddef.location.file.filename}:{mmethoddef.location.line_start})"
1751 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
1752 # The first parameter (the reciever) is always typed by val* in order to accept an object value
1753 class VirtualRuntimeFunction
1754 super AbstractRuntimeFunction
1756 redef fun build_c_name
: String do return "VIRTUAL_{mmethoddef.c_name}"
1758 redef fun to_s
do return self.mmethoddef
.to_s
1760 redef fun compile_to_c
(compiler
)
1762 var mmethoddef
= self.mmethoddef
1764 var recv
= self.mmethoddef
.mclassdef
.bound_mtype
1765 var v
= compiler
.new_visitor
1766 var selfvar
= new RuntimeVariable("self", v
.object_type
, recv
)
1767 var arguments
= new Array[RuntimeVariable]
1768 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
1771 var sig
= new FlatBuffer
1772 var comment
= new FlatBuffer
1774 # Because the function is virtual, the signature must match the one of the original class
1775 var intromclassdef
= self.mmethoddef
.mproperty
.intro
.mclassdef
1776 var msignature
= mmethoddef
.mproperty
.intro
.msignature
.resolve_for
(intromclassdef
.bound_mtype
, intromclassdef
.bound_mtype
, intromclassdef
.mmodule
, true)
1777 var ret
= msignature
.return_mtype
1779 sig
.append
("{ret.ctype} ")
1780 else if mmethoddef
.mproperty
.is_new
then
1782 sig
.append
("{ret.ctype} ")
1786 sig
.append
(self.c_name
)
1787 sig
.append
("({selfvar.mtype.ctype} {selfvar}")
1788 comment
.append
("({selfvar}: {selfvar.mtype}")
1789 arguments
.add
(selfvar
)
1790 for i
in [0..msignature
.arity
[ do
1791 var mtype
= msignature
.mparameters
[i
].mtype
1792 if i
== msignature
.vararg_rank
then
1793 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
1795 comment
.append
(", {mtype}")
1796 sig
.append
(", {mtype.ctype} p{i}")
1797 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1798 arguments
.add
(argvar
)
1803 comment
.append
(": {ret}")
1805 compiler
.provide_declaration
(self.c_name
, "{sig};")
1807 v
.add_decl
("/* method {self} for {comment} */")
1808 v
.add_decl
("{sig} \{")
1810 frame
.returnvar
= v
.new_var
(ret
)
1812 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1814 var subret
= v
.call
(mmethoddef
, recv
, arguments
)
1816 assert subret
!= null
1817 v
.assign
(frame
.returnvar
.as(not null), subret
)
1820 v
.add
("{frame.returnlabel.as(not null)}:;")
1822 v
.add
("return {frame.returnvar.as(not null)};")
1825 if not self.c_name
.has_substring
("VIRTUAL", 0) then compiler
.names
[self.c_name
] = "{mmethoddef.mclassdef.mmodule.name}::{mmethoddef.mclassdef.mclass.name}::{mmethoddef.mproperty.name} ({mmethoddef.location.file.filename}--{mmethoddef.location.line_start})"
1829 redef fun call
(v
, arguments
) do abort
1833 fun const_color
: String do return "COLOR_{c_name}"
1835 # C name of the instance type to use
1836 fun c_instance_name
: String do return c_name
1839 redef class MClassType
1840 redef fun c_instance_name
do return mclass
.c_instance_name
1844 # Extern classes use the C instance of kernel::Pointer
1845 fun c_instance_name
: String
1847 if kind
== extern_kind
then
1848 return "kernel__Pointer"
1853 redef class MProperty
1854 fun const_color
: String do return "COLOR_{c_name}"
1857 redef class MPropDef
1858 fun const_color
: String do return "COLOR_{c_name}"