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 ToolContext
31 var opt_global
= new OptionBool("Use global compilation", "--global")
33 var global_compiler_phase
= new GlobalCompilerPhase(self, null)
37 option_context
.add_option
(opt_global
)
41 class GlobalCompilerPhase
43 redef fun process_mainmodule
(mainmodule
, given_mmodules
) do
44 if not toolcontext
.opt_global
.value
then return
46 var modelbuilder
= toolcontext
.modelbuilder
47 var analysis
= modelbuilder
.do_rapid_type_analysis
(mainmodule
)
48 modelbuilder
.run_global_compiler
(mainmodule
, analysis
)
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)
59 self.toolcontext
.info
("*** GENERATING C ***", 1)
61 var compiler
= new GlobalCompiler(mainmodule
, self, runtime_type_analysis
)
62 compiler
.compile_header
64 for t
in runtime_type_analysis
.live_types
do
65 compiler
.declare_runtimeclass
(t
)
68 compiler
.compile_class_names
70 # Init instance code (allocate and init-arguments)
71 for t
in runtime_type_analysis
.live_types
do
72 if t
.ctype
== "val*" then
73 compiler
.generate_init_instance
(t
)
75 compiler
.generate_box_instance
(t
)
79 # The main function of the C
80 compiler
.compile_main_function
82 # Compile until all runtime_functions are visited
83 while not compiler
.todos
.is_empty
do
84 var m
= compiler
.todos
.shift
85 self.toolcontext
.info
("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
86 m
.compile_to_c
(compiler
)
88 self.toolcontext
.info
("Total methods to compile to C: {compiler.seen.length}", 2)
90 compiler
.display_stats
93 self.toolcontext
.info
("*** END GENERATING C: {time1-time0} ***", 2)
94 write_and_make
(compiler
)
98 # Compiler that use global compilation and perform hard optimisations like:
103 super AbstractCompiler
105 redef type VISITOR: GlobalCompilerVisitor
107 # The result of the RTA (used to know live types and methods)
108 var runtime_type_analysis
: RapidTypeAnalysis
110 init(mainmodule
: MModule, modelbuilder
: ModelBuilder, runtime_type_analysis
: RapidTypeAnalysis)
112 super(mainmodule
, modelbuilder
)
113 var file
= new_file
("{mainmodule.name}.nitgg")
114 self.header
= new CodeWriter(file
)
115 self.runtime_type_analysis
= runtime_type_analysis
116 self.live_primitive_types
= new Array[MClassType]
117 for t
in runtime_type_analysis
.live_types
do
118 if t
.ctype
!= "val*" then
119 self.live_primitive_types
.add
(t
)
124 # Compile class names (for the class_name and output_class_name methods)
125 protected fun compile_class_names
do
127 self.header
.add_decl
("extern const char *class_names[];")
128 v
.add
("const char *class_names[] = \{")
129 for t
in self.runtime_type_analysis
.live_types
do
130 v
.add
("\"{t}\
", /* {self.classid(t)} */")
135 # Return the C symbol associated to a live type runtime
136 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
137 fun classid
(mtype
: MClassType): String
139 if self.classids
.has_key
(mtype
) then
140 return self.classids
[mtype
]
142 print
"No classid for {mtype}"
147 protected var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
149 # Declaration of structures the live Nit types
150 # Each live type is generated as an independent C `struct` type.
151 # They only share a common first field `classid` used to implement the polymorphism.
152 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val` that contains only the `classid` field.
153 redef fun compile_header_structs
do
154 self.header
.add_decl
("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
157 # Subset of runtime_type_analysis.live_types that contains only primitive types
158 # Used to implement the equal test
159 var live_primitive_types
: Array[MClassType]
161 # Add a new todo task
162 fun todo
(m
: AbstractRuntimeFunction)
164 if seen
.has
(m
) then return
169 # runtime_functions that need to be compiled
170 private var todos
: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
172 # runtime_functions already seen (todo or done)
173 private var seen
: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
175 # Declare C structures and identifiers for a runtime class
176 fun declare_runtimeclass
(mtype
: MClassType)
179 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
180 v
.add_decl
("/* runtime class {mtype} */")
181 var idnum
= classids
.length
182 var idname
= "ID_" + mtype
.c_name
183 self.classids
[mtype
] = idname
184 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
186 v
.add_decl
("struct {mtype.c_name} \{")
187 v
.add_decl
("int classid; /* must be {idname} */")
189 if mtype
.mclass
.name
== "NativeArray" then
190 # NativeArrays are just a instance header followed by an array of values
191 v
.add_decl
("int length;")
192 v
.add_decl
("{mtype.arguments.first.ctype} values[1];")
195 if mtype
.ctype
!= "val*" then
196 # Is the Nit type is native then the struct is a box with two fields:
197 # * the `classid` to be polymorph
198 # * the `value` that contains the native value.
199 v
.add_decl
("{mtype.ctype} value;")
202 # Collect all attributes and associate them a field in the structure.
203 # Note: we do not try to optimize the order and helps CC to optimize the client code.
204 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
205 for p
in cd
.intro_mproperties
do
206 if not p
isa MAttribute then continue
207 var t
= p
.intro
.static_mtype
.as(not null)
208 t
= t
.anchor_to
(self.mainmodule
, mtype
)
209 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
215 # Generate the init-instance of a live type (allocate + init-instance)
216 fun generate_init_instance
(mtype
: MClassType)
218 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
219 assert mtype
.ctype
== "val*"
220 var v
= self.new_visitor
222 var is_native_array
= mtype
.mclass
.name
== "NativeArray"
225 if is_native_array
then
231 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig});")
232 v
.add_decl
("/* allocate {mtype} */")
233 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
234 var res
= v
.new_var
(mtype
)
236 if is_native_array
then
237 var mtype_elt
= mtype
.arguments
.first
238 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
239 v
.add
("((struct {mtype.c_name}*){res})->length = length;")
241 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
243 v
.add
("{res}->classid = {self.classid(mtype)};")
245 self.generate_init_attr
(v
, res
, mtype
)
246 v
.add
("return {res};")
250 fun generate_box_instance
(mtype
: MClassType)
252 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
253 assert mtype
.ctype
!= "val*"
254 var v
= self.new_visitor
256 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
257 v
.add_decl
("/* allocate {mtype} */")
258 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
259 v
.add
("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
260 v
.add
("res->classid = {self.classid(mtype)};")
261 v
.add
("res->value = value;")
262 v
.add
("return (val*)res;")
266 redef fun new_visitor
do return new GlobalCompilerVisitor(self)
268 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
270 redef fun compile_nitni_structs
272 self.header
.add_decl
("struct nitni_instance \{ val *value; \};")
276 # A visitor on the AST of property definition that generate the C code.
277 # Because of inlining, a visitor can visit more than one property.
278 class GlobalCompilerVisitor
279 super AbstractCompilerVisitor
281 redef type COMPILER: GlobalCompiler
283 redef fun autobox
(value
, mtype
)
285 if value
.mtype
== mtype
then
287 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
289 else if value
.mtype
.ctype
== "val*" then
290 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
291 else if mtype
.ctype
== "val*" then
292 var valtype
= value
.mtype
.as(MClassType)
293 var res
= self.new_var
(mtype
)
294 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
295 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
296 self.add
("PRINT_ERROR(\"Dead code executed
!\\n\
"); show_backtrace(1);")
299 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
301 else if value
.mtype
.ctype
== "void*" and mtype
.ctype
== "void*" then
304 # Bad things will appen!
305 var res
= self.new_var
(mtype
)
306 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
307 self.add
("PRINT_ERROR(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); show_backtrace(1);")
312 # The runtime types that are acceptable for a given receiver.
313 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
315 var mtype
= recv
.mcasttype
316 if recv
.is_exact
then
317 assert mtype
isa MClassType
318 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
322 var cache
= self.compiler
.collect_types_cache
323 if cache
.has_key
(mtype
) then
326 var types
= new Array[MClassType]
327 var mainmodule
= self.compiler
.mainmodule
328 for t
in self.compiler
.runtime_type_analysis
.live_types
do
329 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
336 redef fun native_array_def
(pname
, ret_type
, arguments
)
338 var elttype
= arguments
.first
.mtype
339 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
340 if pname
== "[]" then
341 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
343 else if pname
== "[]=" then
344 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
346 else if pname
== "length" then
347 self.ret
(self.new_expr
("((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->length", ret_type
.as(not null)))
349 else if pname
== "copy_to" then
350 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
351 self.add
("memcpy({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
356 redef fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
358 var ret_type
= self.get_class
("NativeArray").get_mtype
([elttype
])
359 return self.new_expr
("NEW_{ret_type.c_name}({length})", ret_type
)
362 redef fun calloc_array
(ret_type
, arguments
)
364 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
367 redef fun send
(m
, args
)
369 var types
= self.collect_types
(args
.first
)
371 var res
: nullable RuntimeVariable
372 var ret
= m
.intro
.msignature
.return_mtype
374 ret
= args
.first
.mtype
375 res
= self.new_var
(ret
)
376 else if ret
== null then
379 ret
= self.resolve_for
(ret
, args
.first
)
380 res
= self.new_var
(ret
)
383 self.add
("/* send {m} on {args.first.inspect} */")
384 if args
.first
.mtype
.ctype
!= "val*" then
385 var mclasstype
= args
.first
.mtype
.as(MClassType)
386 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
387 self.add
("/* skip, no method {m} */")
390 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
391 var res2
= self.call
(propdef
, mclasstype
, args
)
392 if res
!= null then self.assign
(res
, res2
.as(not null))
395 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
or m
.name
== "==" or m
.name
== "!="
396 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
397 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
398 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
399 if m
.name
== "==" then
401 if args
[1].mcasttype
isa MNullableType then
402 self.add
("{res} = ({args[1]} == NULL);")
403 else if args
[1].mcasttype
isa MNullType then
404 self.add
("{res} = 1; /* is null */")
406 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
408 else if m
.name
== "!=" then
410 if args
[1].mcasttype
isa MNullableType then
411 self.add
("{res} = ({args[1]} != NULL);")
412 else if args
[1].mcasttype
isa MNullType then
413 self.add
("{res} = 0; /* is null */")
415 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
418 self.add_abort
("Receiver is null")
422 if types
.is_empty
then
424 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
425 self.bugtype
(args
.first
)
430 self.add
("switch({args.first}->classid) \{")
431 var last
= types
.last
432 var defaultpropdef
: nullable MMethodDef = null
434 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
435 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
436 defaultpropdef
= propdef
439 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
440 self.add
("default: /* test {t} */")
442 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
444 var res2
= self.call
(propdef
, t
, args
)
445 if res
!= null then self.assign
(res
, res2
.as(not null))
448 if defaultpropdef
!= null then
449 self.add
("default: /* default is Object */")
450 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
451 if res
!= null then self.assign
(res
, res2
.as(not null))
452 else if self.compiler
.hardening
then
453 self.add
("default: /* bug */")
454 self.bugtype
(args
.first
)
460 fun check_valid_reciever
(recvtype
: MClassType)
462 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
463 print
"{recvtype} is not a live type"
467 # Subpart of old call function
469 # Checks if the type of the receiver is valid and corrects it if necessary
470 private fun get_recvtype
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): MClassType
472 check_valid_reciever
(recvtype
)
473 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
474 if m
.mclassdef
.mclass
.name
== "Object" and recvtype
.ctype
== "val*" then
475 recvtype
= m
.mclassdef
.bound_mtype
480 # Subpart of old call function
481 # Gets the receiver boxed and casted if necessary
482 private fun get_recv
(recvtype
: MClassType, args
: Array[RuntimeVariable]): RuntimeVariable
484 return self.autoadapt
(self.autobox
(args
.first
, recvtype
), recvtype
)
487 # Finalizes a call to a method ´m´ on type ´recvtype´ with arguments ´args´
488 private fun finalize_call
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
490 assert args
.length
== m
.msignature
.arity
+ 1 else debug
("Invalid arity for {m}. {args.length} arguments given.")
492 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
493 return rm
.call
(self, args
)
496 redef fun call
(m
, recvtype
, args
)
498 var recv_type
= get_recvtype
(m
, recvtype
, args
)
499 var recv
= get_recv
(recv_type
, args
)
500 var new_args
= args
.to_a
501 self.varargize
(m
, m
.msignature
.as(not null), new_args
)
502 new_args
.first
= recv
503 return finalize_call
(m
, recv_type
, new_args
)
506 # Does a call without encapsulating varargs into an array
507 # Avoids multiple encapsulation when calling a super in a variadic function
508 fun call_without_varargize
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
510 var recv_type
= get_recvtype
(m
, recvtype
, args
)
511 var recv
= get_recv
(recv_type
, args
)
512 var new_args
= args
.to_a
513 new_args
.first
= recv
514 return finalize_call
(m
, recv_type
, new_args
)
517 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
519 var types
= self.collect_types
(args
.first
)
521 var res
: nullable RuntimeVariable
522 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
526 ret
= self.resolve_for
(ret
, args
.first
)
527 res
= self.new_var
(ret
)
530 self.add
("/* super {m} on {args.first.inspect} */")
531 if args
.first
.mtype
.ctype
!= "val*" then
532 var mclasstype
= args
.first
.mtype
.as(MClassType)
533 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
534 self.add
("/* skip, no method {m} */")
537 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
538 var res2
= self.call_without_varargize
(propdef
, mclasstype
, args
)
539 if res
!= null then self.assign
(res
, res2
.as(not null))
543 if types
.is_empty
then
545 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
546 self.bugtype
(args
.first
)
551 self.add
("switch({args.first}->classid) \{")
552 var last
= types
.last
554 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
555 if not self.compiler
.hardening
and t
== last
then
556 self.add
("default: /* test {t} */")
558 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
560 var res2
= self.call_without_varargize
(propdef
, t
, args
)
561 if res
!= null then self.assign
(res
, res2
.as(not null))
564 if self.compiler
.hardening
then
565 self.add
("default: /* bug */")
566 self.bugtype
(args
.first
)
572 redef fun adapt_signature
(m
, args
)
574 var recv
= args
.first
575 for i
in [0..m
.msignature
.arity
[ do
576 var t
= m
.msignature
.mparameters
[i
].mtype
577 if i
== m
.msignature
.vararg_rank
then
580 t
= self.resolve_for
(t
, recv
)
581 args
[i
+1] = self.autobox
(args
[i
+1], t
)
585 # FIXME: this is currently buggy since recv is not exact
586 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
588 elttype
= self.resolve_for
(elttype
, recv
)
589 return self.array_instance
(varargs
, elttype
)
592 fun bugtype
(recv
: RuntimeVariable)
594 if recv
.mtype
.ctype
!= "val*" then return
595 self.add
("PRINT_ERROR(\"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
596 self.add
("show_backtrace(1);")
599 redef fun isset_attribute
(a
, recv
)
601 check_recv_notnull
(recv
)
603 var types
= self.collect_types
(recv
)
604 var res
= self.new_var
(bool_type
)
606 if types
.is_empty
then
607 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
611 self.add
("/* isset {a} on {recv.inspect} */")
612 self.add
("switch({recv}->classid) \{")
613 var last
= types
.last
615 if not self.compiler
.hardening
and t
== last
then
616 self.add
("default: /*{self.compiler.classid(t)}*/")
618 self.add
("case {self.compiler.classid(t)}:")
620 var recv2
= self.autoadapt
(recv
, t
)
621 var ta
= a
.intro
.static_mtype
.as(not null)
622 ta
= self.resolve_for
(ta
, recv2
)
623 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
624 if not ta
isa MNullableType then
625 if ta
.ctype
== "val*" then
626 self.add
("{res} = ({attr} != NULL);")
628 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
633 if self.compiler
.hardening
then
634 self.add
("default: /* Bug */")
642 redef fun read_attribute
(a
, recv
)
644 check_recv_notnull
(recv
)
646 var types
= self.collect_types
(recv
)
648 var ret
= a
.intro
.static_mtype
.as(not null)
649 ret
= self.resolve_for
(ret
, recv
)
650 var res
= self.new_var
(ret
)
652 if types
.is_empty
then
653 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
657 self.add
("/* read {a} on {recv.inspect} */")
658 self.add
("switch({recv}->classid) \{")
659 var last
= types
.last
661 if not self.compiler
.hardening
and t
== last
then
662 self.add
("default: /*{self.compiler.classid(t)}*/")
664 self.add
("case {self.compiler.classid(t)}:")
666 var recv2
= self.autoadapt
(recv
, t
)
667 var ta
= a
.intro
.static_mtype
.as(not null)
668 ta
= self.resolve_for
(ta
, recv2
)
669 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
670 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_other
.value
then
671 if ta
.ctype
== "val*" then
672 self.add
("if ({res2} == NULL) \{")
673 self.add_abort
("Uninitialized attribute {a.name}")
676 self.add
("/*NOTYET isset on primitive attributes*/")
679 self.assign
(res
, res2
)
682 if self.compiler
.hardening
then
683 self.add
("default: /* Bug */")
691 redef fun write_attribute
(a
, recv
, value
)
693 check_recv_notnull
(recv
)
695 var types
= self.collect_types
(recv
)
697 if types
.is_empty
then
698 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
702 self.add
("/* write {a} on {recv.inspect} */")
703 self.add
("switch({recv}->classid) \{")
704 var last
= types
.last
706 if not self.compiler
.hardening
and t
== last
then
707 self.add
("default: /*{self.compiler.classid(t)}*/")
709 self.add
("case {self.compiler.classid(t)}:")
711 var recv2
= self.autoadapt
(recv
, t
)
712 var ta
= a
.intro
.static_mtype
.as(not null)
713 ta
= self.resolve_for
(ta
, recv2
)
714 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
717 if self.compiler
.hardening
then
718 self.add
("default: /* Bug*/")
724 redef fun init_instance
(mtype
)
726 mtype
= self.anchor
(mtype
).as(MClassType)
727 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
728 debug
"problem: {mtype} was detected dead"
730 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
735 redef fun type_test
(value
, mtype
, tag
)
737 mtype
= self.anchor
(mtype
)
738 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mtype
) then
739 debug
"problem: {mtype} was detected cast-dead"
743 var types
= self.collect_types
(value
)
744 var res
= self.new_var
(bool_type
)
746 self.add
("/* isa {mtype} on {value.inspect} */")
747 if value
.mtype
.ctype
!= "val*" then
748 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
749 self.add
("{res} = 1;")
751 self.add
("{res} = 0;")
755 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
756 self.add
("if ({value} == NULL) \{")
757 if mtype
isa MNullableType then
758 self.add
("{res} = 1; /* isa {mtype} */")
760 self.add
("{res} = 0; /* not isa {mtype} */")
764 self.add
("switch({value}->classid) \{")
766 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
767 self.add
("case {self.compiler.classid(t)}: /* {t} */")
770 self.add
("{res} = 1;")
773 self.add
("{res} = 0;")
779 redef fun is_same_type_test
(value1
, value2
)
781 var res
= self.new_var
(bool_type
)
782 if value2
.mtype
.ctype
== "val*" then
783 if value1
.mtype
.ctype
== "val*" then
784 self.add
"{res} = {value1}->classid == {value2}->classid;"
786 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
789 if value1
.mtype
.ctype
== "val*" then
790 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
791 else if value1
.mcasttype
== value2
.mcasttype
then
792 self.add
"{res} = 1;"
794 self.add
"{res} = 0;"
800 redef fun class_name_string
(value
)
802 var res
= self.get_name
("var_class_name")
803 self.add_decl
("const char* {res};")
804 if value
.mtype
.ctype
== "val*" then
805 self.add
"{res} = class_names[{value}->classid];"
807 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
812 redef fun equal_test
(value1
, value2
)
814 var res
= self.new_var
(bool_type
)
815 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
820 if value1
.mtype
.ctype
!= "val*" then
821 if value2
.mtype
== value1
.mtype
then
822 self.add
("{res} = {value1} == {value2};")
823 else if value2
.mtype
.ctype
!= "val*" then
824 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
826 var mtype1
= value1
.mtype
.as(MClassType)
827 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
828 self.add
("if ({res}) \{")
829 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
833 var s
= new Array[String]
834 for t
in self.compiler
.live_primitive_types
do
835 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
836 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
837 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
840 self.add
("{res} = {value1} == {value2};")
842 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
848 redef fun array_instance
(array
, elttype
)
850 elttype
= self.anchor
(elttype
)
851 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
852 var res
= self.init_instance
(arraytype
)
853 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
854 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
856 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
857 for i
in [0..array
.length
[ do
858 var r
= self.autobox
(array
[i
], elttype
)
859 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
861 var length
= self.int_instance
(array
.length
)
862 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
868 # A runtime function customized on a specific monomrph receiver type
869 private class CustomizedRuntimeFunction
870 super AbstractRuntimeFunction
872 redef type COMPILER: GlobalCompiler
873 redef type VISITOR: GlobalCompilerVisitor
875 # The considered reciever
876 # (usually is a live type but no strong guarantee)
879 init(mmethoddef
: MMethodDef, recv
: MClassType)
885 redef fun build_c_name
887 var res
= self.c_name_cache
888 if res
!= null then return res
889 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
890 res
= self.mmethoddef
.c_name
892 res
= "{mmethoddef.c_name}__{recv.c_name}"
894 self.c_name_cache
= res
898 # used in the compiler worklist
901 if not o
isa CustomizedRuntimeFunction then return false
902 if self.mmethoddef
!= o
.mmethoddef
then return false
903 if self.recv
!= o
.recv
then return false
907 # used in the compiler work-list
908 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
912 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
913 return self.mmethoddef
.to_s
915 return "{self.mmethoddef}@{self.recv}"
919 # compile the code customized for the reciever
920 redef fun compile_to_c
(compiler
)
923 var mmethoddef
= self.mmethoddef
924 if not recv
.is_subtype
(compiler
.mainmodule
, null, mmethoddef
.mclassdef
.bound_mtype
) then
925 print
("problem: why do we compile {self} for {recv}?")
929 var v
= compiler
.new_visitor
930 var selfvar
= new RuntimeVariable("self", recv
, recv
)
931 if compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
932 selfvar
.is_exact
= true
934 var arguments
= new Array[RuntimeVariable]
935 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
938 var sig
= new FlatBuffer
939 var comment
= new FlatBuffer
940 var ret
= mmethoddef
.msignature
.return_mtype
942 ret
= v
.resolve_for
(ret
, selfvar
)
943 sig
.append
("{ret.ctype} ")
944 else if mmethoddef
.mproperty
.is_new
then
946 sig
.append
("{ret.ctype} ")
950 sig
.append
(self.c_name
)
951 sig
.append
("({recv.ctype} {selfvar}")
952 comment
.append
("(self: {recv}")
953 arguments
.add
(selfvar
)
954 for i
in [0..mmethoddef
.msignature
.arity
[ do
955 var mtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
956 if i
== mmethoddef
.msignature
.vararg_rank
then
957 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
959 mtype
= v
.resolve_for
(mtype
, selfvar
)
960 comment
.append
(", {mtype}")
961 sig
.append
(", {mtype.ctype} p{i}")
962 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
963 arguments
.add
(argvar
)
968 comment
.append
(": {ret}")
970 compiler
.header
.add_decl
("{sig};")
972 v
.add_decl
("/* method {self} for {comment} */")
973 v
.add_decl
("{sig} \{")
974 #v.add("printf(\"method {self} for {comment}\\n\");")
976 frame
.returnvar
= v
.new_var
(ret
)
978 frame
.returnlabel
= v
.get_name
("RET_LABEL")
980 mmethoddef
.compile_inside_to_c
(v
, arguments
)
982 v
.add
("{frame.returnlabel.as(not null)}:;")
984 v
.add
("return {frame.returnvar.as(not null)};")
987 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})"
990 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
992 var ret
= self.mmethoddef
.msignature
.return_mtype
993 if self.mmethoddef
.mproperty
.is_new
then
997 ret
= v
.resolve_for
(ret
, arguments
.first
)
999 if self.mmethoddef
.can_inline
(v
) then
1000 var frame
= new Frame(v
, self.mmethoddef
, self.recv
, arguments
)
1001 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1003 frame
.returnvar
= v
.new_var
(ret
)
1005 var old_frame
= v
.frame
1007 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
1008 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
1009 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
1012 return frame
.returnvar
1014 v
.adapt_signature
(self.mmethoddef
, arguments
)
1015 v
.compiler
.todo
(self)
1017 v
.add
("{self.c_name}({arguments.join(",")});")
1020 var res
= v
.new_var
(ret
)
1021 v
.add
("{res} = {self.c_name}({arguments.join(",")});")