1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2012 Jean Privat <jean@pryen.org>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # Global compilation of a Nit program
19 # Techniques used are:
20 # * heterogeneous generics
24 module global_compiler
26 import abstract_compiler
27 import rapid_type_analysis
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)
36 self.toolcontext
.info
("*** GENERATING C ***", 1)
38 var compiler
= new GlobalCompiler(mainmodule
, self, runtime_type_analysis
)
39 compiler
.compile_header
41 for t
in runtime_type_analysis
.live_types
do
42 compiler
.declare_runtimeclass
(t
)
45 compiler
.compile_class_names
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
)
52 compiler
.generate_box_instance
(t
)
56 # The main function of the C
57 compiler
.compile_main_function
59 # Compile until all runtime_functions are visited
60 while not compiler
.todos
.is_empty
do
61 var m
= compiler
.todos
.shift
62 self.toolcontext
.info
("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
63 m
.compile_to_c
(compiler
)
65 self.toolcontext
.info
("Total methods to compile to C: {compiler.seen.length}", 2)
67 compiler
.display_stats
70 self.toolcontext
.info
("*** END GENERATING C: {time1-time0} ***", 2)
71 write_and_make
(compiler
)
75 # Compiler that use global compilation and perform hard optimisations like:
80 super AbstractCompiler
82 redef type VISITOR: GlobalCompilerVisitor
84 # The result of the RTA (used to know live types and methods)
85 var runtime_type_analysis
: RapidTypeAnalysis
87 init(mainmodule
: MModule, modelbuilder
: ModelBuilder, runtime_type_analysis
: RapidTypeAnalysis)
89 super(mainmodule
, modelbuilder
)
90 var file
= new_file
("{mainmodule.name}.nitgg")
91 self.header
= new CodeWriter(file
)
92 self.runtime_type_analysis
= runtime_type_analysis
93 self.live_primitive_types
= new Array[MClassType]
94 for t
in runtime_type_analysis
.live_types
do
95 if t
.ctype
!= "val*" then
96 self.live_primitive_types
.add
(t
)
101 # Compile class names (for the class_name and output_class_name methods)
102 protected fun compile_class_names
do
104 self.header
.add_decl
("extern const char const * class_names[];")
105 v
.add
("const char const * class_names[] = \{")
106 for t
in self.runtime_type_analysis
.live_types
do
107 v
.add
("\"{t}\
", /* {self.classid(t)} */")
112 # Return the C symbol associated to a live type runtime
113 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
114 fun classid
(mtype
: MClassType): String
116 if self.classids
.has_key
(mtype
) then
117 return self.classids
[mtype
]
119 print
"No classid for {mtype}"
124 protected var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
126 # Declaration of structures the live Nit types
127 # Each live type is generated as an independent C `struct` type.
128 # They only share a common first field `classid` used to implement the polymorphism.
129 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val` that contains only the `classid` field.
130 redef fun compile_header_structs
do
131 self.header
.add_decl
("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
134 # Subset of runtime_type_analysis.live_types that contains only primitive types
135 # Used to implement the equal test
136 var live_primitive_types
: Array[MClassType]
138 # Add a new todo task
139 fun todo
(m
: AbstractRuntimeFunction)
141 if seen
.has
(m
) then return
146 # runtime_functions that need to be compiled
147 private var todos
: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
149 # runtime_functions already seen (todo or done)
150 private var seen
: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
152 # Declare C structures and identifiers for a runtime class
153 fun declare_runtimeclass
(mtype
: MClassType)
156 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
157 v
.add_decl
("/* runtime class {mtype} */")
158 var idnum
= classids
.length
159 var idname
= "ID_" + mtype
.c_name
160 self.classids
[mtype
] = idname
161 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
163 v
.add_decl
("struct {mtype.c_name} \{")
164 v
.add_decl
("int classid; /* must be {idname} */")
166 if mtype
.mclass
.name
== "NativeArray" then
167 # NativeArrays are just a instance header followed by an array of values
168 v
.add_decl
("{mtype.arguments.first.ctype} values[1];")
171 if mtype
.ctype
!= "val*" then
172 # Is the Nit type is native then the struct is a box with two fields:
173 # * the `classid` to be polymorph
174 # * the `value` that contains the native value.
175 v
.add_decl
("{mtype.ctype} value;")
178 # Collect all attributes and associate them a field in the structure.
179 # Note: we do not try to optimize the order and helps CC to optimize the client code.
180 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
181 for p
in cd
.intro_mproperties
do
182 if not p
isa MAttribute then continue
183 var t
= p
.intro
.static_mtype
.as(not null)
184 t
= t
.anchor_to
(self.mainmodule
, mtype
)
185 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
191 # Generate the init-instance of a live type (allocate + init-instance)
192 fun generate_init_instance
(mtype
: MClassType)
194 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
195 assert mtype
.ctype
== "val*"
196 var v
= self.new_visitor
198 var is_native_array
= mtype
.mclass
.name
== "NativeArray"
201 if is_native_array
then
207 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig});")
208 v
.add_decl
("/* allocate {mtype} */")
209 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
210 var res
= v
.new_var
(mtype
)
212 if is_native_array
then
213 var mtype_elt
= mtype
.arguments
.first
214 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
216 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
218 v
.add
("{res}->classid = {self.classid(mtype)};")
220 self.generate_init_attr
(v
, res
, mtype
)
221 v
.add
("return {res};")
225 fun generate_box_instance
(mtype
: MClassType)
227 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
228 assert mtype
.ctype
!= "val*"
229 var v
= self.new_visitor
231 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
232 v
.add_decl
("/* allocate {mtype} */")
233 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
234 v
.add
("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
235 v
.add
("res->classid = {self.classid(mtype)};")
236 v
.add
("res->value = value;")
237 v
.add
("return (val*)res;")
241 redef fun new_visitor
do return new GlobalCompilerVisitor(self)
243 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
245 redef fun compile_nitni_structs
247 self.header
.add_decl
("struct nitni_instance \{ val *value; \};")
251 # A visitor on the AST of property definition that generate the C code.
252 # Because of inlining, a visitor can visit more than one property.
253 class GlobalCompilerVisitor
254 super AbstractCompilerVisitor
256 redef type COMPILER: GlobalCompiler
258 redef fun autobox
(value
, mtype
)
260 if value
.mtype
== mtype
then
262 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
264 else if value
.mtype
.ctype
== "val*" then
265 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
266 else if mtype
.ctype
== "val*" then
267 var valtype
= value
.mtype
.as(MClassType)
268 var res
= self.new_var
(mtype
)
269 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
270 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
271 self.add
("printf(\"Dead code executed
!\\n\
"); show_backtrace(1);")
274 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
276 else if value
.mtype
.ctype
== "void*" and mtype
.ctype
== "void*" then
279 # Bad things will appen!
280 var res
= self.new_var
(mtype
)
281 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
282 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); show_backtrace(1);")
287 # The runtime types that are acceptable for a given receiver.
288 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
290 var mtype
= recv
.mcasttype
291 if recv
.is_exact
then
292 assert mtype
isa MClassType
293 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
297 var cache
= self.compiler
.collect_types_cache
298 if cache
.has_key
(mtype
) then
301 var types
= new Array[MClassType]
302 var mainmodule
= self.compiler
.mainmodule
303 for t
in self.compiler
.runtime_type_analysis
.live_types
do
304 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
311 redef fun native_array_def
(pname
, ret_type
, arguments
)
313 var elttype
= arguments
.first
.mtype
314 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
315 if pname
== "[]" then
316 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
318 else if pname
== "[]=" then
319 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
321 else if pname
== "copy_to" then
322 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
323 self.add
("memcpy({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
328 redef fun calloc_array
(ret_type
, arguments
)
330 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
333 redef fun send
(m
, args
)
335 var types
= self.collect_types
(args
.first
)
337 var res
: nullable RuntimeVariable
338 var ret
= m
.intro
.msignature
.return_mtype
340 ret
= args
.first
.mtype
341 res
= self.new_var
(ret
)
342 else if ret
== null then
345 ret
= self.resolve_for
(ret
, args
.first
)
346 res
= self.new_var
(ret
)
349 self.add
("/* send {m} on {args.first.inspect} */")
350 if args
.first
.mtype
.ctype
!= "val*" then
351 var mclasstype
= args
.first
.mtype
.as(MClassType)
352 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
353 self.add
("/* skip, no method {m} */")
356 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
357 var res2
= self.call
(propdef
, mclasstype
, args
)
358 if res
!= null then self.assign
(res
, res2
.as(not null))
361 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or m
.name
== "==" or m
.name
== "!="
362 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
363 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
364 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
365 if m
.name
== "==" then
367 if args
[1].mcasttype
isa MNullableType then
368 self.add
("{res} = ({args[1]} == NULL);")
369 else if args
[1].mcasttype
isa MNullType then
370 self.add
("{res} = 1; /* is null */")
372 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
374 else if m
.name
== "!=" then
376 if args
[1].mcasttype
isa MNullableType then
377 self.add
("{res} = ({args[1]} != NULL);")
378 else if args
[1].mcasttype
isa MNullType then
379 self.add
("{res} = 0; /* is null */")
381 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
384 self.add_abort
("Receiver is null")
388 if types
.is_empty
then
390 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
391 self.bugtype
(args
.first
)
396 self.add
("switch({args.first}->classid) \{")
397 var last
= types
.last
398 var defaultpropdef
: nullable MMethodDef = null
400 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
401 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
402 defaultpropdef
= propdef
405 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
406 self.add
("default: /* test {t} */")
408 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
410 var res2
= self.call
(propdef
, t
, args
)
411 if res
!= null then self.assign
(res
, res2
.as(not null))
414 if defaultpropdef
!= null then
415 self.add
("default: /* default is Object */")
416 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
417 if res
!= null then self.assign
(res
, res2
.as(not null))
418 else if self.compiler
.hardening
then
419 self.add
("default: /* bug */")
420 self.bugtype
(args
.first
)
426 fun check_valid_reciever
(recvtype
: MClassType)
428 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
429 print
"{recvtype} is not a live type"
433 # Subpart of old call function
435 # Checks if the type of the receiver is valid and corrects it if necessary
436 private fun get_recvtype
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): MClassType
438 check_valid_reciever
(recvtype
)
439 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
440 if m
.mclassdef
.mclass
.name
== "Object" and recvtype
.ctype
== "val*" then
441 recvtype
= m
.mclassdef
.bound_mtype
446 # Subpart of old call function
447 # Gets the receiver boxed and casted if necessary
448 private fun get_recv
(recvtype
: MClassType, args
: Array[RuntimeVariable]): RuntimeVariable
450 return self.autoadapt
(self.autobox
(args
.first
, recvtype
), recvtype
)
453 # Finalizes a call to a method ´m´ on type ´recvtype´ with arguments ´args´
454 private fun finalize_call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
456 assert args
.length
== m
.msignature
.arity
+ 1 else debug
("Invalid arity for {m}. {args.length} arguments given.")
458 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
459 return rm
.call
(self, args
)
462 redef fun call
(m
, recvtype
, args
)
464 var recv_type
= get_recvtype
(m
, recvtype
, args
)
465 var recv
= get_recv
(recv_type
, args
)
466 var new_args
= args
.to_a
467 self.varargize
(m
, m
.msignature
.as(not null), new_args
)
468 new_args
.first
= recv
469 return finalize_call
(m
, recv_type
, new_args
)
472 # Does a call without encapsulating varargs into an array
473 # Avoids multiple encapsulation when calling a super in a variadic function
474 fun call_without_varargize
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
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 new_args
.first
= recv
480 return finalize_call
(m
, recv_type
, new_args
)
483 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
485 var types
= self.collect_types
(args
.first
)
487 var res
: nullable RuntimeVariable
488 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
492 ret
= self.resolve_for
(ret
, args
.first
)
493 res
= self.new_var
(ret
)
496 self.add
("/* super {m} on {args.first.inspect} */")
497 if args
.first
.mtype
.ctype
!= "val*" then
498 var mclasstype
= args
.first
.mtype
.as(MClassType)
499 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
500 self.add
("/* skip, no method {m} */")
503 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
504 var res2
= self.call_without_varargize
(propdef
, mclasstype
, args
)
505 if res
!= null then self.assign
(res
, res2
.as(not null))
509 if types
.is_empty
then
511 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
512 self.bugtype
(args
.first
)
517 self.add
("switch({args.first}->classid) \{")
518 var last
= types
.last
520 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
521 if not self.compiler
.hardening
and t
== last
then
522 self.add
("default: /* test {t} */")
524 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
526 var res2
= self.call_without_varargize
(propdef
, t
, args
)
527 if res
!= null then self.assign
(res
, res2
.as(not null))
530 if self.compiler
.hardening
then
531 self.add
("default: /* bug */")
532 self.bugtype
(args
.first
)
538 redef fun adapt_signature
(m
, args
)
540 var recv
= args
.first
541 for i
in [0..m
.msignature
.arity
[ do
542 var t
= m
.msignature
.mparameters
[i
].mtype
543 if i
== m
.msignature
.vararg_rank
then
546 t
= self.resolve_for
(t
, recv
)
547 args
[i
+1] = self.autobox
(args
[i
+1], t
)
551 # FIXME: this is currently buggy since recv is not exact
552 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
554 elttype
= self.resolve_for
(elttype
, recv
)
555 return self.array_instance
(varargs
, elttype
)
558 fun bugtype
(recv
: RuntimeVariable)
560 if recv
.mtype
.ctype
!= "val*" then return
561 self.add
("fprintf(stderr, \"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
562 self.add
("show_backtrace(1);")
565 redef fun isset_attribute
(a
, recv
)
567 check_recv_notnull
(recv
)
569 var types
= self.collect_types
(recv
)
570 var res
= self.new_var
(bool_type
)
572 if types
.is_empty
then
573 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
577 self.add
("/* isset {a} on {recv.inspect} */")
578 self.add
("switch({recv}->classid) \{")
579 var last
= types
.last
581 if not self.compiler
.hardening
and t
== last
then
582 self.add
("default: /*{self.compiler.classid(t)}*/")
584 self.add
("case {self.compiler.classid(t)}:")
586 var recv2
= self.autoadapt
(recv
, t
)
587 var ta
= a
.intro
.static_mtype
.as(not null)
588 ta
= self.resolve_for
(ta
, recv2
)
589 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
590 if not ta
isa MNullableType then
591 if ta
.ctype
== "val*" then
592 self.add
("{res} = ({attr} != NULL);")
594 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
599 if self.compiler
.hardening
then
600 self.add
("default: /* Bug */")
608 redef fun read_attribute
(a
, recv
)
610 check_recv_notnull
(recv
)
612 var types
= self.collect_types
(recv
)
614 var ret
= a
.intro
.static_mtype
.as(not null)
615 ret
= self.resolve_for
(ret
, recv
)
616 var res
= self.new_var
(ret
)
618 if types
.is_empty
then
619 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
623 self.add
("/* read {a} on {recv.inspect} */")
624 self.add
("switch({recv}->classid) \{")
625 var last
= types
.last
627 if not self.compiler
.hardening
and t
== last
then
628 self.add
("default: /*{self.compiler.classid(t)}*/")
630 self.add
("case {self.compiler.classid(t)}:")
632 var recv2
= self.autoadapt
(recv
, t
)
633 var ta
= a
.intro
.static_mtype
.as(not null)
634 ta
= self.resolve_for
(ta
, recv2
)
635 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
636 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then
637 if ta
.ctype
== "val*" then
638 self.add
("if ({res2} == NULL) \{")
639 self.add_abort
("Uninitialized attribute {a.name}")
642 self.add
("/*NOTYET isset on primitive attributes*/")
645 self.assign
(res
, res2
)
648 if self.compiler
.hardening
then
649 self.add
("default: /* Bug */")
657 redef fun write_attribute
(a
, recv
, value
)
659 check_recv_notnull
(recv
)
661 var types
= self.collect_types
(recv
)
663 if types
.is_empty
then
664 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
668 self.add
("/* write {a} on {recv.inspect} */")
669 self.add
("switch({recv}->classid) \{")
670 var last
= types
.last
672 if not self.compiler
.hardening
and t
== last
then
673 self.add
("default: /*{self.compiler.classid(t)}*/")
675 self.add
("case {self.compiler.classid(t)}:")
677 var recv2
= self.autoadapt
(recv
, t
)
678 var ta
= a
.intro
.static_mtype
.as(not null)
679 ta
= self.resolve_for
(ta
, recv2
)
680 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
683 if self.compiler
.hardening
then
684 self.add
("default: /* Bug*/")
690 redef fun init_instance
(mtype
)
692 mtype
= self.anchor
(mtype
).as(MClassType)
693 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
694 debug
"problem: {mtype} was detected dead"
696 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
701 redef fun type_test
(value
, mtype
, tag
)
703 mtype
= self.anchor
(mtype
)
704 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mtype
) then
705 debug
"problem: {mtype} was detected cast-dead"
709 var types
= self.collect_types
(value
)
710 var res
= self.new_var
(bool_type
)
712 self.add
("/* isa {mtype} on {value.inspect} */")
713 if value
.mtype
.ctype
!= "val*" then
714 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
715 self.add
("{res} = 1;")
717 self.add
("{res} = 0;")
721 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
722 self.add
("if ({value} == NULL) \{")
723 if mtype
isa MNullableType then
724 self.add
("{res} = 1; /* isa {mtype} */")
726 self.add
("{res} = 0; /* not isa {mtype} */")
730 self.add
("switch({value}->classid) \{")
732 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
733 self.add
("case {self.compiler.classid(t)}: /* {t} */")
736 self.add
("{res} = 1;")
739 self.add
("{res} = 0;")
745 redef fun is_same_type_test
(value1
, value2
)
747 var res
= self.new_var
(bool_type
)
748 if value2
.mtype
.ctype
== "val*" then
749 if value1
.mtype
.ctype
== "val*" then
750 self.add
"{res} = {value1}->classid == {value2}->classid;"
752 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
755 if value1
.mtype
.ctype
== "val*" then
756 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
757 else if value1
.mcasttype
== value2
.mcasttype
then
758 self.add
"{res} = 1;"
760 self.add
"{res} = 0;"
766 redef fun class_name_string
(value
)
768 var res
= self.get_name
("var_class_name")
769 self.add_decl
("const char* {res};")
770 if value
.mtype
.ctype
== "val*" then
771 self.add
"{res} = class_names[{value}->classid];"
773 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
778 redef fun equal_test
(value1
, value2
)
780 var res
= self.new_var
(bool_type
)
781 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
786 if value1
.mtype
.ctype
!= "val*" then
787 if value2
.mtype
== value1
.mtype
then
788 self.add
("{res} = {value1} == {value2};")
789 else if value2
.mtype
.ctype
!= "val*" then
790 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
792 var mtype1
= value1
.mtype
.as(MClassType)
793 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
794 self.add
("if ({res}) \{")
795 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
799 var s
= new Array[String]
800 for t
in self.compiler
.live_primitive_types
do
801 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
802 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
803 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
806 self.add
("{res} = {value1} == {value2};")
808 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
814 redef fun array_instance
(array
, elttype
)
816 elttype
= self.anchor
(elttype
)
817 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
818 var res
= self.init_instance
(arraytype
)
819 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
820 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
822 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
823 for i
in [0..array
.length
[ do
824 var r
= self.autobox
(array
[i
], elttype
)
825 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
827 var length
= self.int_instance
(array
.length
)
828 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
834 # A runtime function customized on a specific monomrph receiver type
835 private class CustomizedRuntimeFunction
836 super AbstractRuntimeFunction
838 redef type COMPILER: GlobalCompiler
839 redef type VISITOR: GlobalCompilerVisitor
841 # The considered reciever
842 # (usually is a live type but no strong guarantee)
845 init(mmethoddef
: MMethodDef, recv
: MClassType)
851 redef fun build_c_name
853 var res
= self.c_name_cache
854 if res
!= null then return res
855 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
856 res
= self.mmethoddef
.c_name
858 res
= "{mmethoddef.c_name}__{recv.c_name}"
860 self.c_name_cache
= res
864 # used in the compiler worklist
867 if not o
isa CustomizedRuntimeFunction then return false
868 if self.mmethoddef
!= o
.mmethoddef
then return false
869 if self.recv
!= o
.recv
then return false
873 # used in the compiler work-list
874 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
878 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
879 return self.mmethoddef
.to_s
881 return "{self.mmethoddef}@{self.recv}"
885 # compile the code customized for the reciever
886 redef fun compile_to_c
(compiler
)
889 var mmethoddef
= self.mmethoddef
890 if not recv
.is_subtype
(compiler
.mainmodule
, null, mmethoddef
.mclassdef
.bound_mtype
) then
891 print
("problem: why do we compile {self} for {recv}?")
895 var v
= compiler
.new_visitor
896 var selfvar
= new RuntimeVariable("self", recv
, recv
)
897 if compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
898 selfvar
.is_exact
= true
900 var arguments
= new Array[RuntimeVariable]
901 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
904 var sig
= new FlatBuffer
905 var comment
= new FlatBuffer
906 var ret
= mmethoddef
.msignature
.return_mtype
908 ret
= v
.resolve_for
(ret
, selfvar
)
909 sig
.append
("{ret.ctype} ")
910 else if mmethoddef
.mproperty
.is_new
then
912 sig
.append
("{ret.ctype} ")
916 sig
.append
(self.c_name
)
917 sig
.append
("({recv.ctype} {selfvar}")
918 comment
.append
("(self: {recv}")
919 arguments
.add
(selfvar
)
920 for i
in [0..mmethoddef
.msignature
.arity
[ do
921 var mtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
922 if i
== mmethoddef
.msignature
.vararg_rank
then
923 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
925 mtype
= v
.resolve_for
(mtype
, selfvar
)
926 comment
.append
(", {mtype}")
927 sig
.append
(", {mtype.ctype} p{i}")
928 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
929 arguments
.add
(argvar
)
934 comment
.append
(": {ret}")
936 compiler
.header
.add_decl
("{sig};")
938 v
.add_decl
("/* method {self} for {comment} */")
939 v
.add_decl
("{sig} \{")
940 #v.add("printf(\"method {self} for {comment}\\n\");")
942 frame
.returnvar
= v
.new_var
(ret
)
944 frame
.returnlabel
= v
.get_name
("RET_LABEL")
946 mmethoddef
.compile_inside_to_c
(v
, arguments
)
948 v
.add
("{frame.returnlabel.as(not null)}:;")
950 v
.add
("return {frame.returnvar.as(not null)};")
953 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})"
956 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
958 var ret
= self.mmethoddef
.msignature
.return_mtype
959 if self.mmethoddef
.mproperty
.is_new
then
963 ret
= v
.resolve_for
(ret
, arguments
.first
)
965 if self.mmethoddef
.can_inline
(v
) then
966 var frame
= new Frame(v
, self.mmethoddef
, self.recv
, arguments
)
967 frame
.returnlabel
= v
.get_name
("RET_LABEL")
969 frame
.returnvar
= v
.new_var
(ret
)
971 var old_frame
= v
.frame
973 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
974 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
975 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
978 return frame
.returnvar
980 v
.adapt_signature
(self.mmethoddef
, arguments
)
981 v
.compiler
.todo
(self)
983 v
.add
("{self.c_name}({arguments.join(",")});")
986 var res
= v
.new_var
(ret
)
987 v
.add
("{res} = {self.c_name}({arguments.join(",")});")