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