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
)
51 compiler
.generate_check_init_instance
(t
)
53 compiler
.generate_box_instance
(t
)
57 # The main function of the C
58 compiler
.compile_main_function
60 # Compile until all runtime_functions are visited
61 while not compiler
.todos
.is_empty
do
62 var m
= compiler
.todos
.shift
63 self.toolcontext
.info
("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
64 m
.compile_to_c
(compiler
)
66 self.toolcontext
.info
("Total methods to compile to C: {compiler.seen.length}", 2)
68 compiler
.display_stats
71 self.toolcontext
.info
("*** END GENERATING C: {time1-time0} ***", 2)
72 write_and_make
(compiler
)
76 # Compiler that use global compilation and perform hard optimisations like:
81 super AbstractCompiler
83 redef type VISITOR: GlobalCompilerVisitor
85 # The result of the RTA (used to know live types and methods)
86 var runtime_type_analysis
: RapidTypeAnalysis
88 init(mainmodule
: MModule, modelbuilder
: ModelBuilder, runtime_type_analysis
: RapidTypeAnalysis)
90 super(mainmodule
, modelbuilder
)
91 var file
= new_file
("{mainmodule.name}.nitgg")
92 self.header
= new CodeWriter(file
)
93 self.runtime_type_analysis
= runtime_type_analysis
94 self.live_primitive_types
= new Array[MClassType]
95 for t
in runtime_type_analysis
.live_types
do
96 if t
.ctype
!= "val*" then
97 self.live_primitive_types
.add
(t
)
102 # Compile class names (for the class_name and output_class_name methods)
103 protected fun compile_class_names
do
105 self.header
.add_decl
("extern const char const * class_names[];")
106 v
.add
("const char const * class_names[] = \{")
107 for t
in self.runtime_type_analysis
.live_types
do
108 v
.add
("\"{t}\
", /* {self.classid(t)} */")
113 # Return the C symbol associated to a live type runtime
114 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
115 fun classid
(mtype
: MClassType): String
117 if self.classids
.has_key
(mtype
) then
118 return self.classids
[mtype
]
120 print
"No classid for {mtype}"
125 protected var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
127 # Declaration of structures the live Nit types
128 # Each live type is generated as an independent C `struct` type.
129 # They only share a common first field `classid` used to implement the polymorphism.
130 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val` that contains only the `classid` field.
131 redef fun compile_header_structs
do
132 self.header
.add_decl
("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
135 # Subset of runtime_type_analysis.live_types that contains only primitive types
136 # Used to implement the equal test
137 var live_primitive_types
: Array[MClassType]
139 # Add a new todo task
140 fun todo
(m
: AbstractRuntimeFunction)
142 if seen
.has
(m
) then return
147 # runtime_functions that need to be compiled
148 private var todos
: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
150 # runtime_functions already seen (todo or done)
151 private var seen
: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
153 # Declare C structures and identifiers for a runtime class
154 fun declare_runtimeclass
(mtype
: MClassType)
157 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
158 v
.add_decl
("/* runtime class {mtype} */")
159 var idnum
= classids
.length
160 var idname
= "ID_" + mtype
.c_name
161 self.classids
[mtype
] = idname
162 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
164 v
.add_decl
("struct {mtype.c_name} \{")
165 v
.add_decl
("int classid; /* must be {idname} */")
167 if mtype
.mclass
.name
== "NativeArray" then
168 # NativeArrays are just a instance header followed by an array of values
169 v
.add_decl
("{mtype.arguments.first.ctype} values[1];")
172 if mtype
.ctype
!= "val*" then
173 # Is the Nit type is native then the struct is a box with two fields:
174 # * the `classid` to be polymorph
175 # * the `value` that contains the native value.
176 v
.add_decl
("{mtype.ctype} value;")
179 # Collect all attributes and associate them a field in the structure.
180 # Note: we do not try to optimize the order and helps CC to optimize the client code.
181 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
182 for p
in cd
.intro_mproperties
do
183 if not p
isa MAttribute then continue
184 var t
= p
.intro
.static_mtype
.as(not null)
185 t
= t
.anchor_to
(self.mainmodule
, mtype
)
186 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
192 # Generate the init-instance of a live type (allocate + init-instance)
193 fun generate_init_instance
(mtype
: MClassType)
195 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
196 assert mtype
.ctype
== "val*"
197 var v
= self.new_visitor
199 var is_native_array
= mtype
.mclass
.name
== "NativeArray"
202 if is_native_array
then
208 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig});")
209 v
.add_decl
("/* allocate {mtype} */")
210 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
211 var res
= v
.new_var
(mtype
)
213 if is_native_array
then
214 var mtype_elt
= mtype
.arguments
.first
215 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
217 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
219 v
.add
("{res}->classid = {self.classid(mtype)};")
221 self.generate_init_attr
(v
, res
, mtype
)
222 v
.add
("return {res};")
226 redef fun generate_check_init_instance
(mtype
)
228 if self.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
230 var v
= self.new_visitor
231 var res
= new RuntimeVariable("self", mtype
, mtype
)
232 self.header
.add_decl
("void CHECK_NEW_{mtype.c_name}({mtype.ctype});")
233 v
.add_decl
("/* allocate {mtype} */")
234 v
.add_decl
("void CHECK_NEW_{mtype.c_name}({mtype.ctype} {res}) \{")
235 self.generate_check_attr
(v
, res
, mtype
)
239 fun generate_box_instance
(mtype
: MClassType)
241 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
242 assert mtype
.ctype
!= "val*"
243 var v
= self.new_visitor
245 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
246 v
.add_decl
("/* allocate {mtype} */")
247 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
248 v
.add
("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
249 v
.add
("res->classid = {self.classid(mtype)};")
250 v
.add
("res->value = value;")
251 v
.add
("return (val*)res;")
256 redef fun new_visitor
do return new GlobalCompilerVisitor(self)
258 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
261 # A visitor on the AST of property definition that generate the C code.
262 # Because of inlining, a visitor can visit more than one property.
263 class GlobalCompilerVisitor
264 super AbstractCompilerVisitor
266 redef type COMPILER: GlobalCompiler
268 redef fun autobox
(value
, mtype
)
270 if value
.mtype
== mtype
then
272 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
274 else if value
.mtype
.ctype
== "val*" then
275 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
276 else if mtype
.ctype
== "val*" then
277 var valtype
= value
.mtype
.as(MClassType)
278 var res
= self.new_var
(mtype
)
279 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
280 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
281 self.add
("printf(\"Dead code executed
!\\n\
"); show_backtrace(1);")
284 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
287 # Bad things will appen!
288 var res
= self.new_var
(mtype
)
289 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
290 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); show_backtrace(1);")
295 # The runtime types that are acceptable for a given receiver.
296 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
298 var mtype
= recv
.mcasttype
299 if recv
.is_exact
then
300 assert mtype
isa MClassType
301 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
305 var cache
= self.compiler
.collect_types_cache
306 if cache
.has_key
(mtype
) then
309 var types
= new Array[MClassType]
310 var mainmodule
= self.compiler
.mainmodule
311 for t
in self.compiler
.runtime_type_analysis
.live_types
do
312 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
319 redef fun native_array_def
(pname
, ret_type
, arguments
)
321 var elttype
= arguments
.first
.mtype
322 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
323 if pname
== "[]" then
324 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
326 else if pname
== "[]=" then
327 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
329 else if pname
== "copy_to" then
330 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
331 self.add
("memcpy({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
336 redef fun calloc_array
(ret_type
, arguments
)
338 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
341 redef fun send
(m
, args
)
343 var types
= self.collect_types
(args
.first
)
345 var res
: nullable RuntimeVariable
346 var ret
= m
.intro
.msignature
.return_mtype
348 ret
= args
.first
.mtype
349 res
= self.new_var
(ret
)
350 else if ret
== null then
353 ret
= self.resolve_for
(ret
, args
.first
)
354 res
= self.new_var
(ret
)
357 self.add
("/* send {m} on {args.first.inspect} */")
358 if args
.first
.mtype
.ctype
!= "val*" then
359 var mclasstype
= args
.first
.mtype
.as(MClassType)
360 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
361 self.add
("/* skip, no method {m} */")
364 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
365 var res2
= self.call
(propdef
, mclasstype
, args
)
366 if res
!= null then self.assign
(res
, res2
.as(not null))
369 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or m
.name
== "==" or m
.name
== "!="
370 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
371 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
372 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
373 if m
.name
== "==" then
375 if args
[1].mcasttype
isa MNullableType then
376 self.add
("{res} = ({args[1]} == NULL);")
377 else if args
[1].mcasttype
isa MNullType then
378 self.add
("{res} = 1; /* is null */")
380 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
382 else if m
.name
== "!=" then
384 if args
[1].mcasttype
isa MNullableType then
385 self.add
("{res} = ({args[1]} != NULL);")
386 else if args
[1].mcasttype
isa MNullType then
387 self.add
("{res} = 0; /* is null */")
389 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
392 self.add_abort
("Reciever is null")
396 if types
.is_empty
then
398 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
399 self.bugtype
(args
.first
)
404 self.add
("switch({args.first}->classid) \{")
405 var last
= types
.last
406 var defaultpropdef
: nullable MMethodDef = null
408 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
409 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
410 defaultpropdef
= propdef
413 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
414 self.add
("default: /* test {t} */")
416 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
418 var res2
= self.call
(propdef
, t
, args
)
419 if res
!= null then self.assign
(res
, res2
.as(not null))
422 if defaultpropdef
!= null then
423 self.add
("default: /* default is Object */")
424 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
425 if res
!= null then self.assign
(res
, res2
.as(not null))
426 else if self.compiler
.hardening
then
427 self.add
("default: /* bug */")
428 self.bugtype
(args
.first
)
434 fun check_valid_reciever
(recvtype
: MClassType)
436 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
437 print
"{recvtype} is not a live type"
441 # Subpart of old call function
443 # Checks if the type of the receiver is valid and corrects it if necessary
444 private fun get_recvtype
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): MClassType
446 check_valid_reciever
(recvtype
)
447 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
448 if m
.mclassdef
.mclass
.name
== "Object" and recvtype
.ctype
== "val*" then
449 recvtype
= m
.mclassdef
.bound_mtype
454 # Subpart of old call function
455 # Gets the receiver boxed and casted if necessary
456 private fun get_recv
(recvtype
: MClassType, args
: Array[RuntimeVariable]): RuntimeVariable
458 return self.autoadapt
(self.autobox
(args
.first
, recvtype
), recvtype
)
461 # Finalizes a call to a method ´m´ on type ´recvtype´ with arguments ´args´
462 private fun finalize_call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
464 if args
.length
!= m
.msignature
.arity
+ 1 then # because of self
465 add
("printf(\"NOT YET IMPLEMENTED: Invalid arity
for {m}. {args.length} arguments given
.\\n\
"); show_backtrace(1);")
466 debug
("NOT YET IMPLEMENTED: Invalid arity for {m}. {args.length} arguments given.")
470 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
471 return rm
.call
(self, args
)
474 redef fun call
(m
, recvtype
, args
)
476 var recv_type
= get_recvtype
(m
, recvtype
, args
)
477 var recv
= get_recv
(recv_type
, args
)
478 var new_args
= args
.to_a
479 self.varargize
(m
, m
.msignature
.as(not null), new_args
)
480 new_args
.first
= recv
481 return finalize_call
(m
, recv_type
, new_args
)
484 # Does a call without encapsulating varargs into an array
485 # Avoids multiple encapsulation when calling a super in a variadic function
486 fun call_without_varargize
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
488 var recv_type
= get_recvtype
(m
, recvtype
, args
)
489 var recv
= get_recv
(recv_type
, args
)
490 var new_args
= args
.to_a
491 new_args
.first
= recv
492 return finalize_call
(m
, recv_type
, new_args
)
495 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
497 var types
= self.collect_types
(args
.first
)
499 var res
: nullable RuntimeVariable
500 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
504 ret
= self.resolve_for
(ret
, args
.first
)
505 res
= self.new_var
(ret
)
508 self.add
("/* super {m} on {args.first.inspect} */")
509 if args
.first
.mtype
.ctype
!= "val*" then
510 var mclasstype
= args
.first
.mtype
.as(MClassType)
511 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
512 self.add
("/* skip, no method {m} */")
515 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
516 var res2
= self.call_without_varargize
(propdef
, mclasstype
, args
)
517 if res
!= null then self.assign
(res
, res2
.as(not null))
521 if types
.is_empty
then
523 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
524 self.bugtype
(args
.first
)
529 self.add
("switch({args.first}->classid) \{")
530 var last
= types
.last
532 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
533 if not self.compiler
.hardening
and t
== last
then
534 self.add
("default: /* test {t} */")
536 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
538 var res2
= self.call_without_varargize
(propdef
, t
, args
)
539 if res
!= null then self.assign
(res
, res2
.as(not null))
542 if self.compiler
.hardening
then
543 self.add
("default: /* bug */")
544 self.bugtype
(args
.first
)
550 redef fun adapt_signature
(m
, args
)
552 var recv
= args
.first
553 for i
in [0..m
.msignature
.arity
[ do
554 var t
= m
.msignature
.mparameters
[i
].mtype
555 if i
== m
.msignature
.vararg_rank
then
558 t
= self.resolve_for
(t
, recv
)
559 args
[i
+1] = self.autobox
(args
[i
+1], t
)
563 # FIXME: this is currently buggy since recv is not exact
564 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
566 elttype
= self.resolve_for
(elttype
, recv
)
567 return self.array_instance
(varargs
, elttype
)
570 fun bugtype
(recv
: RuntimeVariable)
572 if recv
.mtype
.ctype
!= "val*" then return
573 self.add
("fprintf(stderr, \"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
574 self.add
("show_backtrace(1);")
577 redef fun isset_attribute
(a
, recv
)
579 check_recv_notnull
(recv
)
581 var types
= self.collect_types
(recv
)
582 var res
= self.new_var
(bool_type
)
584 if types
.is_empty
then
585 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
589 self.add
("/* isset {a} on {recv.inspect} */")
590 self.add
("switch({recv}->classid) \{")
591 var last
= types
.last
593 if not self.compiler
.hardening
and t
== last
then
594 self.add
("default: /*{self.compiler.classid(t)}*/")
596 self.add
("case {self.compiler.classid(t)}:")
598 var recv2
= self.autoadapt
(recv
, t
)
599 var ta
= a
.intro
.static_mtype
.as(not null)
600 ta
= self.resolve_for
(ta
, recv2
)
601 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
602 if not ta
isa MNullableType then
603 if ta
.ctype
== "val*" then
604 self.add
("{res} = ({attr} != NULL);")
606 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
611 if self.compiler
.hardening
then
612 self.add
("default: /* Bug */")
620 redef fun read_attribute
(a
, recv
)
622 check_recv_notnull
(recv
)
624 var types
= self.collect_types
(recv
)
626 var ret
= a
.intro
.static_mtype
.as(not null)
627 ret
= self.resolve_for
(ret
, recv
)
628 var res
= self.new_var
(ret
)
630 if types
.is_empty
then
631 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
635 self.add
("/* read {a} on {recv.inspect} */")
636 self.add
("switch({recv}->classid) \{")
637 var last
= types
.last
639 if not self.compiler
.hardening
and t
== last
then
640 self.add
("default: /*{self.compiler.classid(t)}*/")
642 self.add
("case {self.compiler.classid(t)}:")
644 var recv2
= self.autoadapt
(recv
, t
)
645 var ta
= a
.intro
.static_mtype
.as(not null)
646 ta
= self.resolve_for
(ta
, recv2
)
647 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
648 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then
649 if ta
.ctype
== "val*" then
650 self.add
("if ({res2} == NULL) \{")
651 self.add_abort
("Uninitialized attribute {a.name}")
654 self.add
("/*NOTYET isset on primitive attributes*/")
657 self.assign
(res
, res2
)
660 if self.compiler
.hardening
then
661 self.add
("default: /* Bug */")
669 redef fun write_attribute
(a
, recv
, value
)
671 check_recv_notnull
(recv
)
673 var types
= self.collect_types
(recv
)
675 if types
.is_empty
then
676 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
680 self.add
("/* write {a} on {recv.inspect} */")
681 self.add
("switch({recv}->classid) \{")
682 var last
= types
.last
684 if not self.compiler
.hardening
and t
== last
then
685 self.add
("default: /*{self.compiler.classid(t)}*/")
687 self.add
("case {self.compiler.classid(t)}:")
689 var recv2
= self.autoadapt
(recv
, t
)
690 var ta
= a
.intro
.static_mtype
.as(not null)
691 ta
= self.resolve_for
(ta
, recv2
)
692 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
695 if self.compiler
.hardening
then
696 self.add
("default: /* Bug*/")
702 redef fun init_instance
(mtype
)
704 mtype
= self.anchor
(mtype
).as(MClassType)
705 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
706 debug
"problem: {mtype} was detected dead"
708 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
713 redef fun type_test
(value
, mtype
, tag
)
715 mtype
= self.anchor
(mtype
)
716 var mclasstype
= mtype
717 if mtype
isa MNullableType then mclasstype
= mtype
.mtype
718 assert mclasstype
isa MClassType
719 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mclasstype
) then
720 debug
"problem: {mtype} was detected cast-dead"
724 var types
= self.collect_types
(value
)
725 var res
= self.new_var
(bool_type
)
727 self.add
("/* isa {mtype} on {value.inspect} */")
728 if value
.mtype
.ctype
!= "val*" then
729 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
730 self.add
("{res} = 1;")
732 self.add
("{res} = 0;")
736 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
737 self.add
("if ({value} == NULL) \{")
738 if mtype
isa MNullableType then
739 self.add
("{res} = 1; /* isa {mtype} */")
741 self.add
("{res} = 0; /* not isa {mtype} */")
745 self.add
("switch({value}->classid) \{")
747 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
748 self.add
("case {self.compiler.classid(t)}: /* {t} */")
751 self.add
("{res} = 1;")
754 self.add
("{res} = 0;")
760 redef fun is_same_type_test
(value1
, value2
)
762 var res
= self.new_var
(bool_type
)
763 if value2
.mtype
.ctype
== "val*" then
764 if value1
.mtype
.ctype
== "val*" then
765 self.add
"{res} = {value1}->classid == {value2}->classid;"
767 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
770 if value1
.mtype
.ctype
== "val*" then
771 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
772 else if value1
.mcasttype
== value2
.mcasttype
then
773 self.add
"{res} = 1;"
775 self.add
"{res} = 0;"
781 redef fun class_name_string
(value
)
783 var res
= self.get_name
("var_class_name")
784 self.add_decl
("const char* {res};")
785 if value
.mtype
.ctype
== "val*" then
786 self.add
"{res} = class_names[{value}->classid];"
788 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
793 redef fun equal_test
(value1
, value2
)
795 var res
= self.new_var
(bool_type
)
796 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
801 if value1
.mtype
.ctype
!= "val*" then
802 if value2
.mtype
== value1
.mtype
then
803 self.add
("{res} = {value1} == {value2};")
804 else if value2
.mtype
.ctype
!= "val*" then
805 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
807 var mtype1
= value1
.mtype
.as(MClassType)
808 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
809 self.add
("if ({res}) \{")
810 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
814 var s
= new Array[String]
815 for t
in self.compiler
.live_primitive_types
do
816 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
817 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
818 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
821 self.add
("{res} = {value1} == {value2};")
823 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
829 redef fun check_init_instance
(recv
, mtype
)
831 if self.compiler
.modelbuilder
.toolcontext
.opt_no_check_initialization
.value
then return
833 mtype
= self.anchor
(mtype
).as(MClassType)
834 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
835 debug
"problem: {mtype} was detected dead"
838 self.add
("CHECK_NEW_{mtype.c_name}({recv});")
841 redef fun array_instance
(array
, elttype
)
843 elttype
= self.anchor
(elttype
)
844 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
845 var res
= self.init_instance
(arraytype
)
846 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
847 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
849 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
850 for i
in [0..array
.length
[ do
851 var r
= self.autobox
(array
[i
], elttype
)
852 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
854 var length
= self.int_instance
(array
.length
)
855 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
856 self.check_init_instance
(res
, arraytype
)
862 # A runtime function customized on a specific monomrph receiver type
863 private class CustomizedRuntimeFunction
864 super AbstractRuntimeFunction
866 redef type COMPILER: GlobalCompiler
867 redef type VISITOR: GlobalCompilerVisitor
869 # The considered reciever
870 # (usually is a live type but no strong guarantee)
873 init(mmethoddef
: MMethodDef, recv
: MClassType)
879 redef fun build_c_name
881 var res
= self.c_name_cache
882 if res
!= null then return res
883 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
884 res
= self.mmethoddef
.c_name
886 res
= "{mmethoddef.c_name}__{recv.c_name}"
888 self.c_name_cache
= res
892 # used in the compiler worklist
895 if not o
isa CustomizedRuntimeFunction then return false
896 if self.mmethoddef
!= o
.mmethoddef
then return false
897 if self.recv
!= o
.recv
then return false
901 # used in the compiler work-list
902 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
906 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
907 return self.mmethoddef
.to_s
909 return "{self.mmethoddef}@{self.recv}"
913 # compile the code customized for the reciever
914 redef fun compile_to_c
(compiler
)
917 var mmethoddef
= self.mmethoddef
918 if not recv
.is_subtype
(compiler
.mainmodule
, null, mmethoddef
.mclassdef
.bound_mtype
) then
919 print
("problem: why do we compile {self} for {recv}?")
923 var v
= compiler
.new_visitor
924 var selfvar
= new RuntimeVariable("self", recv
, recv
)
925 if compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
926 selfvar
.is_exact
= true
928 var arguments
= new Array[RuntimeVariable]
929 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
933 var comment
= new Buffer
934 var ret
= mmethoddef
.msignature
.return_mtype
936 ret
= v
.resolve_for
(ret
, selfvar
)
937 sig
.append
("{ret.ctype} ")
938 else if mmethoddef
.mproperty
.is_new
then
940 sig
.append
("{ret.ctype} ")
944 sig
.append
(self.c_name
)
945 sig
.append
("({recv.ctype} {selfvar}")
946 comment
.append
("(self: {recv}")
947 arguments
.add
(selfvar
)
948 for i
in [0..mmethoddef
.msignature
.arity
[ do
949 var mtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
950 if i
== mmethoddef
.msignature
.vararg_rank
then
951 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
953 mtype
= v
.resolve_for
(mtype
, selfvar
)
954 comment
.append
(", {mtype}")
955 sig
.append
(", {mtype.ctype} p{i}")
956 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
957 arguments
.add
(argvar
)
962 comment
.append
(": {ret}")
964 compiler
.header
.add_decl
("{sig};")
966 v
.add_decl
("/* method {self} for {comment} */")
967 v
.add_decl
("{sig} \{")
968 #v.add("printf(\"method {self} for {comment}\\n\");")
970 frame
.returnvar
= v
.new_var
(ret
)
972 frame
.returnlabel
= v
.get_name
("RET_LABEL")
974 mmethoddef
.compile_inside_to_c
(v
, arguments
)
976 v
.add
("{frame.returnlabel.as(not null)}:;")
978 v
.add
("return {frame.returnvar.as(not null)};")
983 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
985 var ret
= self.mmethoddef
.msignature
.return_mtype
986 if self.mmethoddef
.mproperty
.is_new
then
990 ret
= v
.resolve_for
(ret
, arguments
.first
)
992 if self.mmethoddef
.can_inline
(v
) then
993 var frame
= new Frame(v
, self.mmethoddef
, self.recv
, arguments
)
994 frame
.returnlabel
= v
.get_name
("RET_LABEL")
996 frame
.returnvar
= v
.new_var
(ret
)
998 var old_frame
= v
.frame
1000 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
1001 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
1002 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
1005 return frame
.returnvar
1007 v
.adapt_signature
(self.mmethoddef
, arguments
)
1008 v
.compiler
.todo
(self)
1010 v
.add
("{self.c_name}({arguments.join(",")});")
1013 var res
= v
.new_var
(ret
)
1014 v
.add
("{res} = {self.c_name}({arguments.join(",")});")