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