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