compile: generate classes init iroutines sooner to insert global analysis
[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 table_computation
21 private import compiling_icode
22
23 class GlobalCompilerVisitor
24 special CompilerVisitor
25 # The global analysis result
26 readable var _program: Program
27 init(m: MMModule, tc: ToolContext, prog: Program)
28 do
29 super(m, tc)
30 _program = prog
31 end
32 end
33
34 redef class Program
35 # Compile module and class tables
36 fun compile_tables_to_c(v: GlobalCompilerVisitor)
37 do
38 for m in module.mhe.greaters_and_self do
39 m.compile_local_table_to_c(v)
40 end
41
42 for c in module.local_classes do
43 c.compile_tables_to_c(v)
44 end
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}")
49 else
50 s.append(", NULL")
51 end
52 end
53 s.append("};")
54 v.add_instr(s.to_s)
55 end
56
57 # Compile main part (for _table.c)
58 fun compile_main_part(v: GlobalCompilerVisitor)
59 do
60 v.add_instr("int main(int argc, char **argv) \{")
61 v.indent
62 v.add_instr("prepare_signals();")
63 v.add_instr("glob_argc = argc; glob_argv = argv;")
64 var sysname = once "Sys".to_symbol
65 if not module.has_global_class_named(sysname) then
66 print("No main")
67 else
68 var sys = module.class_by_name(sysname)
69 var name = once "main".to_symbol
70 if not sys.has_global_property_by_name(name) then
71 print("No main")
72 else
73 var mainm = sys.select_method(name)
74 v.add_instr("G_sys = NEW_Sys();")
75 v.add_instr("register_static_object(&G_sys);")
76 v.add_instr("{mainm.cname}(G_sys);")
77 end
78 end
79 v.add_instr("return 0;")
80 v.unindent
81 v.add_instr("}")
82 end
83 end
84
85 redef class MMModule
86 # Declare class table (for _sep.h)
87 fun declare_class_tables_to_c(v: GlobalCompilerVisitor)
88 do
89 for c in local_classes do
90 if c.global.module == self then
91 c.declare_tables_to_c(v)
92 end
93 end
94 end
95
96 # Compile sep files
97 fun compile_mod_to_c(v: GlobalCompilerVisitor)
98 do
99 v.add_decl("extern const char *LOCATE_{name};")
100 if not v.tc.global then
101 v.add_decl("extern const int SFT_{name}[];")
102 end
103 var i = 0
104 for e in local_table do
105 var value: String
106 if v.tc.global then
107 value = "{e.value(v.program)}"
108 else
109 value = "SFT_{name}[{i}]"
110 i = i + 1
111 end
112 e.compile_macros(v, value)
113 end
114 for c in local_classes do
115 if not c isa MMConcreteClass then continue
116 for pg in c.global_properties do
117 var p = c[pg]
118 if p.local_class == c and p isa MMMethod then
119 p.compile_property_to_c(v)
120 end
121 if pg.is_init_for(c) then
122 # Declare constructors
123 var params = new Array[String]
124 for j in [0..p.signature.arity[ do
125 params.add("val_t p{j}")
126 end
127 v.add_decl("val_t NEW_{c}_{p.global.intro.cname}({params.join(", ")});")
128 end
129 end
130 end
131 end
132
133 # Compile module file for the current module
134 fun compile_local_table_to_c(v: GlobalCompilerVisitor)
135 do
136 v.add_instr("const char *LOCATE_{name} = \"{location.file}\";")
137
138 if v.tc.global or local_table.is_empty then
139 return
140 end
141
142 v.add_instr("const int SFT_{name}[{local_table.length}] = \{")
143 v.indent
144 for e in local_table do
145 v.add_instr(e.value(v.program) + ",")
146 end
147 v.unindent
148 v.add_instr("\};")
149 end
150 end
151
152 ###############################################################################
153
154 redef class AbsTableElt
155 # Compile the macro needed to use the element and other related elements
156 fun compile_macros(v: GlobalCompilerVisitor, value: String) is abstract
157 end
158
159 redef class TableElt
160 # Return the value of the element for a given class
161 fun compile_to_c(v: GlobalCompilerVisitor, c: MMLocalClass): String is abstract
162 end
163
164 redef class ModuleTableElt
165 # Return the value of the element once the global analisys is performed
166 fun value(prog: Program): String is abstract
167 end
168
169 redef class ModuleTableEltGroup
170 redef fun value(prog) do return "{prog.table_information.color(elements.first)} /* Group of ? */"
171 redef fun compile_macros(v, value)
172 do
173 var i = 0
174 for e in elements do
175 e.compile_macros(v, "{value} + {i}")
176 i += 1
177 end
178 end
179 end
180
181 redef class TableEltMeth
182 redef fun compile_macros(v, value)
183 do
184 var pg = property.global
185 v.add_decl("#define {pg.meth_call}(recv) (({pg.intro.cname}_t)CALL((recv), ({value})))")
186 end
187
188 redef fun compile_to_c(v, c)
189 do
190 var p = c[property.global]
191 return p.cname
192 end
193 end
194
195 redef class TableEltSuper
196 redef fun compile_macros(v, value)
197 do
198 var p = property
199 v.add_decl("#define {p.super_meth_call}(recv) (({p.cname}_t)CALL((recv), ({value})))")
200 end
201
202 redef fun compile_to_c(v, c)
203 do
204 var pc = property.local_class
205 var g = property.global
206 var lin = c.che.linear_extension
207 var found = false
208 for s in lin do
209 #print "{c.module}::{c} for {pc.module}::{pc}::{_property} try {s.module}:{s}"
210 if s == pc then
211 found = true
212 else if found and c.che < s then
213 if s.has_global_property(g) then
214 #print "found {s.module}::{s}::{p}"
215 return s[g].cname
216 end
217 end
218 end
219 abort
220 end
221 end
222
223 redef class TableEltAttr
224 redef fun compile_macros(v, value)
225 do
226 var pg = property.global
227 v.add_decl("#define {pg.attr_access}(recv) ATTR(recv, ({value}))")
228 end
229
230 redef fun compile_to_c(v, c)
231 do
232 var prog = v.program
233 var p = c[property.global]
234 return "/* {prog.table_information.color(self)}: Attribute {c}::{p} */"
235 end
236 end
237
238 redef class AbsTableEltClass
239 # The C macro name refering the value
240 fun symbol: String is abstract
241
242 redef fun compile_macros(v, value)
243 do
244 v.add_decl("#define {symbol} ({value})")
245 end
246 end
247
248 redef class TableEltClassId
249 redef fun symbol do return local_class.global.id_id
250
251 redef fun value(prog)
252 do
253 return "{prog.compiled_classes[local_class.global].id} /* Id of {local_class} */"
254 end
255 end
256
257 redef class TableEltClassInitTable
258 redef fun symbol do return local_class.global.init_table_pos_id
259
260 redef fun compile_to_c(v, c)
261 do
262 var prog = v.program
263 var cc = prog.compiled_classes[local_class.global]
264 var linext = c.cshe.reverse_linear_extension
265 var i = 0
266 while linext[i].global != local_class.global do
267 i += 1
268 end
269 return "{i} /* {prog.table_information.color(self)}: {c} < {cc.local_class}: superclass init_table position */"
270 end
271 end
272
273 redef class TableEltClassColor
274 redef fun symbol do return local_class.global.color_id
275
276 redef fun value(prog)
277 do
278 return "{prog.table_information.color(self)} /* Color of {local_class} */"
279 end
280
281 redef fun compile_to_c(v, c)
282 do
283 var prog = v.program
284 var cc = prog.compiled_classes[local_class.global]
285 return "{cc.id} /* {prog.table_information.color(self)}: {c} < {cc.local_class}: superclass typecheck marker */"
286 end
287 end
288
289 redef class TableEltComposite
290 redef fun compile_to_c(v, c) do abort
291 end
292
293 redef class TableEltClassSelfId
294 redef fun compile_to_c(v, c)
295 do
296 var prog = v.program
297 return "{prog.compiled_classes[c.global].id} /* {prog.table_information.color(self)}: Identity */"
298 end
299 end
300
301 redef class TableEltClassObjectSize
302 redef fun compile_to_c(v, c)
303 do
304 var nb = 0
305 var p = v.program
306 if c.name == "NativeArray".to_symbol then
307 nb = -1
308 else
309 var cc = p.compiled_classes[c.global]
310 var itab = cc.instance_table
311 for e in itab do
312 nb += 1
313 end
314 end
315 return "{nb} /* {p.table_information.color(self)}: Object size (-1 if a NativeArray)*/"
316 end
317 end
318
319 redef class TableEltObjectId
320 redef fun compile_to_c(v, c)
321 do
322 var p = v.program
323 return "/* {p.table_information.color(self)}: Object_id */"
324 end
325 end
326
327 redef class TableEltVftPointer
328 redef fun compile_to_c(v, c)
329 do
330 var prog = v.program
331 return "/* {prog.table_information.color(self)}: Pointer to the classtable */"
332 end
333 end
334
335 ###############################################################################
336
337 redef class MMLocalClass
338 # IRoutine for the initialization of the default attributes (called by IInitAttributes)
339 var _init_var_iroutine: nullable IRoutine = null
340 # IRoutine to validate the instance after initialization (called by ICheckInstance)
341 var _checknew_iroutine: nullable IRoutine = null
342 # IRoutines to call to create a new valid instance (memory allocated, object initialized and validated)
343 # These iroutines will call: IAllocateInstance, IInitAttributes, some init function and ICheckInstance
344 # These routines will be called by INew
345 var _new_instance_iroutine: HashMap[MMMethod, IRoutine] = new HashMap[MMMethod, IRoutine]
346
347 # Declaration and macros related to the class table
348 fun declare_tables_to_c(v: GlobalCompilerVisitor)
349 do
350 v.add_decl("")
351 var pi = primitive_info
352 v.add_decl("extern const classtable_elt_t VFT_{name}[];")
353 if name == "NativeArray".to_symbol then
354 v.add_decl("val_t NEW_NativeArray(size_t length, size_t size);")
355 else if pi == null then
356 # v.add_decl("val_t NEW_{name}(void);")
357 else if not pi.tagged then
358 var t = pi.cname
359 var tbox = "struct TBOX_{name}"
360 v.add_decl("{tbox} \{ const classtable_elt_t * vft; bigint object_id; {t} val;};")
361 v.add_decl("val_t BOX_{name}({t} val);")
362 v.add_decl("#define UNBOX_{name}(x) ((({tbox} *)(VAL2OBJ(x)))->val)")
363 end
364 end
365
366 # Generation of allocation function of this class
367 fun generate_allocation_iroutines(prog: Program)
368 do
369 var cc = prog.compiled_classes[self.global]
370
371 var pi = primitive_info
372 if pi == null then
373 do
374 # Generate INIT_ATTRIBUTES routine
375 var iself = new IRegister(get_type)
376 var iselfa = [iself]
377 var iroutine = new IRoutine(iselfa, null)
378 var icb = new ICodeBuilder(module, iroutine)
379
380 for g in global_properties do
381 var p = self[g]
382 var t = p.signature.return_type
383 if p isa MMAttribute and t != null then
384 var ir = p.iroutine
385 if ir == null then continue
386 # FIXME: Not compatible with sep compilation
387 var e = icb.inline_routine(ir, iselfa, null).as(not null)
388 icb.stmt(new IAttrWrite(p, iself, e))
389 end
390 end
391
392 _init_var_iroutine = iroutine
393 end
394 do
395 # Compile CHECKNAME
396 var iself = new IRegister(get_type)
397 var iselfa = [iself]
398 var iroutine = new IRoutine(iselfa, null)
399 var icb = new ICodeBuilder(module, iroutine)
400 for g in global_properties do
401 var p = self[g]
402 var t = p.signature.return_type
403 if p isa MMAttribute and t != null and not t.is_nullable then
404 icb.add_attr_check(p, iself)
405 end
406 end
407
408 _checknew_iroutine = iroutine
409 end
410
411 var init_table_size = cshe.greaters.length + 1
412
413 for g in global_properties do
414 var p = self[g]
415 # FIXME skip invisible constructors
416 if not p.global.is_init_for(self) then continue
417 assert p isa MMMethod
418
419 var iself = new IRegister(get_type)
420 var iparams = new Array[IRegister]
421 for i in [0..p.signature.arity[ do iparams.add(new IRegister(p.signature[i]))
422 var iroutine = new IRoutine(iparams, iself)
423 iroutine.location = p.iroutine.location
424 var icb = new ICodeBuilder(module, iroutine)
425
426 var inew = new IAllocateInstance(get_type)
427 inew.result = iself
428 icb.stmt(inew)
429 var iargs = [iself]
430 iargs.add_all(iparams)
431
432 icb.stmt(new IInitAttributes(get_type, iself))
433 icb.stmt(new IStaticCall(p, iargs))
434 icb.stmt(new ICheckInstance(get_type, iself))
435
436 _new_instance_iroutine[p] = iroutine
437 end
438 end
439 end
440
441 # Compilation of table and new (or box)
442 fun compile_tables_to_c(v: GlobalCompilerVisitor)
443 do
444 var cc = v.program.compiled_classes[self.global]
445 var ctab = cc.class_table
446 var clen = ctab.length
447 if v.program.table_information.max_class_table_length > ctab.length then
448 clen = v.program.table_information.max_class_table_length
449 end
450
451 v.add_instr("const classtable_elt_t VFT_{name}[{clen}] = \{")
452 v.indent
453 for e in ctab do
454 if e == null then
455 v.add_instr("\{0} /* Class Hole :( */,")
456 else
457 v.add_instr("\{(bigint) {e.compile_to_c(v, self)}},")
458 end
459 end
460 if clen > ctab.length then
461 v.add_instr("\{0},"*(clen-ctab.length))
462 end
463 v.unindent
464 v.add_instr("};")
465 var itab = cc.instance_table
466 for e in itab do
467 if e == null then
468 v.add_instr("/* Instance Hole :( */")
469 else
470 v.add_instr(e.compile_to_c(v, self))
471 end
472 end
473
474 var pi = primitive_info
475 if name == "NativeArray".to_symbol then
476 v.add_instr("val_t NEW_NativeArray(size_t length, size_t size) \{")
477 v.indent
478 v.add_instr("Nit_NativeArray array;")
479 v.add_instr("array = (Nit_NativeArray)alloc(sizeof(struct Nit_NativeArray) + ((length - 1) * size));")
480 v.add_instr("array->vft = (classtable_elt_t*)VFT_{name};")
481 v.add_instr("array->object_id = object_id_counter;")
482 v.add_instr("object_id_counter = object_id_counter + 1;")
483 v.add_instr("array->size = length;")
484 v.add_instr("return OBJ2VAL(array);")
485 v.unindent
486 v.add_instr("}")
487 else if pi == null then
488 do
489 # Generate INIT_ATTRIBUTES routine
490 var cname = "INIT_ATTRIBUTES__{name}"
491 var args = _init_var_iroutine.compile_signature_to_c(v, cname, "init var of {name}", null, null)
492 var ctx_old = v.ctx
493 v.ctx = new CContext
494 _init_var_iroutine.compile_to_c(v, cname, args)
495 ctx_old.append(v.ctx)
496 v.ctx = ctx_old
497 v.unindent
498 v.add_instr("}")
499 end
500 do
501 # Generate NEW routine
502 v.add_decl("val_t NEW_{name}(void);")
503 v.add_instr("val_t NEW_{name}(void)")
504 v.add_instr("\{")
505 v.indent
506 v.add_instr("obj_t obj;")
507 v.add_instr("obj = alloc(sizeof(val_t) * {itab.length});")
508 v.add_instr("obj->vft = (classtable_elt_t*)VFT_{name};")
509 v.add_instr("obj[1].object_id = object_id_counter;")
510 v.add_instr("object_id_counter = object_id_counter + 1;")
511 v.add_instr("return OBJ2VAL(obj);")
512 v.unindent
513 v.add_instr("}")
514 end
515 do
516 # Compile CHECKNAME
517 var cname = "CHECKNEW_{name}"
518 var args = _checknew_iroutine.compile_signature_to_c(v, cname, "check new {name}", null, null)
519 var ctx_old = v.ctx
520 v.ctx = new CContext
521 _checknew_iroutine.compile_to_c(v, cname, args)
522 ctx_old.append(v.ctx)
523 v.ctx = ctx_old
524 v.unindent
525 v.add_instr("}")
526 end
527
528 var init_table_size = cshe.greaters.length + 1
529 var init_table_decl = "int init_table[{init_table_size}] = \{0{", 0" * (init_table_size-1)}};"
530
531 for g in global_properties do
532 var p = self[g]
533 # FIXME skip invisible constructors
534 if not p.global.is_init_for(self) then continue
535 assert p isa MMMethod
536
537 var cname = "NEW_{self}_{p.global.intro.cname}"
538 var new_args = _new_instance_iroutine[p].compile_signature_to_c(v, cname, "new {self} {p.full_name}", null, null)
539 var ctx_old = v.ctx
540 v.ctx = new CContext
541 v.add_instr(init_table_decl)
542 var e = _new_instance_iroutine[p].compile_to_c(v, cname, new_args).as(not null)
543 v.add_instr("return {e};")
544 ctx_old.append(v.ctx)
545 v.ctx = ctx_old
546 v.unindent
547 v.add_instr("}")
548 end
549 else if not pi.tagged then
550 var t = pi.cname
551 var tbox = "struct TBOX_{name}"
552 v.add_instr("val_t BOX_{name}({t} val) \{")
553 v.indent
554 v.add_instr("{tbox} *box = ({tbox}*)alloc(sizeof({tbox}));")
555 v.add_instr("box->vft = VFT_{name};")
556 v.add_instr("box->val = val;")
557 v.add_instr("box->object_id = object_id_counter;")
558 v.add_instr("object_id_counter = object_id_counter + 1;")
559 v.add_instr("return OBJ2VAL(box);")
560 v.unindent
561 v.add_instr("}")
562 end
563 end
564 end
565
566 redef class MMMethod
567 fun compile_property_to_c(v: CompilerVisitor)
568 do
569 var ir = iroutine
570 assert ir != null
571
572 var more_params: nullable String = null
573 if global.is_init then more_params = "int* init_table"
574 var args = ir.compile_signature_to_c(v, cname, full_name, null, more_params)
575 var ctx_old = v.ctx
576 v.ctx = new CContext
577
578 v.out_contexts.clear
579
580 var itpos: nullable String = null
581 if global.is_init then
582 itpos = "itpos{v.new_number}"
583 v.add_decl("int {itpos} = VAL2OBJ({args.first})->vft[{local_class.global.init_table_pos_id}].i;")
584 v.add_instr("if (init_table[{itpos}]) return;")
585 end
586
587 var s = ir.compile_to_c(v, cname, args)
588
589 if itpos != null then
590 v.add_instr("init_table[{itpos}] = 1;")
591 end
592 if s == null then
593 v.add_instr("return;")
594 else
595 v.add_instr("return ", s, ";")
596 end
597
598 ctx_old.append(v.ctx)
599 v.ctx = ctx_old
600 v.unindent
601 v.add_instr("}")
602
603 for ctx in v.out_contexts do v.ctx.merge(ctx)
604 end
605 end
606