1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2008 Jean Privat <jean@pryen.org>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # Compute and generate tables for classes and modules.
18 package compiling_global
20 import table_computation
21 private import compiling_icode
23 class GlobalCompilerVisitor
24 special CompilerVisitor
25 # The global analysis result
26 readable var _program
: Program
27 init(m
: MMModule, tc
: ToolContext, prog
: Program)
35 # Compile module and class tables
36 fun compile_tables_to_c
(v
: GlobalCompilerVisitor)
38 for m
in module.mhe
.greaters_and_self
do
39 m
.compile_local_table_to_c
(v
)
42 for c
in module.local_classes
do
43 c
.compile_tables_to_c
(v
)
45 var s
= new Buffer.from
("classtable_t TAG2VFT[4] = \{NULL")
46 for t
in ["Int","Char","Bool"] do
47 if module.has_global_class_named
(t
.to_symbol
) then
48 s
.append
(", (const classtable_t)VFT_{t}")
57 # Compile main part (for _table.c)
58 fun compile_main_part
(v
: GlobalCompilerVisitor)
60 v
.add_instr
("int main(int argc, char **argv) \{")
62 v
.add_instr
("prepare_signals();")
63 v
.add_instr
("glob_argc = argc; glob_argv = argv;")
64 if v
.program
.main_method
== null then
67 v
.add_instr
("G_sys = NEW_Sys();")
68 v
.add_instr
("register_static_object(&G_sys);")
69 v
.add_instr
("{v.program.main_method.cname}(G_sys);")
71 v
.add_instr
("return 0;")
78 # Declare class table (for _sep.h)
79 fun declare_class_tables_to_c
(v
: GlobalCompilerVisitor)
81 for c
in local_classes
do
82 if c
.global
.module == self then
83 c
.declare_tables_to_c
(v
)
89 fun compile_mod_to_c
(v
: GlobalCompilerVisitor)
91 v
.add_decl
("extern const char *LOCATE_{name};")
92 if not v
.tc
.global
then
93 v
.add_decl
("extern const int SFT_{name}[];")
96 for e
in local_table
do
99 value
= "{e.value(v.program)}"
101 value
= "SFT_{name}[{i}]"
104 e
.compile_macros
(v
, value
)
106 for c
in local_classes
do
107 if not c
isa MMConcreteClass then continue
108 for pg
in c
.global_properties
do
110 if p
.local_class
== c
and p
isa MMMethod then
111 p
.compile_property_to_c
(v
)
113 if pg
.is_init_for
(c
) then
114 # Declare constructors
115 var params
= new Array[String]
116 for j
in [0..p
.signature
.arity
[ do
117 params
.add
("val_t p{j}")
119 v
.add_decl
("val_t NEW_{c}_{p.global.intro.cname}({params.join(", ")});")
125 # Compile module file for the current module
126 fun compile_local_table_to_c
(v
: GlobalCompilerVisitor)
128 v
.add_instr
("const char *LOCATE_{name} = \"{location.file}\
";")
130 if v
.tc
.global
or local_table
.is_empty
then
134 v
.add_instr
("const int SFT_{name}[{local_table.length}] = \{")
136 for e
in local_table
do
137 v
.add_instr
(e
.value
(v
.program
) + ",")
144 ###############################################################################
146 redef class AbsTableElt
147 # Compile the macro needed to use the element and other related elements
148 fun compile_macros
(v
: GlobalCompilerVisitor, value
: String) is abstract
152 # Return the value of the element for a given class
153 fun compile_to_c
(v
: GlobalCompilerVisitor, c
: MMLocalClass): String is abstract
156 redef class ModuleTableElt
157 # Return the value of the element once the global analisys is performed
158 fun value
(prog
: Program): String is abstract
161 redef class ModuleTableEltGroup
162 redef fun value
(prog
) do return "{prog.table_information.color(elements.first)} /* Group of ? */"
163 redef fun compile_macros
(v
, value
)
167 e
.compile_macros
(v
, "{value} + {i}")
173 redef class TableEltMeth
174 redef fun compile_macros
(v
, value
)
176 var pg
= property
.global
177 v
.add_decl
("#define {pg.meth_call}(recv) (({pg.intro.cname}_t)CALL((recv), ({value})))")
180 redef fun compile_to_c
(v
, c
)
182 var p
= c
[property
.global
]
187 redef class TableEltSuper
188 redef fun compile_macros
(v
, value
)
191 v
.add_decl
("#define {p.super_meth_call}(recv) (({p.cname}_t)CALL((recv), ({value})))")
194 redef fun compile_to_c
(v
, c
)
196 var pc
= property
.local_class
197 var g
= property
.global
198 var lin
= c
.che
.linear_extension
201 #print "{c.module}::{c} for {pc.module}::{pc}::{_property} try {s.module}:{s}"
204 else if found
and c
.che
< s
then
205 if s
.has_global_property
(g
) then
206 #print "found {s.module}::{s}::{p}"
215 redef class TableEltAttr
216 redef fun compile_macros
(v
, value
)
218 var pg
= property
.global
219 v
.add_decl
("#define {pg.attr_access}(recv) ATTR(recv, ({value}))")
222 redef fun compile_to_c
(v
, c
)
225 var p
= c
[property
.global
]
226 return "/* {prog.table_information.color(self)}: Attribute {c}::{p} */"
230 redef class AbsTableEltClass
231 # The C macro name refering the value
232 fun symbol
: String is abstract
234 redef fun compile_macros
(v
, value
)
236 v
.add_decl
("#define {symbol} ({value})")
240 redef class TableEltClassId
241 redef fun symbol
do return local_class
.global
.id_id
243 redef fun value
(prog
)
245 return "{prog.compiled_classes[local_class.global].id} /* Id of {local_class} */"
249 redef class TableEltClassInitTable
250 redef fun symbol
do return local_class
.global
.init_table_pos_id
252 redef fun compile_to_c
(v
, c
)
255 var cc
= prog
.compiled_classes
[local_class
.global
]
256 var linext
= c
.cshe
.reverse_linear_extension
258 while linext
[i
].global
!= local_class
.global
do
261 return "{i} /* {prog.table_information.color(self)}: {c} < {cc.local_class}: superclass init_table position */"
265 redef class TableEltClassColor
266 redef fun symbol
do return local_class
.global
.color_id
268 redef fun value
(prog
)
270 return "{prog.table_information.color(self)} /* Color of {local_class} */"
273 redef fun compile_to_c
(v
, c
)
276 var cc
= prog
.compiled_classes
[local_class
.global
]
277 return "{cc.id} /* {prog.table_information.color(self)}: {c} < {cc.local_class}: superclass typecheck marker */"
281 redef class TableEltComposite
282 redef fun compile_to_c
(v
, c
) do abort
285 redef class TableEltClassSelfId
286 redef fun compile_to_c
(v
, c
)
289 return "{prog.compiled_classes[c.global].id} /* {prog.table_information.color(self)}: Identity */"
293 redef class TableEltClassObjectSize
294 redef fun compile_to_c
(v
, c
)
298 if c
.name
== "NativeArray".to_symbol
then
301 var cc
= p
.compiled_classes
[c
.global
]
302 var itab
= cc
.instance_table
307 return "{nb} /* {p.table_information.color(self)}: Object size (-1 if a NativeArray)*/"
311 redef class TableEltObjectId
312 redef fun compile_to_c
(v
, c
)
315 return "/* {p.table_information.color(self)}: Object_id */"
319 redef class TableEltVftPointer
320 redef fun compile_to_c
(v
, c
)
323 return "/* {prog.table_information.color(self)}: Pointer to the classtable */"
327 ###############################################################################
329 redef class MMLocalClass
330 # IRoutine for the initialization of the default attributes (called by IInitAttributes)
331 var _init_var_iroutine
: nullable IRoutine = null
332 # IRoutine to validate the instance after initialization (called by ICheckInstance)
333 var _checknew_iroutine
: nullable IRoutine = null
334 # IRoutines to call to create a new valid instance (memory allocated, object initialized and validated)
335 # These iroutines will call: IAllocateInstance, IInitAttributes, some init function and ICheckInstance
336 # These routines will be called by INew
337 var _new_instance_iroutine
: HashMap[MMMethod, IRoutine] = new HashMap[MMMethod, IRoutine]
339 # Declaration and macros related to the class table
340 fun declare_tables_to_c
(v
: GlobalCompilerVisitor)
343 var pi
= primitive_info
344 v
.add_decl
("extern const classtable_elt_t VFT_{name}[];")
345 if name
== "NativeArray".to_symbol
then
346 v
.add_decl
("val_t NEW_NativeArray(size_t length, size_t size);")
347 else if pi
== null then
348 # v.add_decl("val_t NEW_{name}(void);")
349 else if not pi
.tagged
then
351 var tbox
= "struct TBOX_{name}"
352 v
.add_decl
("{tbox} \{ const classtable_elt_t * vft; bigint object_id; {t} val;};")
353 v
.add_decl
("val_t BOX_{name}({t} val);")
354 v
.add_decl
("#define UNBOX_{name}(x) ((({tbox} *)(VAL2OBJ(x)))->val)")
358 # Generation of allocation function of this class
359 fun generate_allocation_iroutines
(prog
: Program)
361 var cc
= prog
.compiled_classes
[self.global
]
363 var pi
= primitive_info
366 # Generate INIT_ATTRIBUTES routine
367 var iself
= new IRegister(get_type
)
369 var iroutine
= new IRoutine(iselfa
, null)
370 var icb
= new ICodeBuilder(module, iroutine
)
372 for g
in global_properties
do
374 var t
= p
.signature
.return_type
375 if p
isa MMAttribute and t
!= null then
377 if ir
== null then continue
378 # FIXME: Not compatible with sep compilation
379 var e
= icb
.inline_routine
(ir
, iselfa
, null).as(not null)
380 icb
.stmt
(new IAttrWrite(p
, iself
, e
))
384 _init_var_iroutine
= iroutine
388 var iself
= new IRegister(get_type
)
390 var iroutine
= new IRoutine(iselfa
, null)
391 var icb
= new ICodeBuilder(module, iroutine
)
392 for g
in global_properties
do
394 var t
= p
.signature
.return_type
395 if p
isa MMAttribute and t
!= null and not t
.is_nullable
then
396 icb
.add_attr_check
(p
, iself
)
400 _checknew_iroutine
= iroutine
403 var init_table_size
= cshe
.greaters
.length
+ 1
405 for g
in global_properties
do
407 # FIXME skip invisible constructors
408 if not p
.global
.is_init_for
(self) then continue
409 assert p
isa MMMethod
411 var iself
= new IRegister(get_type
)
412 var iparams
= new Array[IRegister]
413 for i
in [0..p
.signature
.arity
[ do iparams
.add
(new IRegister(p
.signature
[i
]))
414 var iroutine
= new IRoutine(iparams
, iself
)
415 iroutine
.location
= p
.iroutine
.location
416 var icb
= new ICodeBuilder(module, iroutine
)
418 var inew
= new IAllocateInstance(get_type
)
422 iargs
.add_all
(iparams
)
424 icb
.stmt
(new IInitAttributes(get_type
, iself
))
425 icb
.stmt
(new IStaticCall(p
, iargs
))
426 icb
.stmt
(new ICheckInstance(get_type
, iself
))
428 _new_instance_iroutine
[p
] = iroutine
433 # Compilation of table and new (or box)
434 fun compile_tables_to_c
(v
: GlobalCompilerVisitor)
436 var cc
= v
.program
.compiled_classes
[self.global
]
437 var ctab
= cc
.class_table
438 var clen
= ctab
.length
439 if v
.program
.table_information
.max_class_table_length
> ctab
.length
then
440 clen
= v
.program
.table_information
.max_class_table_length
443 v
.add_instr
("const classtable_elt_t VFT_{name}[{clen}] = \{")
447 v
.add_instr
("\{0} /* Class Hole :( */,")
449 v
.add_instr
("\{(bigint) {e.compile_to_c(v, self)}},")
452 if clen
> ctab
.length
then
453 v
.add_instr
("\{0},"*(clen-ctab
.length
))
457 var itab
= cc
.instance_table
460 v
.add_instr
("/* Instance Hole :( */")
462 v
.add_instr
(e
.compile_to_c
(v
, self))
466 var pi
= primitive_info
467 if name
== "NativeArray".to_symbol
then
468 v
.add_instr
("val_t NEW_NativeArray(size_t length, size_t size) \{")
470 v
.add_instr
("Nit_NativeArray array;")
471 v
.add_instr
("array = (Nit_NativeArray)alloc(sizeof(struct Nit_NativeArray) + ((length - 1) * size));")
472 v
.add_instr
("array->vft = (classtable_elt_t*)VFT_{name};")
473 v
.add_instr
("array->object_id = object_id_counter;")
474 v
.add_instr
("object_id_counter = object_id_counter + 1;")
475 v
.add_instr
("array->size = length;")
476 v
.add_instr
("return OBJ2VAL(array);")
479 else if pi
== null then
481 # Generate INIT_ATTRIBUTES routine
482 var cname
= "INIT_ATTRIBUTES__{name}"
483 var args
= _init_var_iroutine
.compile_signature_to_c
(v
, cname
, "init var of {name}", null, null)
486 _init_var_iroutine
.compile_to_c
(v
, cname
, args
)
487 ctx_old
.append
(v
.ctx
)
493 # Generate NEW routine
494 v
.add_decl
("val_t NEW_{name}(void);")
495 v
.add_instr
("val_t NEW_{name}(void)")
498 v
.add_instr
("obj_t obj;")
499 v
.add_instr
("obj = alloc(sizeof(val_t) * {itab.length});")
500 v
.add_instr
("obj->vft = (classtable_elt_t*)VFT_{name};")
501 v
.add_instr
("obj[1].object_id = object_id_counter;")
502 v
.add_instr
("object_id_counter = object_id_counter + 1;")
503 v
.add_instr
("return OBJ2VAL(obj);")
509 var cname
= "CHECKNEW_{name}"
510 var args
= _checknew_iroutine
.compile_signature_to_c
(v
, cname
, "check new {name}", null, null)
513 _checknew_iroutine
.compile_to_c
(v
, cname
, args
)
514 ctx_old
.append
(v
.ctx
)
520 var init_table_size
= cshe
.greaters
.length
+ 1
521 var init_table_decl
= "int init_table[{init_table_size}] = \{0{", 0" * (init_table_size-1)}};"
523 for g
in global_properties
do
525 # FIXME skip invisible constructors
526 if not p
.global
.is_init_for
(self) then continue
527 assert p
isa MMMethod
529 var cname
= "NEW_{self}_{p.global.intro.cname}"
530 var new_args
= _new_instance_iroutine
[p
].compile_signature_to_c
(v
, cname
, "new {self} {p.full_name}", null, null)
533 v
.add_instr
(init_table_decl
)
534 var e
= _new_instance_iroutine
[p
].compile_to_c
(v
, cname
, new_args
).as(not null)
535 v
.add_instr
("return {e};")
536 ctx_old
.append
(v
.ctx
)
541 else if not pi
.tagged
then
543 var tbox
= "struct TBOX_{name}"
544 v
.add_instr
("val_t BOX_{name}({t} val) \{")
546 v
.add_instr
("{tbox} *box = ({tbox}*)alloc(sizeof({tbox}));")
547 v
.add_instr
("box->vft = VFT_{name};")
548 v
.add_instr
("box->val = val;")
549 v
.add_instr
("box->object_id = object_id_counter;")
550 v
.add_instr
("object_id_counter = object_id_counter + 1;")
551 v
.add_instr
("return OBJ2VAL(box);")
559 fun compile_property_to_c
(v
: CompilerVisitor)
564 var more_params
: nullable String = null
565 if global
.is_init
then more_params
= "int* init_table"
566 var args
= ir
.compile_signature_to_c
(v
, cname
, full_name
, null, more_params
)
572 var itpos
: nullable String = null
573 if global
.is_init
then
574 itpos
= "itpos{v.new_number}"
575 v
.add_decl
("int {itpos} = VAL2OBJ({args.first})->vft[{local_class.global.init_table_pos_id}].i;")
576 v
.add_instr
("if (init_table[{itpos}]) return;")
579 var s
= ir
.compile_to_c
(v
, cname
, args
)
581 if itpos
!= null then
582 v
.add_instr
("init_table[{itpos}] = 1;")
585 v
.add_instr
("return;")
587 v
.add_instr
("return ", s
, ";")
590 ctx_old
.append
(v
.ctx
)
595 for ctx
in v
.out_contexts
do v
.ctx
.merge
(ctx
)