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