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