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;")
242 redef fun new_visitor
do return new GlobalCompilerVisitor(self)
244 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
247 # A visitor on the AST of property definition that generate the C code.
248 # Because of inlining, a visitor can visit more than one property.
249 class GlobalCompilerVisitor
250 super AbstractCompilerVisitor
252 redef type COMPILER: GlobalCompiler
254 redef fun autobox
(value
, mtype
)
256 if value
.mtype
== mtype
then
258 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
260 else if value
.mtype
.ctype
== "val*" then
261 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
262 else if mtype
.ctype
== "val*" then
263 var valtype
= value
.mtype
.as(MClassType)
264 var res
= self.new_var
(mtype
)
265 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
266 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
267 self.add
("printf(\"Dead code executed
!\\n\
"); show_backtrace(1);")
270 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
273 # Bad things will appen!
274 var res
= self.new_var
(mtype
)
275 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
276 self.add
("printf(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); show_backtrace(1);")
281 # The runtime types that are acceptable for a given receiver.
282 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
284 var mtype
= recv
.mcasttype
285 if recv
.is_exact
then
286 assert mtype
isa MClassType
287 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
291 var cache
= self.compiler
.collect_types_cache
292 if cache
.has_key
(mtype
) then
295 var types
= new Array[MClassType]
296 var mainmodule
= self.compiler
.mainmodule
297 for t
in self.compiler
.runtime_type_analysis
.live_types
do
298 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
305 redef fun native_array_def
(pname
, ret_type
, arguments
)
307 var elttype
= arguments
.first
.mtype
308 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
309 if pname
== "[]" then
310 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
312 else if pname
== "[]=" then
313 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
315 else if pname
== "copy_to" then
316 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
317 self.add
("memcpy({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
322 redef fun calloc_array
(ret_type
, arguments
)
324 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
327 redef fun send
(m
, args
)
329 var types
= self.collect_types
(args
.first
)
331 var res
: nullable RuntimeVariable
332 var ret
= m
.intro
.msignature
.return_mtype
334 ret
= args
.first
.mtype
335 res
= self.new_var
(ret
)
336 else if ret
== null then
339 ret
= self.resolve_for
(ret
, args
.first
)
340 res
= self.new_var
(ret
)
343 self.add
("/* send {m} on {args.first.inspect} */")
344 if args
.first
.mtype
.ctype
!= "val*" then
345 var mclasstype
= args
.first
.mtype
.as(MClassType)
346 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
347 self.add
("/* skip, no method {m} */")
350 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
351 var res2
= self.call
(propdef
, mclasstype
, args
)
352 if res
!= null then self.assign
(res
, res2
.as(not null))
355 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or m
.name
== "==" or m
.name
== "!="
356 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
357 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
358 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
359 if m
.name
== "==" then
361 if args
[1].mcasttype
isa MNullableType then
362 self.add
("{res} = ({args[1]} == NULL);")
363 else if args
[1].mcasttype
isa MNullType then
364 self.add
("{res} = 1; /* is null */")
366 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
368 else if m
.name
== "!=" then
370 if args
[1].mcasttype
isa MNullableType then
371 self.add
("{res} = ({args[1]} != NULL);")
372 else if args
[1].mcasttype
isa MNullType then
373 self.add
("{res} = 0; /* is null */")
375 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
378 self.add_abort
("Reciever is null")
382 if types
.is_empty
then
384 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
385 self.bugtype
(args
.first
)
390 self.add
("switch({args.first}->classid) \{")
391 var last
= types
.last
392 var defaultpropdef
: nullable MMethodDef = null
394 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
395 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
396 defaultpropdef
= propdef
399 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
400 self.add
("default: /* test {t} */")
402 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
404 var res2
= self.call
(propdef
, t
, args
)
405 if res
!= null then self.assign
(res
, res2
.as(not null))
408 if defaultpropdef
!= null then
409 self.add
("default: /* default is Object */")
410 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
411 if res
!= null then self.assign
(res
, res2
.as(not null))
412 else if self.compiler
.hardening
then
413 self.add
("default: /* bug */")
414 self.bugtype
(args
.first
)
420 fun check_valid_reciever
(recvtype
: MClassType)
422 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
423 print
"{recvtype} is not a live type"
427 # Subpart of old call function
429 # Checks if the type of the receiver is valid and corrects it if necessary
430 private fun get_recvtype
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): MClassType
432 check_valid_reciever
(recvtype
)
433 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
434 if m
.mclassdef
.mclass
.name
== "Object" and recvtype
.ctype
== "val*" then
435 recvtype
= m
.mclassdef
.bound_mtype
440 # Subpart of old call function
441 # Gets the receiver boxed and casted if necessary
442 private fun get_recv
(recvtype
: MClassType, args
: Array[RuntimeVariable]): RuntimeVariable
444 return self.autoadapt
(self.autobox
(args
.first
, recvtype
), recvtype
)
447 # Finalizes a call to a method ´m´ on type ´recvtype´ with arguments ´args´
448 private fun finalize_call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
450 if args
.length
!= m
.msignature
.arity
+ 1 then # because of self
451 add
("printf(\"NOT YET IMPLEMENTED: Invalid arity
for {m}. {args.length} arguments given
.\\n\
"); show_backtrace(1);")
452 debug
("NOT YET IMPLEMENTED: Invalid arity for {m}. {args.length} arguments given.")
456 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
457 return rm
.call
(self, args
)
460 redef fun call
(m
, recvtype
, args
)
462 var recv_type
= get_recvtype
(m
, recvtype
, args
)
463 var recv
= get_recv
(recv_type
, args
)
464 var new_args
= args
.to_a
465 self.varargize
(m
, m
.msignature
.as(not null), new_args
)
466 new_args
.first
= recv
467 return finalize_call
(m
, recv_type
, new_args
)
470 # Does a call without encapsulating varargs into an array
471 # Avoids multiple encapsulation when calling a super in a variadic function
472 fun call_without_varargize
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
474 var recv_type
= get_recvtype
(m
, recvtype
, args
)
475 var recv
= get_recv
(recv_type
, args
)
476 var new_args
= args
.to_a
477 new_args
.first
= recv
478 return finalize_call
(m
, recv_type
, new_args
)
481 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
483 var types
= self.collect_types
(args
.first
)
485 var res
: nullable RuntimeVariable
486 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
490 ret
= self.resolve_for
(ret
, args
.first
)
491 res
= self.new_var
(ret
)
494 self.add
("/* super {m} on {args.first.inspect} */")
495 if args
.first
.mtype
.ctype
!= "val*" then
496 var mclasstype
= args
.first
.mtype
.as(MClassType)
497 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
498 self.add
("/* skip, no method {m} */")
501 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
502 var res2
= self.call_without_varargize
(propdef
, mclasstype
, args
)
503 if res
!= null then self.assign
(res
, res2
.as(not null))
507 if types
.is_empty
then
509 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
510 self.bugtype
(args
.first
)
515 self.add
("switch({args.first}->classid) \{")
516 var last
= types
.last
518 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
519 if not self.compiler
.hardening
and t
== last
then
520 self.add
("default: /* test {t} */")
522 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
524 var res2
= self.call_without_varargize
(propdef
, t
, args
)
525 if res
!= null then self.assign
(res
, res2
.as(not null))
528 if self.compiler
.hardening
then
529 self.add
("default: /* bug */")
530 self.bugtype
(args
.first
)
536 redef fun adapt_signature
(m
, args
)
538 var recv
= args
.first
539 for i
in [0..m
.msignature
.arity
[ do
540 var t
= m
.msignature
.mparameters
[i
].mtype
541 if i
== m
.msignature
.vararg_rank
then
544 t
= self.resolve_for
(t
, recv
)
545 args
[i
+1] = self.autobox
(args
[i
+1], t
)
549 # FIXME: this is currently buggy since recv is not exact
550 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
552 elttype
= self.resolve_for
(elttype
, recv
)
553 return self.array_instance
(varargs
, elttype
)
556 fun bugtype
(recv
: RuntimeVariable)
558 if recv
.mtype
.ctype
!= "val*" then return
559 self.add
("fprintf(stderr, \"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
560 self.add
("show_backtrace(1);")
563 redef fun isset_attribute
(a
, recv
)
565 check_recv_notnull
(recv
)
567 var types
= self.collect_types
(recv
)
568 var res
= self.new_var
(bool_type
)
570 if types
.is_empty
then
571 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
575 self.add
("/* isset {a} on {recv.inspect} */")
576 self.add
("switch({recv}->classid) \{")
577 var last
= types
.last
579 if not self.compiler
.hardening
and t
== last
then
580 self.add
("default: /*{self.compiler.classid(t)}*/")
582 self.add
("case {self.compiler.classid(t)}:")
584 var recv2
= self.autoadapt
(recv
, t
)
585 var ta
= a
.intro
.static_mtype
.as(not null)
586 ta
= self.resolve_for
(ta
, recv2
)
587 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
588 if not ta
isa MNullableType then
589 if ta
.ctype
== "val*" then
590 self.add
("{res} = ({attr} != NULL);")
592 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
597 if self.compiler
.hardening
then
598 self.add
("default: /* Bug */")
606 redef fun read_attribute
(a
, recv
)
608 check_recv_notnull
(recv
)
610 var types
= self.collect_types
(recv
)
612 var ret
= a
.intro
.static_mtype
.as(not null)
613 ret
= self.resolve_for
(ret
, recv
)
614 var res
= self.new_var
(ret
)
616 if types
.is_empty
then
617 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
621 self.add
("/* read {a} on {recv.inspect} */")
622 self.add
("switch({recv}->classid) \{")
623 var last
= types
.last
625 if not self.compiler
.hardening
and t
== last
then
626 self.add
("default: /*{self.compiler.classid(t)}*/")
628 self.add
("case {self.compiler.classid(t)}:")
630 var recv2
= self.autoadapt
(recv
, t
)
631 var ta
= a
.intro
.static_mtype
.as(not null)
632 ta
= self.resolve_for
(ta
, recv2
)
633 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
634 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then
635 if ta
.ctype
== "val*" then
636 self.add
("if ({res2} == NULL) \{")
637 self.add_abort
("Uninitialized attribute {a.name}")
640 self.add
("/*NOTYET isset on primitive attributes*/")
643 self.assign
(res
, res2
)
646 if self.compiler
.hardening
then
647 self.add
("default: /* Bug */")
655 redef fun write_attribute
(a
, recv
, value
)
657 check_recv_notnull
(recv
)
659 var types
= self.collect_types
(recv
)
661 if types
.is_empty
then
662 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
666 self.add
("/* write {a} on {recv.inspect} */")
667 self.add
("switch({recv}->classid) \{")
668 var last
= types
.last
670 if not self.compiler
.hardening
and t
== last
then
671 self.add
("default: /*{self.compiler.classid(t)}*/")
673 self.add
("case {self.compiler.classid(t)}:")
675 var recv2
= self.autoadapt
(recv
, t
)
676 var ta
= a
.intro
.static_mtype
.as(not null)
677 ta
= self.resolve_for
(ta
, recv2
)
678 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
681 if self.compiler
.hardening
then
682 self.add
("default: /* Bug*/")
688 redef fun init_instance
(mtype
)
690 mtype
= self.anchor
(mtype
).as(MClassType)
691 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
692 debug
"problem: {mtype} was detected dead"
694 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
699 redef fun type_test
(value
, mtype
, tag
)
701 mtype
= self.anchor
(mtype
)
702 var mclasstype
= mtype
703 if mtype
isa MNullableType then mclasstype
= mtype
.mtype
704 assert mclasstype
isa MClassType
705 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mclasstype
) then
706 debug
"problem: {mtype} was detected cast-dead"
710 var types
= self.collect_types
(value
)
711 var res
= self.new_var
(bool_type
)
713 self.add
("/* isa {mtype} on {value.inspect} */")
714 if value
.mtype
.ctype
!= "val*" then
715 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
716 self.add
("{res} = 1;")
718 self.add
("{res} = 0;")
722 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
723 self.add
("if ({value} == NULL) \{")
724 if mtype
isa MNullableType then
725 self.add
("{res} = 1; /* isa {mtype} */")
727 self.add
("{res} = 0; /* not isa {mtype} */")
731 self.add
("switch({value}->classid) \{")
733 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
734 self.add
("case {self.compiler.classid(t)}: /* {t} */")
737 self.add
("{res} = 1;")
740 self.add
("{res} = 0;")
746 redef fun is_same_type_test
(value1
, value2
)
748 var res
= self.new_var
(bool_type
)
749 if value2
.mtype
.ctype
== "val*" then
750 if value1
.mtype
.ctype
== "val*" then
751 self.add
"{res} = {value1}->classid == {value2}->classid;"
753 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
756 if value1
.mtype
.ctype
== "val*" then
757 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
758 else if value1
.mcasttype
== value2
.mcasttype
then
759 self.add
"{res} = 1;"
761 self.add
"{res} = 0;"
767 redef fun class_name_string
(value
)
769 var res
= self.get_name
("var_class_name")
770 self.add_decl
("const char* {res};")
771 if value
.mtype
.ctype
== "val*" then
772 self.add
"{res} = class_names[{value}->classid];"
774 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
779 redef fun equal_test
(value1
, value2
)
781 var res
= self.new_var
(bool_type
)
782 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
787 if value1
.mtype
.ctype
!= "val*" then
788 if value2
.mtype
== value1
.mtype
then
789 self.add
("{res} = {value1} == {value2};")
790 else if value2
.mtype
.ctype
!= "val*" then
791 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
793 var mtype1
= value1
.mtype
.as(MClassType)
794 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
795 self.add
("if ({res}) \{")
796 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
800 var s
= new Array[String]
801 for t
in self.compiler
.live_primitive_types
do
802 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
803 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
804 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
807 self.add
("{res} = {value1} == {value2};")
809 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
815 redef fun array_instance
(array
, elttype
)
817 elttype
= self.anchor
(elttype
)
818 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
819 var res
= self.init_instance
(arraytype
)
820 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
821 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
823 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
824 for i
in [0..array
.length
[ do
825 var r
= self.autobox
(array
[i
], elttype
)
826 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
828 var length
= self.int_instance
(array
.length
)
829 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
835 # A runtime function customized on a specific monomrph receiver type
836 private class CustomizedRuntimeFunction
837 super AbstractRuntimeFunction
839 redef type COMPILER: GlobalCompiler
840 redef type VISITOR: GlobalCompilerVisitor
842 # The considered reciever
843 # (usually is a live type but no strong guarantee)
846 init(mmethoddef
: MMethodDef, recv
: MClassType)
852 redef fun build_c_name
854 var res
= self.c_name_cache
855 if res
!= null then return res
856 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
857 res
= self.mmethoddef
.c_name
859 res
= "{mmethoddef.c_name}__{recv.c_name}"
861 self.c_name_cache
= res
865 # used in the compiler worklist
868 if not o
isa CustomizedRuntimeFunction then return false
869 if self.mmethoddef
!= o
.mmethoddef
then return false
870 if self.recv
!= o
.recv
then return false
874 # used in the compiler work-list
875 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
879 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
880 return self.mmethoddef
.to_s
882 return "{self.mmethoddef}@{self.recv}"
886 # compile the code customized for the reciever
887 redef fun compile_to_c
(compiler
)
890 var mmethoddef
= self.mmethoddef
891 if not recv
.is_subtype
(compiler
.mainmodule
, null, mmethoddef
.mclassdef
.bound_mtype
) then
892 print
("problem: why do we compile {self} for {recv}?")
896 var v
= compiler
.new_visitor
897 var selfvar
= new RuntimeVariable("self", recv
, recv
)
898 if compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
899 selfvar
.is_exact
= true
901 var arguments
= new Array[RuntimeVariable]
902 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
906 var comment
= new Buffer
907 var ret
= mmethoddef
.msignature
.return_mtype
909 ret
= v
.resolve_for
(ret
, selfvar
)
910 sig
.append
("{ret.ctype} ")
911 else if mmethoddef
.mproperty
.is_new
then
913 sig
.append
("{ret.ctype} ")
917 sig
.append
(self.c_name
)
918 sig
.append
("({recv.ctype} {selfvar}")
919 comment
.append
("(self: {recv}")
920 arguments
.add
(selfvar
)
921 for i
in [0..mmethoddef
.msignature
.arity
[ do
922 var mtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
923 if i
== mmethoddef
.msignature
.vararg_rank
then
924 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
926 mtype
= v
.resolve_for
(mtype
, selfvar
)
927 comment
.append
(", {mtype}")
928 sig
.append
(", {mtype.ctype} p{i}")
929 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
930 arguments
.add
(argvar
)
935 comment
.append
(": {ret}")
937 compiler
.header
.add_decl
("{sig};")
939 v
.add_decl
("/* method {self} for {comment} */")
940 v
.add_decl
("{sig} \{")
941 #v.add("printf(\"method {self} for {comment}\\n\");")
943 frame
.returnvar
= v
.new_var
(ret
)
945 frame
.returnlabel
= v
.get_name
("RET_LABEL")
947 mmethoddef
.compile_inside_to_c
(v
, arguments
)
949 v
.add
("{frame.returnlabel.as(not null)}:;")
951 v
.add
("return {frame.returnvar.as(not null)};")
954 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})"
957 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
959 var ret
= self.mmethoddef
.msignature
.return_mtype
960 if self.mmethoddef
.mproperty
.is_new
then
964 ret
= v
.resolve_for
(ret
, arguments
.first
)
966 if self.mmethoddef
.can_inline
(v
) then
967 var frame
= new Frame(v
, self.mmethoddef
, self.recv
, arguments
)
968 frame
.returnlabel
= v
.get_name
("RET_LABEL")
970 frame
.returnvar
= v
.new_var
(ret
)
972 var old_frame
= v
.frame
974 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
975 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
976 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
979 return frame
.returnvar
981 v
.adapt_signature
(self.mmethoddef
, arguments
)
982 v
.compiler
.todo
(self)
984 v
.add
("{self.c_name}({arguments.join(",")});")
987 var res
= v
.new_var
(ret
)
988 v
.add
("{res} = {self.c_name}({arguments.join(",")});")