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 if mainmodule
.model
.get_mclasses_by_name
("Pointer") != null then
65 runtime_type_analysis
.live_types
.add
(mainmodule
.pointer_type
)
67 for t
in runtime_type_analysis
.live_types
do
68 compiler
.declare_runtimeclass
(t
)
71 compiler
.compile_class_names
73 # Init instance code (allocate and init-arguments)
74 for t
in runtime_type_analysis
.live_types
do
75 if t
.ctype
== "val*" then
76 compiler
.generate_init_instance
(t
)
77 if t
.mclass
.kind
== extern_kind
then
78 compiler
.generate_box_instance
(t
)
81 compiler
.generate_box_instance
(t
)
85 # The main function of the C
86 compiler
.compile_nitni_global_ref_functions
87 compiler
.compile_main_function
89 # Compile until all runtime_functions are visited
90 while not compiler
.todos
.is_empty
do
91 var m
= compiler
.todos
.shift
92 self.toolcontext
.info
("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
93 m
.compile_to_c
(compiler
)
95 self.toolcontext
.info
("Total methods to compile to C: {compiler.seen.length}", 2)
97 compiler
.display_stats
100 self.toolcontext
.info
("*** END GENERATING C: {time1-time0} ***", 2)
101 write_and_make
(compiler
)
105 # Compiler that use global compilation and perform hard optimisations like:
110 super AbstractCompiler
112 redef type VISITOR: GlobalCompilerVisitor
114 # The result of the RTA (used to know live types and methods)
115 var runtime_type_analysis
: RapidTypeAnalysis
119 var file
= new_file
("{mainmodule.c_name}.nitgg")
120 self.header
= new CodeWriter(file
)
121 self.live_primitive_types
= new Array[MClassType]
122 for t
in runtime_type_analysis
.live_types
do
123 if t
.ctype
!= "val*" or t
.mclass
.name
== "Pointer" then
124 self.live_primitive_types
.add
(t
)
129 # Compile class names (for the class_name and output_class_name methods)
130 protected fun compile_class_names
do
132 self.header
.add_decl
("extern const char *class_names[];")
133 v
.add
("const char *class_names[] = \{")
134 for t
in self.runtime_type_analysis
.live_types
do
135 v
.add
("\"{t}\
", /* {self.classid(t)} */")
140 # Return the C symbol associated to a live type runtime
141 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
142 fun classid
(mtype
: MClassType): String
144 if self.classids
.has_key
(mtype
) then
145 return self.classids
[mtype
]
147 print
"No classid for {mtype}"
152 protected var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
154 # Declaration of structures the live Nit types
155 # Each live type is generated as an independent C `struct` type.
156 # They only share a common first field `classid` used to implement the polymorphism.
157 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val` that contains only the `classid` field.
158 redef fun compile_header_structs
do
159 self.header
.add_decl
("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
162 # Subset of runtime_type_analysis.live_types that contains only primitive types
163 # Used to implement the equal test
164 var live_primitive_types
: Array[MClassType] is noinit
166 # Add a new todo task
167 fun todo
(m
: AbstractRuntimeFunction)
169 if seen
.has
(m
) then return
174 # runtime_functions that need to be compiled
175 private var todos
: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
177 # runtime_functions already seen (todo or done)
178 private var seen
: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
180 # Declare C structures and identifiers for a runtime class
181 fun declare_runtimeclass
(mtype
: MClassType)
184 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
185 v
.add_decl
("/* runtime class {mtype} */")
186 var idnum
= classids
.length
187 var idname
= "ID_" + mtype
.c_name
188 self.classids
[mtype
] = idname
189 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
191 v
.add_decl
("struct {mtype.c_name} \{")
192 v
.add_decl
("int classid; /* must be {idname} */")
194 if mtype
.mclass
.name
== "NativeArray" then
195 # NativeArrays are just a instance header followed by an array of values
196 v
.add_decl
("int length;")
197 v
.add_decl
("{mtype.arguments.first.ctype} values[1];")
200 if mtype
.ctype_extern
!= "val*" then
201 # Is the Nit type is native then the struct is a box with two fields:
202 # * the `classid` to be polymorph
203 # * the `value` that contains the native value.
204 v
.add_decl
("{mtype.ctype_extern} value;")
207 # Collect all attributes and associate them a field in the structure.
208 # Note: we do not try to optimize the order and helps CC to optimize the client code.
209 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
210 for p
in cd
.intro_mproperties
do
211 if not p
isa MAttribute then continue
212 var t
= p
.intro
.static_mtype
.as(not null)
213 t
= t
.anchor_to
(self.mainmodule
, mtype
)
214 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
220 # Generate the init-instance of a live type (allocate + init-instance)
221 fun generate_init_instance
(mtype
: MClassType)
223 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
224 assert mtype
.ctype
== "val*"
225 var v
= self.new_visitor
227 var is_native_array
= mtype
.mclass
.name
== "NativeArray"
230 if is_native_array
then
236 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig});")
237 v
.add_decl
("/* allocate {mtype} */")
238 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
239 var res
= v
.new_var
(mtype
)
241 if is_native_array
then
242 var mtype_elt
= mtype
.arguments
.first
243 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
244 v
.add
("((struct {mtype.c_name}*){res})->length = length;")
246 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
248 v
.add
("{res}->classid = {self.classid(mtype)};")
250 self.generate_init_attr
(v
, res
, mtype
)
252 v
.add
("return {res};")
256 fun generate_box_instance
(mtype
: MClassType)
258 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
259 var v
= self.new_visitor
261 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
262 v
.add_decl
("/* allocate {mtype} */")
263 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
264 v
.add
("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
265 v
.add
("res->classid = {self.classid(mtype)};")
266 v
.add
("res->value = value;")
267 v
.add
("return (val*)res;")
271 redef fun new_visitor
do return new GlobalCompilerVisitor(self)
273 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
275 redef fun compile_nitni_structs
277 self.header
.add_decl
"""
278 struct nitni_instance \{
279 struct nitni_instance *next,
280 *prev; /* adjacent global references in global list */
281 int count; /* number of time this global reference has been marked */
288 # A visitor on the AST of property definition that generate the C code.
289 # Because of inlining, a visitor can visit more than one property.
290 class GlobalCompilerVisitor
291 super AbstractCompilerVisitor
293 redef type COMPILER: GlobalCompiler
295 redef fun autobox
(value
, mtype
)
297 if value
.mtype
== mtype
then
299 else if value
.mtype
.ctype
== "val*" and mtype
.ctype
== "val*" then
301 else if value
.mtype
.ctype
== "val*" then
302 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
303 else if mtype
.ctype
== "val*" then
304 var valtype
= value
.mtype
.as(MClassType)
305 var res
= self.new_var
(mtype
)
306 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
307 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
308 self.add
("PRINT_ERROR(\"Dead code executed
!\\n\
"); show_backtrace(1);")
311 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
313 else if value
.mtype
.ctype
== "void*" and mtype
.ctype
== "void*" then
316 # Bad things will appen!
317 var res
= self.new_var
(mtype
)
318 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
319 self.add
("PRINT_ERROR(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); show_backtrace(1);")
324 redef fun unbox_extern
(value
, mtype
)
326 if mtype
isa MClassType and mtype
.mclass
.kind
== extern_kind
and
327 mtype
.mclass
.name
!= "NativeString" then
328 var res
= self.new_var_extern
(mtype
)
329 self.add
"{res} = ((struct {mtype.c_name}*){value})->value; /* unboxing {value.mtype} */"
336 redef fun box_extern
(value
, mtype
)
338 if not mtype
isa MClassType or mtype
.mclass
.kind
!= extern_kind
or
339 mtype
.mclass
.name
== "NativeString" then return value
341 var valtype
= value
.mtype
.as(MClassType)
342 var res
= self.new_var
(mtype
)
343 if not compiler
.runtime_type_analysis
.live_types
.has
(value
.mtype
.as(MClassType)) then
344 self.add
("/*no boxing of {value.mtype}: {value.mtype} is not live! */")
345 self.add
("PRINT_ERROR(\"Dead code executed
!\\n\
"); show_backtrace(1);")
348 self.add
("{res} = BOX_{valtype.c_name}({value}); /* boxing {value.mtype} */")
352 # The runtime types that are acceptable for a given receiver.
353 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
355 var mtype
= recv
.mcasttype
356 if recv
.is_exact
then
357 assert mtype
isa MClassType
358 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
362 var cache
= self.compiler
.collect_types_cache
363 if cache
.has_key
(mtype
) then
366 var types
= new Array[MClassType]
367 var mainmodule
= self.compiler
.mainmodule
368 for t
in self.compiler
.runtime_type_analysis
.live_types
do
369 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
376 redef fun native_array_def
(pname
, ret_type
, arguments
)
378 var elttype
= arguments
.first
.mtype
379 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
380 if pname
== "[]" then
381 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
383 else if pname
== "[]=" then
384 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
386 else if pname
== "length" then
387 self.ret
(self.new_expr
("((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->length", ret_type
.as(not null)))
389 else if pname
== "copy_to" then
390 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
391 self.add
("memmove({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
396 redef fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
398 var ret_type
= self.get_class
("NativeArray").get_mtype
([elttype
])
399 ret_type
= anchor
(ret_type
).as(MClassType)
400 return self.new_expr
("NEW_{ret_type.c_name}({length})", ret_type
)
403 redef fun calloc_array
(ret_type
, arguments
)
405 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
408 redef fun send
(m
, args
)
410 var types
= self.collect_types
(args
.first
)
412 var res
: nullable RuntimeVariable
413 var ret
= m
.intro
.msignature
.return_mtype
417 ret
= self.resolve_for
(ret
, args
.first
)
418 res
= self.new_var
(ret
)
421 self.add
("/* send {m} on {args.first.inspect} */")
422 if args
.first
.mtype
.ctype
!= "val*" then
423 var mclasstype
= args
.first
.mtype
.as(MClassType)
424 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
425 self.add
("/* skip, no method {m} */")
428 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
429 var res2
= self.call
(propdef
, mclasstype
, args
)
430 if res
!= null then self.assign
(res
, res2
.as(not null))
433 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_null
.value
or m
.name
== "==" or m
.name
== "!="
434 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
435 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
436 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
437 if m
.name
== "==" or m
.name
== "is_same_instance" then
439 if args
[1].mcasttype
isa MNullableType then
440 self.add
("{res} = ({args[1]} == NULL);")
441 else if args
[1].mcasttype
isa MNullType then
442 self.add
("{res} = 1; /* is null */")
444 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
446 else if m
.name
== "!=" then
448 if args
[1].mcasttype
isa MNullableType then
449 self.add
("{res} = ({args[1]} != NULL);")
450 else if args
[1].mcasttype
isa MNullType then
451 self.add
("{res} = 0; /* is null */")
453 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
456 self.add_abort
("Receiver is null")
460 if types
.is_empty
then
462 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
463 self.bugtype
(args
.first
)
468 self.add
("switch({args.first}->classid) \{")
469 var last
= types
.last
470 var defaultpropdef
: nullable MMethodDef = null
472 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
473 if propdef
.mclassdef
.mclass
.name
== "Object" and t
.ctype
== "val*" then
474 defaultpropdef
= propdef
477 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
478 self.add
("default: /* test {t} */")
480 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
482 var res2
= self.call
(propdef
, t
, args
)
483 if res
!= null then self.assign
(res
, res2
.as(not null))
486 if defaultpropdef
!= null then
487 self.add
("default: /* default is Object */")
488 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
489 if res
!= null then self.assign
(res
, res2
.as(not null))
490 else if self.compiler
.hardening
then
491 self.add
("default: /* bug */")
492 self.bugtype
(args
.first
)
498 fun check_valid_reciever
(recvtype
: MClassType)
500 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
501 print
"{recvtype} is not a live type"
505 # Subpart of old call function
507 # Checks if the type of the receiver is valid and corrects it if necessary
508 private fun get_recvtype
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): MClassType
510 check_valid_reciever
(recvtype
)
511 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
512 if m
.mproperty
.is_toplevel
then
513 # Do not customize top-level methods
514 recvtype
= m
.mclassdef
.bound_mtype
519 redef fun call
(m
, recvtype
, args
)
521 var recv_type
= get_recvtype
(m
, recvtype
, args
)
522 var recv
= self.autoadapt
(self.autobox
(args
.first
, recvtype
), recvtype
)
523 if m
.is_extern
then recv
= unbox_extern
(recv
, recv_type
)
528 assert args
.length
== m
.msignature
.arity
+ 1 else debug
("Invalid arity for {m}. {args.length} arguments given.")
530 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
531 return rm
.call
(self, args
)
534 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
536 var types
= self.collect_types
(args
.first
)
538 var res
: nullable RuntimeVariable
539 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
543 ret
= self.resolve_for
(ret
, args
.first
)
544 res
= self.new_var
(ret
)
547 self.add
("/* super {m} on {args.first.inspect} */")
548 if args
.first
.mtype
.ctype
!= "val*" then
549 var mclasstype
= args
.first
.mtype
.as(MClassType)
550 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
551 self.add
("/* skip, no method {m} */")
554 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
555 var res2
= self.call
(propdef
, mclasstype
, args
)
556 if res
!= null then self.assign
(res
, res2
.as(not null))
560 if types
.is_empty
then
562 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
563 self.bugtype
(args
.first
)
568 self.add
("switch({args.first}->classid) \{")
569 var last
= types
.last
571 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
572 if not self.compiler
.hardening
and t
== last
then
573 self.add
("default: /* test {t} */")
575 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
577 var res2
= self.call
(propdef
, t
, args
)
578 if res
!= null then self.assign
(res
, res2
.as(not null))
581 if self.compiler
.hardening
then
582 self.add
("default: /* bug */")
583 self.bugtype
(args
.first
)
589 redef fun adapt_signature
(m
, args
)
591 var recv
= args
.first
592 for i
in [0..m
.msignature
.arity
[ do
593 var t
= m
.msignature
.mparameters
[i
].mtype
594 if i
== m
.msignature
.vararg_rank
then
597 t
= self.resolve_for
(t
, recv
)
598 args
[i
+1] = self.autobox
(args
[i
+1], t
)
602 redef fun unbox_signature_extern
(m
, args
)
604 var recv
= args
.first
605 for i
in [0..m
.msignature
.arity
[ do
606 var t
= m
.msignature
.mparameters
[i
].mtype
607 if i
== m
.msignature
.vararg_rank
then
610 t
= self.resolve_for
(t
, recv
)
611 if m
.is_extern
then args
[i
+1] = self.unbox_extern
(args
[i
+1], t
)
615 # FIXME: this is currently buggy since recv is not exact
616 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
618 elttype
= self.resolve_for
(elttype
, recv
)
619 return self.array_instance
(varargs
, elttype
)
622 fun bugtype
(recv
: RuntimeVariable)
624 if recv
.mtype
.ctype
!= "val*" then return
625 self.add
("PRINT_ERROR(\"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
626 self.add
("show_backtrace(1);")
629 redef fun isset_attribute
(a
, recv
)
631 check_recv_notnull
(recv
)
633 var types
= self.collect_types
(recv
)
634 var res
= self.new_var
(bool_type
)
636 if types
.is_empty
then
637 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
641 self.add
("/* isset {a} on {recv.inspect} */")
642 self.add
("switch({recv}->classid) \{")
643 var last
= types
.last
645 if not self.compiler
.hardening
and t
== last
then
646 self.add
("default: /*{self.compiler.classid(t)}*/")
648 self.add
("case {self.compiler.classid(t)}:")
650 var recv2
= self.autoadapt
(recv
, t
)
651 var ta
= a
.intro
.static_mtype
.as(not null)
652 ta
= self.resolve_for
(ta
, recv2
)
653 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
654 if not ta
isa MNullableType then
655 if ta
.ctype
== "val*" then
656 self.add
("{res} = ({attr} != NULL);")
658 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
663 if self.compiler
.hardening
then
664 self.add
("default: /* Bug */")
672 redef fun read_attribute
(a
, recv
)
674 check_recv_notnull
(recv
)
676 var types
= self.collect_types
(recv
)
678 var ret
= a
.intro
.static_mtype
.as(not null)
679 ret
= self.resolve_for
(ret
, recv
)
680 var res
= self.new_var
(ret
)
682 if types
.is_empty
then
683 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
687 self.add
("/* read {a} on {recv.inspect} */")
688 self.add
("switch({recv}->classid) \{")
689 var last
= types
.last
691 if not self.compiler
.hardening
and t
== last
then
692 self.add
("default: /*{self.compiler.classid(t)}*/")
694 self.add
("case {self.compiler.classid(t)}:")
696 var recv2
= self.autoadapt
(recv
, t
)
697 var ta
= a
.intro
.static_mtype
.as(not null)
698 ta
= self.resolve_for
(ta
, recv2
)
699 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
700 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_attr_isset
.value
then
701 if ta
.ctype
== "val*" then
702 self.add
("if ({res2} == NULL) \{")
703 self.add_abort
("Uninitialized attribute {a.name}")
706 self.add
("/*NOTYET isset on primitive attributes*/")
709 self.assign
(res
, res2
)
712 if self.compiler
.hardening
then
713 self.add
("default: /* Bug */")
721 redef fun write_attribute
(a
, recv
, value
)
723 check_recv_notnull
(recv
)
725 var types
= self.collect_types
(recv
)
727 if types
.is_empty
then
728 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
732 self.add
("/* write {a} on {recv.inspect} */")
733 self.add
("switch({recv}->classid) \{")
734 var last
= types
.last
736 if not self.compiler
.hardening
and t
== last
then
737 self.add
("default: /*{self.compiler.classid(t)}*/")
739 self.add
("case {self.compiler.classid(t)}:")
741 var recv2
= self.autoadapt
(recv
, t
)
742 var ta
= a
.intro
.static_mtype
.as(not null)
743 ta
= self.resolve_for
(ta
, recv2
)
744 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
747 if self.compiler
.hardening
then
748 self.add
("default: /* Bug*/")
754 redef fun init_instance
(mtype
)
756 mtype
= self.anchor
(mtype
).as(MClassType)
757 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
758 debug
"problem: {mtype} was detected dead"
760 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
765 redef fun type_test
(value
, mtype
, tag
)
767 mtype
= self.anchor
(mtype
)
768 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mtype
) then
769 debug
"problem: {mtype} was detected cast-dead"
773 var types
= self.collect_types
(value
)
774 var res
= self.new_var
(bool_type
)
776 self.add
("/* isa {mtype} on {value.inspect} */")
777 if value
.mtype
.ctype
!= "val*" then
778 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
779 self.add
("{res} = 1;")
781 self.add
("{res} = 0;")
785 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
786 self.add
("if ({value} == NULL) \{")
787 if mtype
isa MNullableType then
788 self.add
("{res} = 1; /* isa {mtype} */")
790 self.add
("{res} = 0; /* not isa {mtype} */")
794 self.add
("switch({value}->classid) \{")
796 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
797 self.add
("case {self.compiler.classid(t)}: /* {t} */")
800 self.add
("{res} = 1;")
803 self.add
("{res} = 0;")
809 redef fun is_same_type_test
(value1
, value2
)
811 var res
= self.new_var
(bool_type
)
812 if value2
.mtype
.ctype
== "val*" then
813 if value1
.mtype
.ctype
== "val*" then
814 self.add
"{res} = {value1}->classid == {value2}->classid;"
816 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
819 if value1
.mtype
.ctype
== "val*" then
820 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
821 else if value1
.mcasttype
== value2
.mcasttype
then
822 self.add
"{res} = 1;"
824 self.add
"{res} = 0;"
830 redef fun class_name_string
(value
)
832 var res
= self.get_name
("var_class_name")
833 self.add_decl
("const char* {res};")
834 if value
.mtype
.ctype
== "val*" then
835 self.add
"{res} = class_names[{value}->classid];"
837 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
842 redef fun equal_test
(value1
, value2
)
844 var res
= self.new_var
(bool_type
)
845 if value2
.mtype
.ctype
!= "val*" and value1
.mtype
.ctype
== "val*" then
850 if value1
.mtype
.ctype
!= "val*" then
851 if value2
.mtype
== value1
.mtype
then
852 self.add
("{res} = {value1} == {value2};")
853 else if value2
.mtype
.ctype
!= "val*" then
854 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
856 var mtype1
= value1
.mtype
.as(MClassType)
857 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
858 self.add
("if ({res}) \{")
859 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
863 var s
= new Array[String]
864 for t
in self.compiler
.live_primitive_types
do
865 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
866 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
867 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
870 if self.compiler
.mainmodule
.model
.get_mclasses_by_name
("Pointer") != null then
871 var pointer_type
= self.compiler
.mainmodule
.pointer_type
872 if value1
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) or
873 value2
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) then
874 s
.add
"(((struct {pointer_type.c_name}*){value1})->value == ((struct {pointer_type.c_name}*){value2})->value)"
879 self.add
("{res} = {value1} == {value2};")
881 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
887 redef fun array_instance
(array
, elttype
)
889 elttype
= self.anchor
(elttype
)
890 var arraytype
= self.get_class
("Array").get_mtype
([elttype
])
891 var res
= self.init_instance
(arraytype
)
892 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
893 var nat
= self.new_var
(self.get_class
("NativeArray").get_mtype
([elttype
]))
895 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
896 for i
in [0..array
.length
[ do
897 var r
= self.autobox
(array
[i
], elttype
)
898 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
900 var length
= self.int_instance
(array
.length
)
901 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
907 # A runtime function customized on a specific monomrph receiver type
908 private class CustomizedRuntimeFunction
909 super AbstractRuntimeFunction
911 redef type COMPILER: GlobalCompiler
912 redef type VISITOR: GlobalCompilerVisitor
914 # The considered reciever
915 # (usually is a live type but no strong guarantee)
918 redef fun build_c_name
920 var res
= self.c_name_cache
921 if res
!= null then return res
922 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
923 res
= self.mmethoddef
.c_name
925 res
= "{mmethoddef.c_name}__{recv.c_name}"
927 self.c_name_cache
= res
931 # used in the compiler worklist
934 if not o
isa CustomizedRuntimeFunction then return false
935 if self.mmethoddef
!= o
.mmethoddef
then return false
936 if self.recv
!= o
.recv
then return false
940 # used in the compiler work-list
941 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
945 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
946 return self.mmethoddef
.to_s
948 return "{self.mmethoddef}@{self.recv}"
952 # compile the code customized for the reciever
953 redef fun compile_to_c
(compiler
)
956 var mmethoddef
= self.mmethoddef
957 if not recv
.is_subtype
(compiler
.mainmodule
, null, mmethoddef
.mclassdef
.bound_mtype
) then
958 print
("problem: why do we compile {self} for {recv}?")
962 var v
= compiler
.new_visitor
963 var selfvar
= new RuntimeVariable("self", recv
, recv
)
964 if compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
965 selfvar
.is_exact
= true
967 var arguments
= new Array[RuntimeVariable]
968 var frame
= new Frame(v
, mmethoddef
, recv
, arguments
)
971 var sig
= new FlatBuffer
972 var comment
= new FlatBuffer
973 var ret
= mmethoddef
.msignature
.return_mtype
975 ret
= v
.resolve_for
(ret
, selfvar
)
976 sig
.append
("{ret.ctype} ")
980 sig
.append
(self.c_name
)
981 sig
.append
("({recv.ctype} {selfvar}")
982 comment
.append
("(self: {recv}")
983 arguments
.add
(selfvar
)
984 for i
in [0..mmethoddef
.msignature
.arity
[ do
985 var mtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
986 if i
== mmethoddef
.msignature
.vararg_rank
then
987 mtype
= v
.get_class
("Array").get_mtype
([mtype
])
989 mtype
= v
.resolve_for
(mtype
, selfvar
)
990 comment
.append
(", {mtype}")
991 sig
.append
(", {mtype.ctype} p{i}")
992 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
993 arguments
.add
(argvar
)
998 comment
.append
(": {ret}")
1000 compiler
.header
.add_decl
("{sig};")
1002 v
.add_decl
("/* method {self} for {comment} */")
1003 v
.add_decl
("{sig} \{")
1004 #v.add("printf(\"method {self} for {comment}\\n\");")
1006 frame
.returnvar
= v
.new_var
(ret
)
1008 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1010 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1012 v
.add
("{frame.returnlabel.as(not null)}:;")
1014 v
.add
("return {frame.returnvar.as(not null)};")
1017 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})"
1020 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1022 var ret
= self.mmethoddef
.msignature
.return_mtype
1024 ret
= v
.resolve_for
(ret
, arguments
.first
)
1026 if self.mmethoddef
.can_inline
(v
) then
1027 var frame
= new Frame(v
, self.mmethoddef
, self.recv
, arguments
)
1028 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1030 frame
.returnvar
= v
.new_var
(ret
)
1032 var old_frame
= v
.frame
1034 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
1035 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
1036 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
1039 return frame
.returnvar
1041 v
.adapt_signature
(self.mmethoddef
, arguments
)
1042 v
.compiler
.todo
(self)
1044 v
.add
("{self.c_name}({arguments.join(",")});")
1047 var res
= v
.new_var
(ret
)
1048 v
.add
("{res} = {self.c_name}({arguments.join(",")});")