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