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