bc69ed14e00e26c0d7628d8a5878e18d97f00c1c
[nit.git] / src / compiling / compiling_global.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2008 Jean Privat <jean@pryen.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Compute and generate tables for classes and modules.
18 package compiling_global
19
20 private import compiling_icode
21
22 # Something that store color of table elements
23 class ColorContext
24 var _colors: HashMap[TableElt, Int] = new HashMap[TableElt, Int]
25
26 # The color of a table element.
27 fun color(e: TableElt): Int
28 do
29 return _colors[e]
30 end
31
32 # Is a table element already colored?
33 fun has_color(e: TableElt): Bool
34 do
35 return _colors.has_key(e)
36 end
37
38 # Assign a color to a table element.
39 fun color=(e: TableElt, c: Int)
40 do
41 _colors[e] = c
42 var idx = c
43 for i in [0..e.length[ do
44 _colors[e.item(i)] = idx
45 idx = idx + 1
46 end
47 end
48 end
49
50 # All information and results of the global analysis.
51 class GlobalAnalysis
52 special ColorContext
53 # Associate global classes to compiled classes
54 readable var _compiled_classes: HashMap[MMGlobalClass, CompiledClass] = new HashMap[MMGlobalClass, CompiledClass]
55
56 # The main module of the program globally analysed
57 readable var _module: MMModule
58
59 # FIXME: do something better.
60 readable writable var _max_class_table_length: Int = 0
61
62 init(module: MMModule)
63 do
64 _module = module
65 end
66 end
67
68 class GlobalCompilerVisitor
69 special CompilerVisitor
70 # The global analysis result
71 readable var _global_analysis: GlobalAnalysis
72 init(m: MMModule, tc: ToolContext, ga: GlobalAnalysis)
73 do
74 super(m, tc)
75 _global_analysis = ga
76 end
77 end
78
79 # A compiled class is a class in a program
80 class CompiledClass
81 special ColorContext
82 # The corresponding local class in the main module of the prgram
83 readable var _local_class: MMLocalClass
84
85 # The identifier of the class
86 readable writable var _id: Int = 0
87
88 # The full class table of the class
89 readable var _class_table: Array[nullable TableElt] = new Array[nullable TableElt]
90
91 # The full instance table of the class
92 readable var _instance_table: Array[nullable TableElt] = new Array[nullable TableElt]
93
94 # The proper class table part (no superclasses but all refinements)
95 readable writable var _class_layout: TableEltComposite = new TableEltComposite(self)
96
97 # The proper instance table part (no superclasses but all refinements)
98 readable writable var _instance_layout: TableEltComposite = new TableEltComposite(self)
99
100 init(c: MMLocalClass) do _local_class = c
101 end
102
103 redef class MMConcreteClass
104 # The table element of the subtype check
105 fun class_color_pos: TableEltClassColor do return _class_color_pos.as(not null)
106 var _class_color_pos: nullable TableEltClassColor
107
108 # The proper local class table part (nor superclasses nor refinments)
109 readable var _class_layout: Array[TableElt] = new Array[TableElt]
110
111 # The proper local instance table part (nor superclasses nor refinments)
112 readable var _instance_layout: Array[TableElt] = new Array[TableElt]
113
114 # Build the local layout of the class and feed the module table
115 fun build_layout_in(tc: ToolContext, module_table: Array[ModuleTableElt])
116 do
117 var clt = _class_layout
118 var ilt = _instance_layout
119
120 if global.intro == self then
121 module_table.add(new TableEltClassId(self))
122 var cpp = new TableEltClassColor(self)
123 _class_color_pos = cpp
124 module_table.add(cpp)
125 clt.add(new TableEltClassInitTable(self))
126 end
127 for p in local_local_properties do
128 var pg = p.global
129 if pg.intro == p then
130 if p isa MMAttribute then
131 ilt.add(new TableEltAttr(p))
132 else if p isa MMMethod then
133 clt.add(new TableEltMeth(p))
134 end
135 end
136 if p isa MMMethod and p.need_super then
137 clt.add(new TableEltSuper(p))
138 end
139 end
140
141 if not ilt.is_empty then
142 var teg = new ModuleTableEltGroup
143 teg.elements.append(ilt)
144 module_table.add(teg)
145 end
146
147 if not clt.is_empty then
148 var teg = new ModuleTableEltGroup
149 teg.elements.append(clt)
150 module_table.add(teg)
151 end
152 end
153 end
154
155 redef class MMModule
156 # The local table of the module (refers things introduced in the module)
157 var _local_table: Array[ModuleTableElt] = new Array[ModuleTableElt]
158
159 # Builds the local tables and local classes layouts
160 fun local_analysis(tc: ToolContext)
161 do
162 for c in local_classes do
163 if c isa MMConcreteClass then
164 c.build_layout_in(tc, _local_table)
165 end
166 end
167 end
168
169 # Do the complete global analysis
170 fun global_analysis(cctx: ToolContext): GlobalAnalysis
171 do
172 #print "Do the complete global analysis"
173 var ga = new GlobalAnalysis(self)
174 var smallest_classes = new Array[MMLocalClass]
175 var global_properties = new HashSet[MMGlobalProperty]
176 var ctab = new Array[TableElt]
177 var itab = new Array[TableElt]
178
179 ctab.add(new TableEltClassSelfId)
180 ctab.add(new TableEltClassObjectSize)
181 itab.add(new TableEltVftPointer)
182 itab.add(new TableEltObjectId)
183
184 var pclassid = -1
185 var classid = 3
186
187 # We have to work on ALL the classes of the module
188 var classes = new Array[MMLocalClass]
189 for c in local_classes do
190 c.compute_super_classes
191 classes.add(c)
192 end
193 (new ClassSorter).sort(classes)
194
195 for c in classes do
196 # Finish processing the class (if invisible)
197 c.compute_ancestors
198 c.inherit_global_properties
199
200 # Associate a CompiledClass to the class
201 var cc = new CompiledClass(c)
202 ga.compiled_classes[c.global] = cc
203
204 # Assign a unique class identifier
205 # (negative are for primitive classes)
206 var gc = c.global
207 var bm = gc.module
208 if c.primitive_info != null then
209 cc.id = pclassid
210 pclassid = pclassid - 4
211 else
212 cc.id = classid
213 classid = classid + 4
214 end
215
216 # Register is the class is a leaf
217 if c.cshe.direct_smallers.is_empty then
218 smallest_classes.add(c)
219 end
220
221 # Store the colortableelt in the class table pool
222 var bc = c.global.intro
223 assert bc isa MMConcreteClass
224 ctab.add(bc.class_color_pos)
225 end
226
227 # Compute core and crown classes for colorization
228 var crown_classes = new HashSet[MMLocalClass]
229 var core_classes = new HashSet[MMLocalClass]
230 for c in smallest_classes do
231 while c.cshe.direct_greaters.length == 1 do
232 c = c.cshe.direct_greaters.first
233 end
234 crown_classes.add(c)
235 core_classes.add_all(c.cshe.greaters_and_self)
236 end
237 #print("nbclasses: {classes.length} leaves: {smallest_classes.length} crown: {crown_classes.length} core: {core_classes.length}")
238
239 # Colorize core color for typechecks
240 colorize(ga, ctab, crown_classes, 0)
241
242 # Compute tables for typechecks
243 var maxcolor = 0
244 for c in classes do
245 var cc = ga.compiled_classes[c.global]
246 if core_classes.has(c) then
247 # For core classes, just build the table
248 build_tables_in(cc.class_table, ga, c, ctab)
249 if maxcolor < cc.class_table.length then maxcolor = cc.class_table.length
250 else
251 # For other classes, it's easier: just append to the parent tables
252 var sc = c.cshe.direct_greaters.first
253 var scc = ga.compiled_classes[sc.global]
254 assert cc.class_table.is_empty
255 cc.class_table.add_all(scc.class_table)
256 var bc = c.global.intro
257 assert bc isa MMConcreteClass
258 var colpos = bc.class_color_pos
259 var colposcolor = cc.class_table.length
260 ga.color(colpos) = colposcolor
261 cc.class_table.add(colpos)
262 if maxcolor < colposcolor then maxcolor = colposcolor
263 end
264 end
265 ga.max_class_table_length = maxcolor + 1
266
267 # Fill class table and instance tables pools
268 for c in classes do
269 var cc = ga.compiled_classes[c.global]
270 var cte = cc.class_layout
271 var ite = cc.instance_layout
272 for sc in c.crhe.greaters_and_self do
273 if sc isa MMConcreteClass then
274 cte.add(sc, sc.class_layout)
275 ite.add(sc, sc.instance_layout)
276 end
277 end
278
279 if core_classes.has(c) then
280 if cte.length > 0 then
281 ctab.add(cte)
282 end
283 if ite.length > 0 then
284 itab.add(ite)
285 end
286 end
287 end
288
289 # Colorize all elements in pools tables
290 colorize(ga, ctab, crown_classes, maxcolor+1)
291 colorize(ga, itab, crown_classes, 0)
292
293 # Build class and instance tables now things are colored
294 ga.max_class_table_length = 0
295 for c in classes do
296 var cc = ga.compiled_classes[c.global]
297 if core_classes.has(c) then
298 # For core classes, just build the table
299 build_tables_in(cc.class_table, ga, c, ctab)
300 build_tables_in(cc.instance_table, ga, c, itab)
301 else
302 # For other classes, it's easier: just append to the parent tables
303 var sc = c.cshe.direct_greaters.first
304 var scc = ga.compiled_classes[sc.global]
305 cc.class_table.clear
306 cc.class_table.add_all(scc.class_table)
307 var bc = c.global.intro
308 assert bc isa MMConcreteClass
309 var colpos = bc.class_color_pos
310 cc.class_table[ga.color(colpos)] = colpos
311 while cc.class_table.length <= maxcolor do
312 cc.class_table.add(null)
313 end
314 append_to_table(ga, cc.class_table, cc.class_layout)
315 assert cc.instance_table.is_empty
316 cc.instance_table.add_all(scc.instance_table)
317 append_to_table(ga, cc.instance_table, cc.instance_layout)
318 end
319 end
320
321 return ga
322 end
323
324 private fun append_to_table(cc: ColorContext, table: Array[nullable TableElt], cmp: TableEltComposite)
325 do
326 for j in [0..cmp.length[ do
327 var e = cmp.item(j)
328 cc.color(e) = table.length
329 table.add(e)
330 end
331 end
332
333 private fun build_tables_in(table: Array[nullable TableElt], ga: GlobalAnalysis, c: MMLocalClass, elts: Array[TableElt])
334 do
335 var tab = new HashMap[Int, TableElt]
336 var len = 0
337 for e in elts do
338 if e.is_related_to(c) then
339 var col = ga.color(e)
340 var l = col + e.length
341 tab[col] = e
342 if len < l then
343 len = l
344 end
345 end
346 end
347 var i = 0
348 while i < len do
349 if tab.has_key(i) then
350 var e = tab[i]
351 for j in [0..e.length[ do
352 table[i] = e.item(j)
353 i = i + 1
354 end
355 else
356 table[i] = null
357 i = i + 1
358 end
359 end
360 end
361
362 # Perform coloring
363 fun colorize(ga: GlobalAnalysis, elts: Array[TableElt], classes: Collection[MMLocalClass], startcolor: Int)
364 do
365 var colors = new HashMap[Int, Array[TableElt]]
366 var rel_classes = new Array[MMLocalClass]
367 for e in elts do
368 var color = -1
369 var len = e.length
370 if ga.has_color(e) then
371 color = ga.color(e)
372 else
373 rel_classes.clear
374 for c in classes do
375 if e.is_related_to(c) then
376 rel_classes.add(c)
377 end
378 end
379 var trycolor = startcolor
380 while trycolor != color do
381 color = trycolor
382 for c in rel_classes do
383 var idx = 0
384 while idx < len do
385 if colors.has_key(trycolor + idx) and not free_color(colors[trycolor + idx], c) then
386 trycolor = trycolor + idx + 1
387 idx = 0
388 else
389 idx = idx + 1
390 end
391 end
392 end
393 end
394 ga.color(e) = color
395 end
396 for idx in [0..len[ do
397 if colors.has_key(color + idx) then
398 colors[color + idx].add(e)
399 else
400 colors[color + idx] = [e]
401 end
402 end
403 end
404 end
405
406 private fun free_color(es: Array[TableElt], c: MMLocalClass): Bool
407 do
408 for e2 in es do
409 if e2.is_related_to(c) then
410 return false
411 end
412 end
413 return true
414 end
415
416 # Compile module and class tables
417 fun compile_tables_to_c(v: GlobalCompilerVisitor)
418 do
419 for m in mhe.greaters_and_self do
420 m.compile_local_table_to_c(v)
421 end
422
423 for c in local_classes do
424 c.compile_tables_to_c(v)
425 end
426 var s = new Buffer.from("classtable_t TAG2VFT[4] = \{NULL")
427 for t in ["Int","Char","Bool"] do
428 if has_global_class_named(t.to_symbol) then
429 s.append(", (const classtable_t)VFT_{t}")
430 else
431 s.append(", NULL")
432 end
433 end
434 s.append("};")
435 v.add_instr(s.to_s)
436 end
437
438 # Declare class table (for _sep.h)
439 fun declare_class_tables_to_c(v: GlobalCompilerVisitor)
440 do
441 for c in local_classes do
442 if c.global.module == self then
443 c.declare_tables_to_c(v)
444 end
445 end
446 end
447
448 # Compile main part (for _table.c)
449 fun compile_main_part(v: GlobalCompilerVisitor)
450 do
451 v.add_instr("int main(int argc, char **argv) \{")
452 v.indent
453 v.add_instr("prepare_signals();")
454 v.add_instr("glob_argc = argc; glob_argv = argv;")
455 var sysname = once "Sys".to_symbol
456 if not has_global_class_named(sysname) then
457 print("No main")
458 else
459 var sys = class_by_name(sysname)
460 var name = once "main".to_symbol
461 if not sys.has_global_property_by_name(name) then
462 print("No main")
463 else
464 var mainm = sys.select_method(name)
465 v.add_instr("G_sys = NEW_Sys();")
466 v.add_instr("register_static_object(&G_sys);")
467 v.add_instr("{mainm.cname}(G_sys);")
468 end
469 end
470 v.add_instr("return 0;")
471 v.unindent
472 v.add_instr("}")
473 end
474
475 # Compile sep files
476 fun compile_mod_to_c(v: GlobalCompilerVisitor)
477 do
478 v.add_decl("extern const char *LOCATE_{name};")
479 if not v.tc.global then
480 v.add_decl("extern const int SFT_{name}[];")
481 end
482 var i = 0
483 for e in _local_table do
484 var value: String
485 if v.tc.global then
486 value = "{e.value(v.global_analysis)}"
487 else
488 value = "SFT_{name}[{i}]"
489 i = i + 1
490 end
491 e.compile_macros(v, value)
492 end
493 for c in local_classes do
494 if not c isa MMConcreteClass then continue
495 for pg in c.global_properties do
496 var p = c[pg]
497 if p.local_class == c and p isa MMMethod then
498 p.compile_property_to_c(v)
499 end
500 if pg.is_init_for(c) then
501 # Declare constructors
502 var params = new Array[String]
503 for j in [0..p.signature.arity[ do
504 params.add("val_t p{j}")
505 end
506 v.add_decl("val_t NEW_{c}_{p.global.intro.cname}({params.join(", ")});")
507 end
508 end
509 end
510 end
511
512 # Compile module file for the current module
513 fun compile_local_table_to_c(v: GlobalCompilerVisitor)
514 do
515 v.add_instr("const char *LOCATE_{name} = \"{location.file}\";")
516
517 if v.tc.global or _local_table.is_empty then
518 return
519 end
520
521 v.add_instr("const int SFT_{name}[{_local_table.length}] = \{")
522 v.indent
523 for e in _local_table do
524 v.add_instr(e.value(v.global_analysis) + ",")
525 end
526 v.unindent
527 v.add_instr("\};")
528 end
529 end
530
531 ###############################################################################
532
533 # An element of a class, an instance or a module table
534 abstract class AbsTableElt
535 # Compile the macro needed to use the element and other related elements
536 fun compile_macros(v: GlobalCompilerVisitor, value: String) is abstract
537 end
538
539 # An element of a class or an instance table
540 # Such an elements represent method function pointers, attribute values, etc.
541 abstract class TableElt
542 special AbsTableElt
543 # Is the element conflict to class `c' (used for coloring)
544 fun is_related_to(c: MMLocalClass): Bool is abstract
545
546 # Number of sub-elements. 1 if none
547 fun length: Int do return 1
548
549 # Access the ith subelement.
550 fun item(i: Int): TableElt do return self
551
552 # Return the value of the element for a given class
553 fun compile_to_c(v: GlobalCompilerVisitor, c: MMLocalClass): String is abstract
554 end
555
556 # An element of a module table
557 # Such an elements represent colors or identifiers
558 abstract class ModuleTableElt
559 special AbsTableElt
560 # Return the value of the element once the global analisys is performed
561 fun value(ga: GlobalAnalysis): String is abstract
562 end
563
564 # An element of a module table that represents a group of TableElt defined in the same local class
565 class ModuleTableEltGroup
566 special ModuleTableElt
567 readable var _elements: Array[TableElt] = new Array[TableElt]
568
569 redef fun value(ga) do return "{ga.color(_elements.first)} /* Group of ? */"
570 redef fun compile_macros(v, value)
571 do
572 var i = 0
573 for e in _elements do
574 e.compile_macros(v, "{value} + {i}")
575 i += 1
576 end
577 end
578 end
579
580 # An element that represents a class property
581 abstract class TableEltProp
582 special TableElt
583 var _property: MMLocalProperty
584
585 init(p: MMLocalProperty)
586 do
587 _property = p
588 end
589 end
590
591 # An element that represents a function pointer to a global method
592 class TableEltMeth
593 special TableEltProp
594 redef fun compile_macros(v, value)
595 do
596 var pg = _property.global
597 v.add_decl("#define {pg.meth_call}(recv) (({pg.intro.cname}_t)CALL((recv), ({value})))")
598 end
599
600 redef fun compile_to_c(v, c)
601 do
602 var p = c[_property.global]
603 return p.cname
604 end
605 end
606
607 # An element that represents a function pointer to the super method of a local method
608 class TableEltSuper
609 special TableEltProp
610 redef fun compile_macros(v, value)
611 do
612 var p = _property
613 v.add_decl("#define {p.super_meth_call}(recv) (({p.cname}_t)CALL((recv), ({value})))")
614 end
615
616 redef fun compile_to_c(v, c)
617 do
618 var pc = _property.local_class
619 var g = _property.global
620 var lin = c.che.linear_extension
621 var found = false
622 for s in lin do
623 #print "{c.module}::{c} for {pc.module}::{pc}::{_property} try {s.module}:{s}"
624 if s == pc then
625 found = true
626 else if found and c.che < s then
627 if s.has_global_property(g) then
628 #print "found {s.module}::{s}::{p}"
629 return s[g].cname
630 end
631 end
632 end
633 abort
634 end
635 end
636
637 # An element that represents the value stored for a global attribute
638 class TableEltAttr
639 special TableEltProp
640 redef fun compile_macros(v, value)
641 do
642 var pg = _property.global
643 v.add_decl("#define {pg.attr_access}(recv) ATTR(recv, ({value}))")
644 end
645
646 redef fun compile_to_c(v, c)
647 do
648 var ga = v.global_analysis
649 var p = c[_property.global]
650 return "/* {ga.color(self)}: Attribute {c}::{p} */"
651 end
652 end
653
654 # An element representing a class information
655 class AbsTableEltClass
656 special AbsTableElt
657 # The local class where the information comes from
658 var _local_class: MMLocalClass
659
660 init(c: MMLocalClass)
661 do
662 _local_class = c
663 end
664
665 # The C macro name refering the value
666 fun symbol: String is abstract
667
668 redef fun compile_macros(v, value)
669 do
670 v.add_decl("#define {symbol} ({value})")
671 end
672 end
673
674 # An element of a class table representing a class information
675 class TableEltClass
676 special TableElt
677 special AbsTableEltClass
678 redef fun is_related_to(c)
679 do
680 var bc = c.module[_local_class.global]
681 return c.cshe <= bc
682 end
683 end
684
685 # An element representing the id of a class in a module table
686 class TableEltClassId
687 special ModuleTableElt
688 special AbsTableEltClass
689 redef fun symbol do return _local_class.global.id_id
690
691 redef fun value(ga)
692 do
693 return "{ga.compiled_classes[_local_class.global].id} /* Id of {_local_class} */"
694 end
695 end
696
697 # An element representing the constructor marker position in a class table
698 class TableEltClassInitTable
699 special TableEltClass
700 redef fun symbol do return _local_class.global.init_table_pos_id
701
702 redef fun compile_to_c(v, c)
703 do
704 var ga = v.global_analysis
705 var cc = ga.compiled_classes[_local_class.global]
706 var linext = c.cshe.reverse_linear_extension
707 var i = 0
708 while linext[i].global != _local_class.global do
709 i += 1
710 end
711 return "{i} /* {ga.color(self)}: {c} < {cc.local_class}: superclass init_table position */"
712 end
713 end
714
715 # An element used for a cast
716 # Note: this element is both a TableElt and a ModuleTableElt.
717 # At the TableElt offset, there is the id of the super-class
718 # At the ModuleTableElt offset, there is the TableElt offset (ie. the color of the super-class).
719 class TableEltClassColor
720 special TableEltClass
721 special ModuleTableElt
722 redef fun symbol do return _local_class.global.color_id
723
724 redef fun value(ga)
725 do
726 return "{ga.color(self)} /* Color of {_local_class} */"
727 end
728
729 redef fun compile_to_c(v, c)
730 do
731 var ga = v.global_analysis
732 var cc = ga.compiled_classes[_local_class.global]
733 return "{cc.id} /* {ga.color(self)}: {c} < {cc.local_class}: superclass typecheck marker */"
734 end
735 end
736
737 # A Group of elements introduced in the same global-class that are colored together
738 class TableEltComposite
739 special TableElt
740 var _table: Array[TableElt]
741 var _cc: CompiledClass
742 var _offsets: HashMap[MMLocalClass, Int]
743 redef fun length do return _table.length
744 redef fun is_related_to(c) do return c.cshe <= _cc.local_class
745
746 fun add(c: MMLocalClass, tab: Array[TableElt])
747 do
748 _offsets[c] = _table.length
749 _table.append(tab)
750 end
751
752 redef fun item(i) do return _table[i]
753
754 redef fun compile_to_c(v, c) do abort
755
756 init(cc: CompiledClass)
757 do
758 _cc = cc
759 _table = new Array[TableElt]
760 _offsets = new HashMap[MMLocalClass, Int]
761 end
762 end
763
764 # The element that represent the class id
765 class TableEltClassSelfId
766 special TableElt
767 redef fun is_related_to(c) do return true
768 redef fun compile_to_c(v, c)
769 do
770 var ga = v.global_analysis
771 return "{v.global_analysis.compiled_classes[c.global].id} /* {ga.color(self)}: Identity */"
772 end
773 end
774
775
776 # The element that represent the Object Size
777 class TableEltClassObjectSize
778 special TableElt
779 redef fun is_related_to(c) do return true
780 redef fun compile_to_c(v, c)
781 do
782 var nb = 0
783 var ga = v.global_analysis
784 if c.name == "NativeArray".to_symbol then
785 nb = -1
786 else
787 var cc = ga.compiled_classes[c.global]
788 var itab = cc.instance_table
789 for e in itab do
790 nb += 1
791 end
792 end
793 return "{nb} /* {ga.color(self)}: Object size (-1 if a NativeArray)*/"
794 end
795 end
796
797 # The element that represent the object id
798 class TableEltObjectId
799 special TableElt
800 redef fun is_related_to(c) do return true
801 redef fun compile_to_c(v, c)
802 do
803 var ga = v.global_analysis
804 return "/* {ga.color(self)}: Object_id */"
805 end
806 end
807
808 # The element that
809 class TableEltVftPointer
810 special TableElt
811 redef fun is_related_to(c) do return true
812 redef fun compile_to_c(v, c)
813 do
814 var ga = v.global_analysis
815 return "/* {ga.color(self)}: Pointer to the classtable */"
816 end
817 end
818
819 ###############################################################################
820
821 # Used to sort local class in a deterministic total order
822 # The total order superset the class refinement and the class specialisation relations
823 class ClassSorter
824 special AbstractSorter[MMLocalClass]
825 redef fun compare(a, b) do return a.compare(b)
826 init do end
827 end
828
829 redef class MMLocalClass
830 # Comparaison in a total order that superset the class refinement and the class specialisation relations
831 fun compare(b: MMLocalClass): Int
832 do
833 var a = self
834 if a == b then
835 return 0
836 else if a.module.mhe < b.module then
837 return 1
838 else if b.module.mhe < a.module then
839 return -1
840 end
841 var ar = a.cshe.rank
842 var br = b.cshe.rank
843 if ar > br then
844 return 1
845 else if br > ar then
846 return -1
847 else
848 return b.name.to_s <=> a.name.to_s
849 end
850 end
851
852 # Declaration and macros related to the class table
853 fun declare_tables_to_c(v: GlobalCompilerVisitor)
854 do
855 v.add_decl("")
856 var pi = primitive_info
857 v.add_decl("extern const classtable_elt_t VFT_{name}[];")
858 if name == "NativeArray".to_symbol then
859 v.add_decl("val_t NEW_NativeArray(size_t length, size_t size);")
860 else if pi == null then
861 # v.add_decl("val_t NEW_{name}(void);")
862 else if not pi.tagged then
863 var t = pi.cname
864 var tbox = "struct TBOX_{name}"
865 v.add_decl("{tbox} \{ const classtable_elt_t * vft; bigint object_id; {t} val;};")
866 v.add_decl("val_t BOX_{name}({t} val);")
867 v.add_decl("#define UNBOX_{name}(x) ((({tbox} *)(VAL2OBJ(x)))->val)")
868 end
869 end
870
871 # Compilation of table and new (or box)
872 fun compile_tables_to_c(v: GlobalCompilerVisitor)
873 do
874 var cc = v.global_analysis.compiled_classes[self.global]
875 var ctab = cc.class_table
876 var clen = ctab.length
877 if v.global_analysis.max_class_table_length > ctab.length then
878 clen = v.global_analysis.max_class_table_length
879 end
880
881 v.add_instr("const classtable_elt_t VFT_{name}[{clen}] = \{")
882 v.indent
883 for e in ctab do
884 if e == null then
885 v.add_instr("\{0} /* Class Hole :( */,")
886 else
887 v.add_instr("\{(bigint) {e.compile_to_c(v, self)}},")
888 end
889 end
890 if clen > ctab.length then
891 v.add_instr("\{0},"*(clen-ctab.length))
892 end
893 v.unindent
894 v.add_instr("};")
895 var itab = cc.instance_table
896 for e in itab do
897 if e == null then
898 v.add_instr("/* Instance Hole :( */")
899 else
900 v.add_instr(e.compile_to_c(v, self))
901 end
902 end
903
904 var pi = primitive_info
905 if name == "NativeArray".to_symbol then
906 v.add_instr("val_t NEW_NativeArray(size_t length, size_t size) \{")
907 v.indent
908 v.add_instr("Nit_NativeArray array;")
909 v.add_instr("array = (Nit_NativeArray)alloc(sizeof(struct Nit_NativeArray) + ((length - 1) * size));")
910 v.add_instr("array->vft = (classtable_elt_t*)VFT_{name};")
911 v.add_instr("array->object_id = object_id_counter;")
912 v.add_instr("object_id_counter = object_id_counter + 1;")
913 v.add_instr("array->size = length;")
914 v.add_instr("return OBJ2VAL(array);")
915 v.unindent
916 v.add_instr("}")
917 else if pi == null then
918 do
919 # Generate INIT_ATTRIBUTES routine
920 var iself = new IRegister(get_type)
921 var iselfa = [iself]
922 var iroutine = new IRoutine(iselfa, null)
923 var icb = new ICodeBuilder(module, iroutine)
924
925 for g in global_properties do
926 var p = self[g]
927 var t = p.signature.return_type
928 if p isa MMAttribute and t != null then
929 var ir = p.iroutine
930 if ir == null then continue
931 # FIXME: Not compatible with sep compilation
932 var e = icb.inline_routine(ir, iselfa, null).as(not null)
933 icb.stmt(new IAttrWrite(p, iself, e))
934 end
935 end
936
937 var cname = "INIT_ATTRIBUTES__{name}"
938 var args = iroutine.compile_signature_to_c(v, cname, "init attributes of {name}", null, null)
939 var ctx_old = v.ctx
940 v.ctx = new CContext
941 iroutine.compile_to_c(v, cname, args)
942 ctx_old.append(v.ctx)
943 v.ctx = ctx_old
944 v.unindent
945 v.add_instr("}")
946 end
947 do
948 # Generate NEW routine
949 v.add_decl("val_t NEW_{name}(void);")
950 v.add_instr("val_t NEW_{name}(void)")
951 v.add_instr("\{")
952 v.indent
953 v.add_instr("obj_t obj;")
954 v.add_instr("obj = alloc(sizeof(val_t) * {itab.length});")
955 v.add_instr("obj->vft = (classtable_elt_t*)VFT_{name};")
956 v.add_instr("obj[1].object_id = object_id_counter;")
957 v.add_instr("object_id_counter = object_id_counter + 1;")
958 v.add_instr("return OBJ2VAL(obj);")
959 v.unindent
960 v.add_instr("}")
961 end
962 do
963 # Compile CHECKNAME
964 var iself = new IRegister(get_type)
965 var iselfa = [iself]
966 var iroutine = new IRoutine(iselfa, null)
967 var icb = new ICodeBuilder(module, iroutine)
968 for g in global_properties do
969 var p = self[g]
970 var t = p.signature.return_type
971 if p isa MMAttribute and t != null and not t.is_nullable then
972 icb.add_attr_check(p, iself)
973 end
974 end
975 var cname = "CHECKNEW_{name}"
976 var args = iroutine.compile_signature_to_c(v, cname, "check new {name}", null, null)
977 var ctx_old = v.ctx
978 v.ctx = new CContext
979 iroutine.compile_to_c(v, cname, args)
980 ctx_old.append(v.ctx)
981 v.ctx = ctx_old
982 v.unindent
983 v.add_instr("}")
984 end
985
986 var init_table_size = cshe.greaters.length + 1
987 var init_table_decl = "int init_table[{init_table_size}] = \{0{", 0" * (init_table_size-1)}};"
988
989 for g in global_properties do
990 var p = self[g]
991 # FIXME skip invisible constructors
992 if not p.global.is_init_for(self) then continue
993 assert p isa MMMethod
994
995 var iself = new IRegister(get_type)
996 var iparams = new Array[IRegister]
997 for i in [0..p.signature.arity[ do iparams.add(new IRegister(p.signature[i]))
998 var iroutine = new IRoutine(iparams, iself)
999 iroutine.location = p.iroutine.location
1000 var icb = new ICodeBuilder(module, iroutine)
1001
1002 var inew = new IAllocateInstance(get_type)
1003 inew.result = iself
1004 icb.stmt(inew)
1005 var iargs = [iself]
1006 iargs.add_all(iparams)
1007
1008 icb.stmt(new IInitAttributes(get_type, iself))
1009 icb.stmt(new IStaticCall(p, iargs))
1010 icb.stmt(new ICheckInstance(get_type, iself))
1011
1012 var cname = "NEW_{self}_{p.global.intro.cname}"
1013 var new_args = iroutine.compile_signature_to_c(v, cname, "new {self} {p.full_name}", null, null)
1014 var ctx_old = v.ctx
1015 v.ctx = new CContext
1016 v.add_instr(init_table_decl)
1017 var e = iroutine.compile_to_c(v, cname, new_args).as(not null)
1018 v.add_instr("return {e};")
1019 ctx_old.append(v.ctx)
1020 v.ctx = ctx_old
1021 v.unindent
1022 v.add_instr("}")
1023 end
1024 else if not pi.tagged then
1025 var t = pi.cname
1026 var tbox = "struct TBOX_{name}"
1027 v.add_instr("val_t BOX_{name}({t} val) \{")
1028 v.indent
1029 v.add_instr("{tbox} *box = ({tbox}*)alloc(sizeof({tbox}));")
1030 v.add_instr("box->vft = VFT_{name};")
1031 v.add_instr("box->val = val;")
1032 v.add_instr("box->object_id = object_id_counter;")
1033 v.add_instr("object_id_counter = object_id_counter + 1;")
1034 v.add_instr("return OBJ2VAL(box);")
1035 v.unindent
1036 v.add_instr("}")
1037 end
1038 end
1039 end
1040
1041 redef class MMMethod
1042 fun compile_property_to_c(v: CompilerVisitor)
1043 do
1044 var ir = iroutine
1045 assert ir != null
1046
1047 var more_params: nullable String = null
1048 if global.is_init then more_params = "int* init_table"
1049 var args = ir.compile_signature_to_c(v, cname, full_name, null, more_params)
1050 var ctx_old = v.ctx
1051 v.ctx = new CContext
1052
1053 v.out_contexts.clear
1054
1055 var itpos: nullable String = null
1056 if global.is_init then
1057 itpos = "itpos{v.new_number}"
1058 v.add_decl("int {itpos} = VAL2OBJ({args.first})->vft[{local_class.global.init_table_pos_id}].i;")
1059 v.add_instr("if (init_table[{itpos}]) return;")
1060 end
1061
1062 var s = ir.compile_to_c(v, cname, args)
1063
1064 if itpos != null then
1065 v.add_instr("init_table[{itpos}] = 1;")
1066 end
1067 if s == null then
1068 v.add_instr("return;")
1069 else
1070 v.add_instr("return ", s, ";")
1071 end
1072
1073 ctx_old.append(v.ctx)
1074 v.ctx = ctx_old
1075 v.unindent
1076 v.add_instr("}")
1077
1078 for ctx in v.out_contexts do v.ctx.merge(ctx)
1079 end
1080 end
1081