nitg & lib: intro `Finalizable` to be called when an object is freed
[nit.git] / src / global_compiler.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 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 # Global compilation of a Nit program
18 #
19 # Techniques used are:
20 # * heterogeneous generics
21 # * customization
22 # * switch dispatch
23 # * inlining
24 module global_compiler
25
26 import abstract_compiler
27 import rapid_type_analysis
28
29 redef class ToolContext
30 # option --global
31 var opt_global = new OptionBool("Use global compilation", "--global")
32
33 var global_compiler_phase = new GlobalCompilerPhase(self, null)
34
35 redef init do
36 super
37 option_context.add_option(opt_global)
38 end
39 end
40
41 class GlobalCompilerPhase
42 super Phase
43 redef fun process_mainmodule(mainmodule, given_mmodules) do
44 if not toolcontext.opt_global.value then return
45
46 var modelbuilder = toolcontext.modelbuilder
47 var analysis = modelbuilder.do_rapid_type_analysis(mainmodule)
48 modelbuilder.run_global_compiler(mainmodule, analysis)
49 end
50 end
51
52 redef class ModelBuilder
53 # Entry point to performs a global compilation on the AST of a complete program.
54 # `mainmodule` is the main module of the program
55 # `runtime_type_analysis` is a already computer type analysis.
56 fun run_global_compiler(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis)
57 do
58 var time0 = get_time
59 self.toolcontext.info("*** GENERATING C ***", 1)
60
61 var compiler = new GlobalCompiler(mainmodule, self, runtime_type_analysis)
62 compiler.compile_header
63
64 for t in runtime_type_analysis.live_types do
65 compiler.declare_runtimeclass(t)
66 end
67
68 compiler.compile_class_names
69
70 # Init instance code (allocate and init-arguments)
71 for t in runtime_type_analysis.live_types do
72 if t.ctype == "val*" then
73 compiler.generate_init_instance(t)
74 else
75 compiler.generate_box_instance(t)
76 end
77 end
78
79 # The main function of the C
80 compiler.compile_nitni_global_ref_functions
81 compiler.compile_main_function
82
83 # Compile until all runtime_functions are visited
84 while not compiler.todos.is_empty do
85 var m = compiler.todos.shift
86 self.toolcontext.info("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
87 m.compile_to_c(compiler)
88 end
89 self.toolcontext.info("Total methods to compile to C: {compiler.seen.length}", 2)
90
91 compiler.display_stats
92
93 var time1 = get_time
94 self.toolcontext.info("*** END GENERATING C: {time1-time0} ***", 2)
95 write_and_make(compiler)
96 end
97 end
98
99 # Compiler that use global compilation and perform hard optimisations like:
100 # * customization
101 # * switch dispatch
102 # * inlining
103 class GlobalCompiler
104 super AbstractCompiler
105
106 redef type VISITOR: GlobalCompilerVisitor
107
108 # The result of the RTA (used to know live types and methods)
109 var runtime_type_analysis: RapidTypeAnalysis
110
111 init(mainmodule: MModule, modelbuilder: ModelBuilder, runtime_type_analysis: RapidTypeAnalysis)
112 do
113 super(mainmodule, modelbuilder)
114 var file = new_file("{mainmodule.name}.nitgg")
115 self.header = new CodeWriter(file)
116 self.runtime_type_analysis = runtime_type_analysis
117 self.live_primitive_types = new Array[MClassType]
118 for t in runtime_type_analysis.live_types do
119 if t.ctype != "val*" then
120 self.live_primitive_types.add(t)
121 end
122 end
123 end
124
125 # Compile class names (for the class_name and output_class_name methods)
126 protected fun compile_class_names do
127 var v = new_visitor
128 self.header.add_decl("extern const char *class_names[];")
129 v.add("const char *class_names[] = \{")
130 for t in self.runtime_type_analysis.live_types do
131 v.add("\"{t}\", /* {self.classid(t)} */")
132 end
133 v.add("\};")
134 end
135
136 # Return the C symbol associated to a live type runtime
137 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
138 fun classid(mtype: MClassType): String
139 do
140 if self.classids.has_key(mtype) then
141 return self.classids[mtype]
142 end
143 print "No classid for {mtype}"
144 abort
145 end
146
147 # Cache for classid
148 protected var classids: HashMap[MClassType, String] = new HashMap[MClassType, String]
149
150 # Declaration of structures the live Nit types
151 # Each live type is generated as an independent C `struct` type.
152 # They only share a common first field `classid` used to implement the polymorphism.
153 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val` that contains only the `classid` field.
154 redef fun compile_header_structs do
155 self.header.add_decl("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
156 end
157
158 # Subset of runtime_type_analysis.live_types that contains only primitive types
159 # Used to implement the equal test
160 var live_primitive_types: Array[MClassType]
161
162 # Add a new todo task
163 fun todo(m: AbstractRuntimeFunction)
164 do
165 if seen.has(m) then return
166 todos.add(m)
167 seen.add(m)
168 end
169
170 # runtime_functions that need to be compiled
171 private var todos: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
172
173 # runtime_functions already seen (todo or done)
174 private var seen: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
175
176 # Declare C structures and identifiers for a runtime class
177 fun declare_runtimeclass(mtype: MClassType)
178 do
179 var v = self.header
180 assert self.runtime_type_analysis.live_types.has(mtype)
181 v.add_decl("/* runtime class {mtype} */")
182 var idnum = classids.length
183 var idname = "ID_" + mtype.c_name
184 self.classids[mtype] = idname
185 v.add_decl("#define {idname} {idnum} /* {mtype} */")
186
187 v.add_decl("struct {mtype.c_name} \{")
188 v.add_decl("int classid; /* must be {idname} */")
189
190 if mtype.mclass.name == "NativeArray" then
191 # NativeArrays are just a instance header followed by an array of values
192 v.add_decl("int length;")
193 v.add_decl("{mtype.arguments.first.ctype} values[1];")
194 end
195
196 if mtype.ctype != "val*" then
197 # Is the Nit type is native then the struct is a box with two fields:
198 # * the `classid` to be polymorph
199 # * the `value` that contains the native value.
200 v.add_decl("{mtype.ctype} value;")
201 end
202
203 # Collect all attributes and associate them a field in the structure.
204 # Note: we do not try to optimize the order and helps CC to optimize the client code.
205 for cd in mtype.collect_mclassdefs(self.mainmodule) do
206 for p in cd.intro_mproperties do
207 if not p isa MAttribute then continue
208 var t = p.intro.static_mtype.as(not null)
209 t = t.anchor_to(self.mainmodule, mtype)
210 v.add_decl("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
211 end
212 end
213 v.add_decl("\};")
214 end
215
216 # Generate the init-instance of a live type (allocate + init-instance)
217 fun generate_init_instance(mtype: MClassType)
218 do
219 assert self.runtime_type_analysis.live_types.has(mtype)
220 assert mtype.ctype == "val*"
221 var v = self.new_visitor
222
223 var is_native_array = mtype.mclass.name == "NativeArray"
224
225 var sig
226 if is_native_array then
227 sig = "int length"
228 else
229 sig = "void"
230 end
231
232 self.header.add_decl("{mtype.ctype} NEW_{mtype.c_name}({sig});")
233 v.add_decl("/* allocate {mtype} */")
234 v.add_decl("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
235 var res = v.new_var(mtype)
236 res.is_exact = true
237 if is_native_array then
238 var mtype_elt = mtype.arguments.first
239 v.add("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
240 v.add("((struct {mtype.c_name}*){res})->length = length;")
241 else
242 v.add("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
243 end
244 v.add("{res}->classid = {self.classid(mtype)};")
245
246 self.generate_init_attr(v, res, mtype)
247 v.set_finalizer res
248 v.add("return {res};")
249 v.add("\}")
250 end
251
252 fun generate_box_instance(mtype: MClassType)
253 do
254 assert self.runtime_type_analysis.live_types.has(mtype)
255 assert mtype.ctype != "val*"
256 var v = self.new_visitor
257
258 self.header.add_decl("val* BOX_{mtype.c_name}({mtype.ctype});")
259 v.add_decl("/* allocate {mtype} */")
260 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
261 v.add("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
262 v.add("res->classid = {self.classid(mtype)};")
263 v.add("res->value = value;")
264 v.add("return (val*)res;")
265 v.add("\}")
266 end
267
268 redef fun new_visitor do return new GlobalCompilerVisitor(self)
269
270 private var collect_types_cache: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
271
272 redef fun compile_nitni_structs
273 do
274 self.header.add_decl """
275 struct nitni_instance \{
276 struct nitni_instance *next,
277 *prev; /* adjacent global references in global list */
278 int count; /* number of time this global reference has been marked */
279 val *value;
280 \};"""
281 super
282 end
283 end
284
285 # A visitor on the AST of property definition that generate the C code.
286 # Because of inlining, a visitor can visit more than one property.
287 class GlobalCompilerVisitor
288 super AbstractCompilerVisitor
289
290 redef type COMPILER: GlobalCompiler
291
292 redef fun autobox(value, mtype)
293 do
294 if value.mtype == mtype then
295 return value
296 else if value.mtype.ctype == "val*" and mtype.ctype == "val*" then
297 return value
298 else if value.mtype.ctype == "val*" then
299 return self.new_expr("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype)
300 else if mtype.ctype == "val*" then
301 var valtype = value.mtype.as(MClassType)
302 var res = self.new_var(mtype)
303 if not compiler.runtime_type_analysis.live_types.has(valtype) then
304 self.add("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
305 self.add("PRINT_ERROR(\"Dead code executed!\\n\"); show_backtrace(1);")
306 return res
307 end
308 self.add("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
309 return res
310 else if value.mtype.ctype == "void*" and mtype.ctype == "void*" then
311 return value
312 else
313 # Bad things will appen!
314 var res = self.new_var(mtype)
315 self.add("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
316 self.add("PRINT_ERROR(\"Cast error: Cannot cast %s to %s.\\n\", \"{value.mtype}\", \"{mtype}\"); show_backtrace(1);")
317 return res
318 end
319 end
320
321 # The runtime types that are acceptable for a given receiver.
322 fun collect_types(recv: RuntimeVariable): Array[MClassType]
323 do
324 var mtype = recv.mcasttype
325 if recv.is_exact then
326 assert mtype isa MClassType
327 assert self.compiler.runtime_type_analysis.live_types.has(mtype)
328 var types = [mtype]
329 return types
330 end
331 var cache = self.compiler.collect_types_cache
332 if cache.has_key(mtype) then
333 return cache[mtype]
334 end
335 var types = new Array[MClassType]
336 var mainmodule = self.compiler.mainmodule
337 for t in self.compiler.runtime_type_analysis.live_types do
338 if not t.is_subtype(mainmodule, null, mtype) then continue
339 types.add(t)
340 end
341 cache[mtype] = types
342 return types
343 end
344
345 redef fun native_array_def(pname, ret_type, arguments)
346 do
347 var elttype = arguments.first.mtype
348 var recv = "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
349 if pname == "[]" then
350 self.ret(self.new_expr("{recv}[{arguments[1]}]", ret_type.as(not null)))
351 return
352 else if pname == "[]=" then
353 self.add("{recv}[{arguments[1]}]={arguments[2]};")
354 return
355 else if pname == "length" then
356 self.ret(self.new_expr("((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->length", ret_type.as(not null)))
357 return
358 else if pname == "copy_to" then
359 var recv1 = "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
360 self.add("memcpy({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
361 return
362 end
363 end
364
365 redef fun native_array_instance(elttype: MType, length: RuntimeVariable): RuntimeVariable
366 do
367 var ret_type = self.get_class("NativeArray").get_mtype([elttype])
368 return self.new_expr("NEW_{ret_type.c_name}({length})", ret_type)
369 end
370
371 redef fun calloc_array(ret_type, arguments)
372 do
373 self.ret(self.new_expr("NEW_{ret_type.c_name}({arguments[1]})", ret_type))
374 end
375
376 redef fun send(m, args)
377 do
378 var types = self.collect_types(args.first)
379
380 var res: nullable RuntimeVariable
381 var ret = m.intro.msignature.return_mtype
382 if m.is_new then
383 ret = args.first.mtype
384 res = self.new_var(ret)
385 else if ret == null then
386 res = null
387 else
388 ret = self.resolve_for(ret, args.first)
389 res = self.new_var(ret)
390 end
391
392 self.add("/* send {m} on {args.first.inspect} */")
393 if args.first.mtype.ctype != "val*" then
394 var mclasstype = args.first.mtype.as(MClassType)
395 if not self.compiler.runtime_type_analysis.live_types.has(mclasstype) then
396 self.add("/* skip, no method {m} */")
397 return res
398 end
399 var propdef = m.lookup_first_definition(self.compiler.mainmodule, mclasstype)
400 var res2 = self.call(propdef, mclasstype, args)
401 if res != null then self.assign(res, res2.as(not null))
402 return res
403 end
404 var consider_null = not self.compiler.modelbuilder.toolcontext.opt_no_check_other.value or m.name == "==" or m.name == "!="
405 if args.first.mcasttype isa MNullableType or args.first.mcasttype isa MNullType and consider_null then
406 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
407 self.add("if ({args.first} == NULL) \{ /* Special null case */")
408 if m.name == "==" then
409 assert res != null
410 if args[1].mcasttype isa MNullableType then
411 self.add("{res} = ({args[1]} == NULL);")
412 else if args[1].mcasttype isa MNullType then
413 self.add("{res} = 1; /* is null */")
414 else
415 self.add("{res} = 0; /* {args[1].inspect} cannot be null */")
416 end
417 else if m.name == "!=" then
418 assert res != null
419 if args[1].mcasttype isa MNullableType then
420 self.add("{res} = ({args[1]} != NULL);")
421 else if args[1].mcasttype isa MNullType then
422 self.add("{res} = 0; /* is null */")
423 else
424 self.add("{res} = 1; /* {args[1].inspect} cannot be null */")
425 end
426 else
427 self.add_abort("Receiver is null")
428 end
429 self.add "\} else"
430 end
431 if types.is_empty then
432 self.add("\{")
433 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
434 self.bugtype(args.first)
435 self.add("\}")
436 return res
437 end
438
439 self.add("switch({args.first}->classid) \{")
440 var last = types.last
441 var defaultpropdef: nullable MMethodDef = null
442 for t in types do
443 var propdef = m.lookup_first_definition(self.compiler.mainmodule, t)
444 if propdef.mclassdef.mclass.name == "Object" and t.ctype == "val*" then
445 defaultpropdef = propdef
446 continue
447 end
448 if not self.compiler.hardening and t == last and defaultpropdef == null then
449 self.add("default: /* test {t} */")
450 else
451 self.add("case {self.compiler.classid(t)}: /* test {t} */")
452 end
453 var res2 = self.call(propdef, t, args)
454 if res != null then self.assign(res, res2.as(not null))
455 self.add "break;"
456 end
457 if defaultpropdef != null then
458 self.add("default: /* default is Object */")
459 var res2 = self.call(defaultpropdef, defaultpropdef.mclassdef.bound_mtype, args)
460 if res != null then self.assign(res, res2.as(not null))
461 else if self.compiler.hardening then
462 self.add("default: /* bug */")
463 self.bugtype(args.first)
464 end
465 self.add("\}")
466 return res
467 end
468
469 fun check_valid_reciever(recvtype: MClassType)
470 do
471 if self.compiler.runtime_type_analysis.live_types.has(recvtype) or recvtype.mclass.name == "Object" then return
472 print "{recvtype} is not a live type"
473 abort
474 end
475
476 # Subpart of old call function
477 #
478 # Checks if the type of the receiver is valid and corrects it if necessary
479 private fun get_recvtype(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): MClassType
480 do
481 check_valid_reciever(recvtype)
482 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
483 if m.mclassdef.mclass.name == "Object" and recvtype.ctype == "val*" then
484 recvtype = m.mclassdef.bound_mtype
485 end
486 return recvtype
487 end
488
489 # Subpart of old call function
490 # Gets the receiver boxed and casted if necessary
491 private fun get_recv(recvtype: MClassType, args: Array[RuntimeVariable]): RuntimeVariable
492 do
493 return self.autoadapt(self.autobox(args.first, recvtype), recvtype)
494 end
495
496 # Finalizes a call to a method ´m´ on type ´recvtype´ with arguments ´args´
497 private fun finalize_call(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
498 do
499 assert args.length == m.msignature.arity + 1 else debug("Invalid arity for {m}. {args.length} arguments given.")
500
501 var rm = new CustomizedRuntimeFunction(m, recvtype)
502 return rm.call(self, args)
503 end
504
505 redef fun call(m, recvtype, args)
506 do
507 var recv_type = get_recvtype(m, recvtype, args)
508 var recv = get_recv(recv_type, args)
509 var new_args = args.to_a
510 self.varargize(m, m.msignature.as(not null), new_args)
511 new_args.first = recv
512 return finalize_call(m, recv_type, new_args)
513 end
514
515 # Does a call without encapsulating varargs into an array
516 # Avoids multiple encapsulation when calling a super in a variadic function
517 fun call_without_varargize(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
518 do
519 var recv_type = get_recvtype(m, recvtype, args)
520 var recv = get_recv(recv_type, args)
521 var new_args = args.to_a
522 new_args.first = recv
523 return finalize_call(m, recv_type, new_args)
524 end
525
526 redef fun supercall(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
527 do
528 var types = self.collect_types(args.first)
529
530 var res: nullable RuntimeVariable
531 var ret = m.mproperty.intro.msignature.return_mtype
532 if ret == null then
533 res = null
534 else
535 ret = self.resolve_for(ret, args.first)
536 res = self.new_var(ret)
537 end
538
539 self.add("/* super {m} on {args.first.inspect} */")
540 if args.first.mtype.ctype != "val*" then
541 var mclasstype = args.first.mtype.as(MClassType)
542 if not self.compiler.runtime_type_analysis.live_types.has(mclasstype) then
543 self.add("/* skip, no method {m} */")
544 return res
545 end
546 var propdef = m.lookup_next_definition(self.compiler.mainmodule, mclasstype)
547 var res2 = self.call_without_varargize(propdef, mclasstype, args)
548 if res != null then self.assign(res, res2.as(not null))
549 return res
550 end
551
552 if types.is_empty then
553 self.add("\{")
554 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
555 self.bugtype(args.first)
556 self.add("\}")
557 return res
558 end
559
560 self.add("switch({args.first}->classid) \{")
561 var last = types.last
562 for t in types do
563 var propdef = m.lookup_next_definition(self.compiler.mainmodule, t)
564 if not self.compiler.hardening and t == last then
565 self.add("default: /* test {t} */")
566 else
567 self.add("case {self.compiler.classid(t)}: /* test {t} */")
568 end
569 var res2 = self.call_without_varargize(propdef, t, args)
570 if res != null then self.assign(res, res2.as(not null))
571 self.add "break;"
572 end
573 if self.compiler.hardening then
574 self.add("default: /* bug */")
575 self.bugtype(args.first)
576 end
577 self.add("\}")
578 return res
579 end
580
581 redef fun adapt_signature(m, args)
582 do
583 var recv = args.first
584 for i in [0..m.msignature.arity[ do
585 var t = m.msignature.mparameters[i].mtype
586 if i == m.msignature.vararg_rank then
587 t = args[i+1].mtype
588 end
589 t = self.resolve_for(t, recv)
590 args[i+1] = self.autobox(args[i+1], t)
591 end
592 end
593
594 # FIXME: this is currently buggy since recv is not exact
595 redef fun vararg_instance(mpropdef, recv, varargs, elttype)
596 do
597 elttype = self.resolve_for(elttype, recv)
598 return self.array_instance(varargs, elttype)
599 end
600
601 fun bugtype(recv: RuntimeVariable)
602 do
603 if recv.mtype.ctype != "val*" then return
604 self.add("PRINT_ERROR(\"BTD BUG: Dynamic type is %s, static type is %s\\n\", class_names[{recv}->classid], \"{recv.mcasttype}\");")
605 self.add("show_backtrace(1);")
606 end
607
608 redef fun isset_attribute(a, recv)
609 do
610 check_recv_notnull(recv)
611
612 var types = self.collect_types(recv)
613 var res = self.new_var(bool_type)
614
615 if types.is_empty then
616 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
617 self.bugtype(recv)
618 return res
619 end
620 self.add("/* isset {a} on {recv.inspect} */")
621 self.add("switch({recv}->classid) \{")
622 var last = types.last
623 for t in types do
624 if not self.compiler.hardening and t == last then
625 self.add("default: /*{self.compiler.classid(t)}*/")
626 else
627 self.add("case {self.compiler.classid(t)}:")
628 end
629 var recv2 = self.autoadapt(recv, t)
630 var ta = a.intro.static_mtype.as(not null)
631 ta = self.resolve_for(ta, recv2)
632 var attr = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
633 if not ta isa MNullableType then
634 if ta.ctype == "val*" then
635 self.add("{res} = ({attr} != NULL);")
636 else
637 self.add("{res} = 1; /*NOTYET isset on primitive attributes*/")
638 end
639 end
640 self.add("break;")
641 end
642 if self.compiler.hardening then
643 self.add("default: /* Bug */")
644 self.bugtype(recv)
645 end
646 self.add("\}")
647
648 return res
649 end
650
651 redef fun read_attribute(a, recv)
652 do
653 check_recv_notnull(recv)
654
655 var types = self.collect_types(recv)
656
657 var ret = a.intro.static_mtype.as(not null)
658 ret = self.resolve_for(ret, recv)
659 var res = self.new_var(ret)
660
661 if types.is_empty then
662 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
663 self.bugtype(recv)
664 return res
665 end
666 self.add("/* read {a} on {recv.inspect} */")
667 self.add("switch({recv}->classid) \{")
668 var last = types.last
669 for t in types do
670 if not self.compiler.hardening and t == last then
671 self.add("default: /*{self.compiler.classid(t)}*/")
672 else
673 self.add("case {self.compiler.classid(t)}:")
674 end
675 var recv2 = self.autoadapt(recv, t)
676 var ta = a.intro.static_mtype.as(not null)
677 ta = self.resolve_for(ta, recv2)
678 var res2 = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
679 if not ta isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_other.value then
680 if ta.ctype == "val*" then
681 self.add("if ({res2} == NULL) \{")
682 self.add_abort("Uninitialized attribute {a.name}")
683 self.add("\}")
684 else
685 self.add("/*NOTYET isset on primitive attributes*/")
686 end
687 end
688 self.assign(res, res2)
689 self.add("break;")
690 end
691 if self.compiler.hardening then
692 self.add("default: /* Bug */")
693 self.bugtype(recv)
694 end
695 self.add("\}")
696
697 return res
698 end
699
700 redef fun write_attribute(a, recv, value)
701 do
702 check_recv_notnull(recv)
703
704 var types = self.collect_types(recv)
705
706 if types.is_empty then
707 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
708 self.bugtype(recv)
709 return
710 end
711 self.add("/* write {a} on {recv.inspect} */")
712 self.add("switch({recv}->classid) \{")
713 var last = types.last
714 for t in types do
715 if not self.compiler.hardening and t == last then
716 self.add("default: /*{self.compiler.classid(t)}*/")
717 else
718 self.add("case {self.compiler.classid(t)}:")
719 end
720 var recv2 = self.autoadapt(recv, t)
721 var ta = a.intro.static_mtype.as(not null)
722 ta = self.resolve_for(ta, recv2)
723 self.add("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
724 self.add("break;")
725 end
726 if self.compiler.hardening then
727 self.add("default: /* Bug*/")
728 self.bugtype(recv)
729 end
730 self.add("\}")
731 end
732
733 redef fun init_instance(mtype)
734 do
735 mtype = self.anchor(mtype).as(MClassType)
736 if not self.compiler.runtime_type_analysis.live_types.has(mtype) then
737 debug "problem: {mtype} was detected dead"
738 end
739 var res = self.new_expr("NEW_{mtype.c_name}()", mtype)
740 res.is_exact = true
741 return res
742 end
743
744 redef fun type_test(value, mtype, tag)
745 do
746 mtype = self.anchor(mtype)
747 if not self.compiler.runtime_type_analysis.live_cast_types.has(mtype) then
748 debug "problem: {mtype} was detected cast-dead"
749 abort
750 end
751
752 var types = self.collect_types(value)
753 var res = self.new_var(bool_type)
754
755 self.add("/* isa {mtype} on {value.inspect} */")
756 if value.mtype.ctype != "val*" then
757 if value.mtype.is_subtype(self.compiler.mainmodule, null, mtype) then
758 self.add("{res} = 1;")
759 else
760 self.add("{res} = 0;")
761 end
762 return res
763 end
764 if value.mcasttype isa MNullableType or value.mcasttype isa MNullType then
765 self.add("if ({value} == NULL) \{")
766 if mtype isa MNullableType then
767 self.add("{res} = 1; /* isa {mtype} */")
768 else
769 self.add("{res} = 0; /* not isa {mtype} */")
770 end
771 self.add("\} else ")
772 end
773 self.add("switch({value}->classid) \{")
774 for t in types do
775 if t.is_subtype(self.compiler.mainmodule, null, mtype) then
776 self.add("case {self.compiler.classid(t)}: /* {t} */")
777 end
778 end
779 self.add("{res} = 1;")
780 self.add("break;")
781 self.add("default:")
782 self.add("{res} = 0;")
783 self.add("\}")
784
785 return res
786 end
787
788 redef fun is_same_type_test(value1, value2)
789 do
790 var res = self.new_var(bool_type)
791 if value2.mtype.ctype == "val*" then
792 if value1.mtype.ctype == "val*" then
793 self.add "{res} = {value1}->classid == {value2}->classid;"
794 else
795 self.add "{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
796 end
797 else
798 if value1.mtype.ctype == "val*" then
799 self.add "{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
800 else if value1.mcasttype == value2.mcasttype then
801 self.add "{res} = 1;"
802 else
803 self.add "{res} = 0;"
804 end
805 end
806 return res
807 end
808
809 redef fun class_name_string(value)
810 do
811 var res = self.get_name("var_class_name")
812 self.add_decl("const char* {res};")
813 if value.mtype.ctype == "val*" then
814 self.add "{res} = class_names[{value}->classid];"
815 else
816 self.add "{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
817 end
818 return res
819 end
820
821 redef fun equal_test(value1, value2)
822 do
823 var res = self.new_var(bool_type)
824 if value2.mtype.ctype != "val*" and value1.mtype.ctype == "val*" then
825 var tmp = value1
826 value1 = value2
827 value2 = tmp
828 end
829 if value1.mtype.ctype != "val*" then
830 if value2.mtype == value1.mtype then
831 self.add("{res} = {value1} == {value2};")
832 else if value2.mtype.ctype != "val*" then
833 self.add("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
834 else
835 var mtype1 = value1.mtype.as(MClassType)
836 self.add("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
837 self.add("if ({res}) \{")
838 self.add("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
839 self.add("\}")
840 end
841 else
842 var s = new Array[String]
843 for t in self.compiler.live_primitive_types do
844 if not t.is_subtype(self.compiler.mainmodule, null, value1.mcasttype) then continue
845 if not t.is_subtype(self.compiler.mainmodule, null, value2.mcasttype) then continue
846 s.add "({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
847 end
848 if s.is_empty then
849 self.add("{res} = {value1} == {value2};")
850 else
851 self.add("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
852 end
853 end
854 return res
855 end
856
857 redef fun array_instance(array, elttype)
858 do
859 elttype = self.anchor(elttype)
860 var arraytype = self.get_class("Array").get_mtype([elttype])
861 var res = self.init_instance(arraytype)
862 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
863 var nat = self.new_var(self.get_class("NativeArray").get_mtype([elttype]))
864 nat.is_exact = true
865 self.add("{nat} = NEW_{nat.mtype.c_name}({array.length});")
866 for i in [0..array.length[ do
867 var r = self.autobox(array[i], elttype)
868 self.add("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
869 end
870 var length = self.int_instance(array.length)
871 self.send(self.get_property("with_native", arraytype), [res, nat, length])
872 self.add("\}")
873 return res
874 end
875 end
876
877 # A runtime function customized on a specific monomrph receiver type
878 private class CustomizedRuntimeFunction
879 super AbstractRuntimeFunction
880
881 redef type COMPILER: GlobalCompiler
882 redef type VISITOR: GlobalCompilerVisitor
883
884 # The considered reciever
885 # (usually is a live type but no strong guarantee)
886 var recv: MClassType
887
888 init(mmethoddef: MMethodDef, recv: MClassType)
889 do
890 super(mmethoddef)
891 self.recv = recv
892 end
893
894 redef fun build_c_name
895 do
896 var res = self.c_name_cache
897 if res != null then return res
898 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
899 res = self.mmethoddef.c_name
900 else
901 res = "{mmethoddef.c_name}__{recv.c_name}"
902 end
903 self.c_name_cache = res
904 return res
905 end
906
907 # used in the compiler worklist
908 redef fun ==(o)
909 do
910 if not o isa CustomizedRuntimeFunction then return false
911 if self.mmethoddef != o.mmethoddef then return false
912 if self.recv != o.recv then return false
913 return true
914 end
915
916 # used in the compiler work-list
917 redef fun hash do return self.mmethoddef.hash + self.recv.hash
918
919 redef fun to_s
920 do
921 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
922 return self.mmethoddef.to_s
923 else
924 return "{self.mmethoddef}@{self.recv}"
925 end
926 end
927
928 # compile the code customized for the reciever
929 redef fun compile_to_c(compiler)
930 do
931 var recv = self.recv
932 var mmethoddef = self.mmethoddef
933 if not recv.is_subtype(compiler.mainmodule, null, mmethoddef.mclassdef.bound_mtype) then
934 print("problem: why do we compile {self} for {recv}?")
935 abort
936 end
937
938 var v = compiler.new_visitor
939 var selfvar = new RuntimeVariable("self", recv, recv)
940 if compiler.runtime_type_analysis.live_types.has(recv) then
941 selfvar.is_exact = true
942 end
943 var arguments = new Array[RuntimeVariable]
944 var frame = new Frame(v, mmethoddef, recv, arguments)
945 v.frame = frame
946
947 var sig = new FlatBuffer
948 var comment = new FlatBuffer
949 var ret = mmethoddef.msignature.return_mtype
950 if ret != null then
951 ret = v.resolve_for(ret, selfvar)
952 sig.append("{ret.ctype} ")
953 else if mmethoddef.mproperty.is_new then
954 ret = recv
955 sig.append("{ret.ctype} ")
956 else
957 sig.append("void ")
958 end
959 sig.append(self.c_name)
960 sig.append("({recv.ctype} {selfvar}")
961 comment.append("(self: {recv}")
962 arguments.add(selfvar)
963 for i in [0..mmethoddef.msignature.arity[ do
964 var mtype = mmethoddef.msignature.mparameters[i].mtype
965 if i == mmethoddef.msignature.vararg_rank then
966 mtype = v.get_class("Array").get_mtype([mtype])
967 end
968 mtype = v.resolve_for(mtype, selfvar)
969 comment.append(", {mtype}")
970 sig.append(", {mtype.ctype} p{i}")
971 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
972 arguments.add(argvar)
973 end
974 sig.append(")")
975 comment.append(")")
976 if ret != null then
977 comment.append(": {ret}")
978 end
979 compiler.header.add_decl("{sig};")
980
981 v.add_decl("/* method {self} for {comment} */")
982 v.add_decl("{sig} \{")
983 #v.add("printf(\"method {self} for {comment}\\n\");")
984 if ret != null then
985 frame.returnvar = v.new_var(ret)
986 end
987 frame.returnlabel = v.get_name("RET_LABEL")
988
989 mmethoddef.compile_inside_to_c(v, arguments)
990
991 v.add("{frame.returnlabel.as(not null)}:;")
992 if ret != null then
993 v.add("return {frame.returnvar.as(not null)};")
994 end
995 v.add("\}")
996 if not self.c_name.has_substring("VIRTUAL", 0) then compiler.names[self.c_name] = "{mmethoddef.mclassdef.mmodule.name}::{mmethoddef.mclassdef.mclass.name}::{mmethoddef.mproperty.name} ({mmethoddef.location.file.filename}:{mmethoddef.location.line_start})"
997 end
998
999 redef fun call(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1000 do
1001 var ret = self.mmethoddef.msignature.return_mtype
1002 if self.mmethoddef.mproperty.is_new then
1003 ret = recv
1004 end
1005 if ret != null then
1006 ret = v.resolve_for(ret, arguments.first)
1007 end
1008 if self.mmethoddef.can_inline(v) then
1009 var frame = new Frame(v, self.mmethoddef, self.recv, arguments)
1010 frame.returnlabel = v.get_name("RET_LABEL")
1011 if ret != null then
1012 frame.returnvar = v.new_var(ret)
1013 end
1014 var old_frame = v.frame
1015 v.frame = frame
1016 v.add("\{ /* Inline {self} ({arguments.join(",")}) */")
1017 self.mmethoddef.compile_inside_to_c(v, arguments)
1018 v.add("{frame.returnlabel.as(not null)}:(void)0;")
1019 v.add("\}")
1020 v.frame = old_frame
1021 return frame.returnvar
1022 end
1023 v.adapt_signature(self.mmethoddef, arguments)
1024 v.compiler.todo(self)
1025 if ret == null then
1026 v.add("{self.c_name}({arguments.join(",")});")
1027 return null
1028 else
1029 var res = v.new_var(ret)
1030 v.add("{res} = {self.c_name}({arguments.join(",")});")
1031 return res
1032 end
1033 end
1034 end