global_compiler: remove useless methods since varargisation is done at the AST level
[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 redef fun call(m, recvtype, args)
524 do
525 var recv_type = get_recvtype(m, recvtype, args)
526 var recv = self.autoadapt(self.autobox(args.first, recvtype), recvtype)
527 if m.is_extern then recv = unbox_extern(recv, recv_type)
528
529 args = args.to_a
530 args.first = recv
531
532 assert args.length == m.msignature.arity + 1 else debug("Invalid arity for {m}. {args.length} arguments given.")
533
534 var rm = new CustomizedRuntimeFunction(m, recvtype)
535 return rm.call(self, args)
536 end
537
538 redef fun supercall(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
539 do
540 var types = self.collect_types(args.first)
541
542 var res: nullable RuntimeVariable
543 var ret = m.mproperty.intro.msignature.return_mtype
544 if ret == null then
545 res = null
546 else
547 ret = self.resolve_for(ret, args.first)
548 res = self.new_var(ret)
549 end
550
551 self.add("/* super {m} on {args.first.inspect} */")
552 if args.first.mtype.ctype != "val*" then
553 var mclasstype = args.first.mtype.as(MClassType)
554 if not self.compiler.runtime_type_analysis.live_types.has(mclasstype) then
555 self.add("/* skip, no method {m} */")
556 return res
557 end
558 var propdef = m.lookup_next_definition(self.compiler.mainmodule, mclasstype)
559 var res2 = self.call(propdef, mclasstype, args)
560 if res != null then self.assign(res, res2.as(not null))
561 return res
562 end
563
564 if types.is_empty then
565 self.add("\{")
566 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
567 self.bugtype(args.first)
568 self.add("\}")
569 return res
570 end
571
572 self.add("switch({args.first}->classid) \{")
573 var last = types.last
574 for t in types do
575 var propdef = m.lookup_next_definition(self.compiler.mainmodule, t)
576 if not self.compiler.hardening and t == last then
577 self.add("default: /* test {t} */")
578 else
579 self.add("case {self.compiler.classid(t)}: /* test {t} */")
580 end
581 var res2 = self.call(propdef, t, args)
582 if res != null then self.assign(res, res2.as(not null))
583 self.add "break;"
584 end
585 if self.compiler.hardening then
586 self.add("default: /* bug */")
587 self.bugtype(args.first)
588 end
589 self.add("\}")
590 return res
591 end
592
593 redef fun adapt_signature(m, args)
594 do
595 var recv = args.first
596 for i in [0..m.msignature.arity[ do
597 var t = m.msignature.mparameters[i].mtype
598 if i == m.msignature.vararg_rank then
599 t = args[i+1].mtype
600 end
601 t = self.resolve_for(t, recv)
602 args[i+1] = self.autobox(args[i+1], t)
603 end
604 end
605
606 redef fun unbox_signature_extern(m, args)
607 do
608 var recv = args.first
609 for i in [0..m.msignature.arity[ do
610 var t = m.msignature.mparameters[i].mtype
611 if i == m.msignature.vararg_rank then
612 t = args[i+1].mtype
613 end
614 t = self.resolve_for(t, recv)
615 if m.is_extern then args[i+1] = self.unbox_extern(args[i+1], t)
616 end
617 end
618
619 # FIXME: this is currently buggy since recv is not exact
620 redef fun vararg_instance(mpropdef, recv, varargs, elttype)
621 do
622 elttype = self.resolve_for(elttype, recv)
623 return self.array_instance(varargs, elttype)
624 end
625
626 fun bugtype(recv: RuntimeVariable)
627 do
628 if recv.mtype.ctype != "val*" then return
629 self.add("PRINT_ERROR(\"BTD BUG: Dynamic type is %s, static type is %s\\n\", class_names[{recv}->classid], \"{recv.mcasttype}\");")
630 self.add("show_backtrace(1);")
631 end
632
633 redef fun isset_attribute(a, recv)
634 do
635 check_recv_notnull(recv)
636
637 var types = self.collect_types(recv)
638 var res = self.new_var(bool_type)
639
640 if types.is_empty then
641 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
642 self.bugtype(recv)
643 return res
644 end
645 self.add("/* isset {a} on {recv.inspect} */")
646 self.add("switch({recv}->classid) \{")
647 var last = types.last
648 for t in types do
649 if not self.compiler.hardening and t == last then
650 self.add("default: /*{self.compiler.classid(t)}*/")
651 else
652 self.add("case {self.compiler.classid(t)}:")
653 end
654 var recv2 = self.autoadapt(recv, t)
655 var ta = a.intro.static_mtype.as(not null)
656 ta = self.resolve_for(ta, recv2)
657 var attr = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
658 if not ta isa MNullableType then
659 if ta.ctype == "val*" then
660 self.add("{res} = ({attr} != NULL);")
661 else
662 self.add("{res} = 1; /*NOTYET isset on primitive attributes*/")
663 end
664 end
665 self.add("break;")
666 end
667 if self.compiler.hardening then
668 self.add("default: /* Bug */")
669 self.bugtype(recv)
670 end
671 self.add("\}")
672
673 return res
674 end
675
676 redef fun read_attribute(a, recv)
677 do
678 check_recv_notnull(recv)
679
680 var types = self.collect_types(recv)
681
682 var ret = a.intro.static_mtype.as(not null)
683 ret = self.resolve_for(ret, recv)
684 var res = self.new_var(ret)
685
686 if types.is_empty then
687 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
688 self.bugtype(recv)
689 return res
690 end
691 self.add("/* read {a} on {recv.inspect} */")
692 self.add("switch({recv}->classid) \{")
693 var last = types.last
694 for t in types do
695 if not self.compiler.hardening and t == last then
696 self.add("default: /*{self.compiler.classid(t)}*/")
697 else
698 self.add("case {self.compiler.classid(t)}:")
699 end
700 var recv2 = self.autoadapt(recv, t)
701 var ta = a.intro.static_mtype.as(not null)
702 ta = self.resolve_for(ta, recv2)
703 var res2 = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
704 if not ta isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_attr_isset.value then
705 if ta.ctype == "val*" then
706 self.add("if ({res2} == NULL) \{")
707 self.add_abort("Uninitialized attribute {a.name}")
708 self.add("\}")
709 else
710 self.add("/*NOTYET isset on primitive attributes*/")
711 end
712 end
713 self.assign(res, res2)
714 self.add("break;")
715 end
716 if self.compiler.hardening then
717 self.add("default: /* Bug */")
718 self.bugtype(recv)
719 end
720 self.add("\}")
721
722 return res
723 end
724
725 redef fun write_attribute(a, recv, value)
726 do
727 check_recv_notnull(recv)
728
729 var types = self.collect_types(recv)
730
731 if types.is_empty then
732 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
733 self.bugtype(recv)
734 return
735 end
736 self.add("/* write {a} on {recv.inspect} */")
737 self.add("switch({recv}->classid) \{")
738 var last = types.last
739 for t in types do
740 if not self.compiler.hardening and t == last then
741 self.add("default: /*{self.compiler.classid(t)}*/")
742 else
743 self.add("case {self.compiler.classid(t)}:")
744 end
745 var recv2 = self.autoadapt(recv, t)
746 var ta = a.intro.static_mtype.as(not null)
747 ta = self.resolve_for(ta, recv2)
748 self.add("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
749 self.add("break;")
750 end
751 if self.compiler.hardening then
752 self.add("default: /* Bug*/")
753 self.bugtype(recv)
754 end
755 self.add("\}")
756 end
757
758 redef fun init_instance(mtype)
759 do
760 mtype = self.anchor(mtype).as(MClassType)
761 if not self.compiler.runtime_type_analysis.live_types.has(mtype) then
762 debug "problem: {mtype} was detected dead"
763 end
764 var res = self.new_expr("NEW_{mtype.c_name}()", mtype)
765 res.is_exact = true
766 return res
767 end
768
769 redef fun type_test(value, mtype, tag)
770 do
771 mtype = self.anchor(mtype)
772 if not self.compiler.runtime_type_analysis.live_cast_types.has(mtype) then
773 debug "problem: {mtype} was detected cast-dead"
774 abort
775 end
776
777 var types = self.collect_types(value)
778 var res = self.new_var(bool_type)
779
780 self.add("/* isa {mtype} on {value.inspect} */")
781 if value.mtype.ctype != "val*" then
782 if value.mtype.is_subtype(self.compiler.mainmodule, null, mtype) then
783 self.add("{res} = 1;")
784 else
785 self.add("{res} = 0;")
786 end
787 return res
788 end
789 if value.mcasttype isa MNullableType or value.mcasttype isa MNullType then
790 self.add("if ({value} == NULL) \{")
791 if mtype isa MNullableType then
792 self.add("{res} = 1; /* isa {mtype} */")
793 else
794 self.add("{res} = 0; /* not isa {mtype} */")
795 end
796 self.add("\} else ")
797 end
798 self.add("switch({value}->classid) \{")
799 for t in types do
800 if t.is_subtype(self.compiler.mainmodule, null, mtype) then
801 self.add("case {self.compiler.classid(t)}: /* {t} */")
802 end
803 end
804 self.add("{res} = 1;")
805 self.add("break;")
806 self.add("default:")
807 self.add("{res} = 0;")
808 self.add("\}")
809
810 return res
811 end
812
813 redef fun is_same_type_test(value1, value2)
814 do
815 var res = self.new_var(bool_type)
816 if value2.mtype.ctype == "val*" then
817 if value1.mtype.ctype == "val*" then
818 self.add "{res} = {value1}->classid == {value2}->classid;"
819 else
820 self.add "{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
821 end
822 else
823 if value1.mtype.ctype == "val*" then
824 self.add "{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
825 else if value1.mcasttype == value2.mcasttype then
826 self.add "{res} = 1;"
827 else
828 self.add "{res} = 0;"
829 end
830 end
831 return res
832 end
833
834 redef fun class_name_string(value)
835 do
836 var res = self.get_name("var_class_name")
837 self.add_decl("const char* {res};")
838 if value.mtype.ctype == "val*" then
839 self.add "{res} = class_names[{value}->classid];"
840 else
841 self.add "{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
842 end
843 return res
844 end
845
846 redef fun equal_test(value1, value2)
847 do
848 var res = self.new_var(bool_type)
849 if value2.mtype.ctype != "val*" and value1.mtype.ctype == "val*" then
850 var tmp = value1
851 value1 = value2
852 value2 = tmp
853 end
854 if value1.mtype.ctype != "val*" then
855 if value2.mtype == value1.mtype then
856 self.add("{res} = {value1} == {value2};")
857 else if value2.mtype.ctype != "val*" then
858 self.add("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
859 else
860 var mtype1 = value1.mtype.as(MClassType)
861 self.add("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
862 self.add("if ({res}) \{")
863 self.add("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
864 self.add("\}")
865 end
866 else
867 var s = new Array[String]
868 for t in self.compiler.live_primitive_types do
869 if not t.is_subtype(self.compiler.mainmodule, null, value1.mcasttype) then continue
870 if not t.is_subtype(self.compiler.mainmodule, null, value2.mcasttype) then continue
871 s.add "({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
872 end
873
874 if self.compiler.mainmodule.model.get_mclasses_by_name("Pointer") != null then
875 var pointer_type = self.compiler.mainmodule.pointer_type
876 if value1.mcasttype.is_subtype(self.compiler.mainmodule, null, pointer_type) or
877 value2.mcasttype.is_subtype(self.compiler.mainmodule, null, pointer_type) then
878 s.add "(((struct {pointer_type.c_name}*){value1})->value == ((struct {pointer_type.c_name}*){value2})->value)"
879 end
880 end
881
882 if s.is_empty then
883 self.add("{res} = {value1} == {value2};")
884 else
885 self.add("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
886 end
887 end
888 return res
889 end
890
891 redef fun array_instance(array, elttype)
892 do
893 elttype = self.anchor(elttype)
894 var arraytype = self.get_class("Array").get_mtype([elttype])
895 var res = self.init_instance(arraytype)
896 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
897 var nat = self.new_var(self.get_class("NativeArray").get_mtype([elttype]))
898 nat.is_exact = true
899 self.add("{nat} = NEW_{nat.mtype.c_name}({array.length});")
900 for i in [0..array.length[ do
901 var r = self.autobox(array[i], elttype)
902 self.add("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
903 end
904 var length = self.int_instance(array.length)
905 self.send(self.get_property("with_native", arraytype), [res, nat, length])
906 self.add("\}")
907 return res
908 end
909 end
910
911 # A runtime function customized on a specific monomrph receiver type
912 private class CustomizedRuntimeFunction
913 super AbstractRuntimeFunction
914
915 redef type COMPILER: GlobalCompiler
916 redef type VISITOR: GlobalCompilerVisitor
917
918 # The considered reciever
919 # (usually is a live type but no strong guarantee)
920 var recv: MClassType
921
922 init(mmethoddef: MMethodDef, recv: MClassType)
923 do
924 super(mmethoddef)
925 self.recv = recv
926 end
927
928 redef fun build_c_name
929 do
930 var res = self.c_name_cache
931 if res != null then return res
932 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
933 res = self.mmethoddef.c_name
934 else
935 res = "{mmethoddef.c_name}__{recv.c_name}"
936 end
937 self.c_name_cache = res
938 return res
939 end
940
941 # used in the compiler worklist
942 redef fun ==(o)
943 do
944 if not o isa CustomizedRuntimeFunction then return false
945 if self.mmethoddef != o.mmethoddef then return false
946 if self.recv != o.recv then return false
947 return true
948 end
949
950 # used in the compiler work-list
951 redef fun hash do return self.mmethoddef.hash + self.recv.hash
952
953 redef fun to_s
954 do
955 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
956 return self.mmethoddef.to_s
957 else
958 return "{self.mmethoddef}@{self.recv}"
959 end
960 end
961
962 # compile the code customized for the reciever
963 redef fun compile_to_c(compiler)
964 do
965 var recv = self.recv
966 var mmethoddef = self.mmethoddef
967 if not recv.is_subtype(compiler.mainmodule, null, mmethoddef.mclassdef.bound_mtype) then
968 print("problem: why do we compile {self} for {recv}?")
969 abort
970 end
971
972 var v = compiler.new_visitor
973 var selfvar = new RuntimeVariable("self", recv, recv)
974 if compiler.runtime_type_analysis.live_types.has(recv) then
975 selfvar.is_exact = true
976 end
977 var arguments = new Array[RuntimeVariable]
978 var frame = new Frame(v, mmethoddef, recv, arguments)
979 v.frame = frame
980
981 var sig = new FlatBuffer
982 var comment = new FlatBuffer
983 var ret = mmethoddef.msignature.return_mtype
984 if ret != null then
985 ret = v.resolve_for(ret, selfvar)
986 sig.append("{ret.ctype} ")
987 else if mmethoddef.mproperty.is_new then
988 ret = recv
989 sig.append("{ret.ctype} ")
990 else
991 sig.append("void ")
992 end
993 sig.append(self.c_name)
994 sig.append("({recv.ctype} {selfvar}")
995 comment.append("(self: {recv}")
996 arguments.add(selfvar)
997 for i in [0..mmethoddef.msignature.arity[ do
998 var mtype = mmethoddef.msignature.mparameters[i].mtype
999 if i == mmethoddef.msignature.vararg_rank then
1000 mtype = v.get_class("Array").get_mtype([mtype])
1001 end
1002 mtype = v.resolve_for(mtype, selfvar)
1003 comment.append(", {mtype}")
1004 sig.append(", {mtype.ctype} p{i}")
1005 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
1006 arguments.add(argvar)
1007 end
1008 sig.append(")")
1009 comment.append(")")
1010 if ret != null then
1011 comment.append(": {ret}")
1012 end
1013 compiler.header.add_decl("{sig};")
1014
1015 v.add_decl("/* method {self} for {comment} */")
1016 v.add_decl("{sig} \{")
1017 #v.add("printf(\"method {self} for {comment}\\n\");")
1018 if ret != null then
1019 frame.returnvar = v.new_var(ret)
1020 end
1021 frame.returnlabel = v.get_name("RET_LABEL")
1022
1023 mmethoddef.compile_inside_to_c(v, arguments)
1024
1025 v.add("{frame.returnlabel.as(not null)}:;")
1026 if ret != null then
1027 v.add("return {frame.returnvar.as(not null)};")
1028 end
1029 v.add("\}")
1030 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})"
1031 end
1032
1033 redef fun call(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1034 do
1035 var ret = self.mmethoddef.msignature.return_mtype
1036 if self.mmethoddef.mproperty.is_new then
1037 ret = recv
1038 end
1039 if ret != null then
1040 ret = v.resolve_for(ret, arguments.first)
1041 end
1042 if self.mmethoddef.can_inline(v) then
1043 var frame = new Frame(v, self.mmethoddef, self.recv, arguments)
1044 frame.returnlabel = v.get_name("RET_LABEL")
1045 if ret != null then
1046 frame.returnvar = v.new_var(ret)
1047 end
1048 var old_frame = v.frame
1049 v.frame = frame
1050 v.add("\{ /* Inline {self} ({arguments.join(",")}) */")
1051 self.mmethoddef.compile_inside_to_c(v, arguments)
1052 v.add("{frame.returnlabel.as(not null)}:(void)0;")
1053 v.add("\}")
1054 v.frame = old_frame
1055 return frame.returnvar
1056 end
1057 v.adapt_signature(self.mmethoddef, arguments)
1058 v.compiler.todo(self)
1059 if ret == null then
1060 v.add("{self.c_name}({arguments.join(",")});")
1061 return null
1062 else
1063 var res = v.new_var(ret)
1064 v.add("{res} = {self.c_name}({arguments.join(",")});")
1065 return res
1066 end
1067 end
1068 end