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