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