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