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