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