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
.do_compilation
63 compiler
.display_stats
66 self.toolcontext
.info
("*** END GENERATING C: {time1-time0} ***", 2)
67 write_and_make
(compiler
)
71 # Compiler that use global compilation and perform hard optimisations like:
76 super AbstractCompiler
78 redef type VISITOR: GlobalCompilerVisitor
80 # The result of the RTA (used to know live types and methods)
81 var runtime_type_analysis
: RapidTypeAnalysis
85 var file
= new_file
("{mainmodule.c_name}.nitgg")
86 self.header
= new CodeWriter(file
)
87 self.live_primitive_types
= new Array[MClassType]
88 for t
in runtime_type_analysis
.live_types
do
89 if t
.is_c_primitive
or t
.mclass
.name
== "Pointer" then
90 self.live_primitive_types
.add
(t
)
95 redef fun do_compilation
99 compiler
.compile_header
101 if mainmodule
.model
.get_mclasses_by_name
("Pointer") != null then
102 runtime_type_analysis
.live_types
.add
(mainmodule
.pointer_type
)
104 for t
in runtime_type_analysis
.live_types
do
105 compiler
.declare_runtimeclass
(t
)
108 compiler
.compile_class_names
110 # Init instance code (allocate and init-arguments)
111 for t
in runtime_type_analysis
.live_types
do
112 if not t
.is_c_primitive
then
113 compiler
.generate_init_instance
(t
)
114 if t
.mclass
.kind
== extern_kind
then
115 compiler
.generate_box_instance
(t
)
118 compiler
.generate_box_instance
(t
)
122 # The main function of the C
123 compiler
.compile_nitni_global_ref_functions
124 compiler
.compile_main_function
126 # Compile until all runtime_functions are visited
127 while not compiler
.todos
.is_empty
do
128 var m
= compiler
.todos
.shift
129 modelbuilder
.toolcontext
.info
("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
130 m
.compile_to_c
(compiler
)
132 modelbuilder
.toolcontext
.info
("Total methods to compile to C: {compiler.seen.length}", 2)
136 # Compile class names (for the class_name and output_class_name methods)
137 protected fun compile_class_names
do
139 self.header
.add_decl
("extern const char *class_names[];")
140 v
.add
("const char *class_names[] = \{")
141 for t
in self.runtime_type_analysis
.live_types
do
142 v
.add
("\"{t}\
", /* {self.classid(t)} */")
147 # Return the C symbol associated to a live type runtime
148 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
149 fun classid
(mtype
: MClassType): String
151 if self.classids
.has_key
(mtype
) then
152 return self.classids
[mtype
]
154 print
"No classid for {mtype}"
159 protected var classids
: HashMap[MClassType, String] = new HashMap[MClassType, String]
161 # Declaration of structures the live Nit types
162 # Each live type is generated as an independent C `struct` type.
163 # They only share a common first field `classid` used to implement the polymorphism.
164 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val` that contains only the `classid` field.
165 redef fun compile_header_structs
do
166 self.header
.add_decl
("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
169 # Subset of runtime_type_analysis.live_types that contains only primitive types
170 # Used to implement the equal test
171 var live_primitive_types
: Array[MClassType] is noinit
173 # Add a new todo task
174 fun todo
(m
: AbstractRuntimeFunction)
176 if seen
.has
(m
) then return
181 # runtime_functions that need to be compiled
182 private var todos
: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
184 # runtime_functions already seen (todo or done)
185 private var seen
: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
187 # Declare C structures and identifiers for a runtime class
188 fun declare_runtimeclass
(mtype
: MClassType)
191 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
192 v
.add_decl
("/* runtime class {mtype} */")
193 var idnum
= classids
.length
194 var idname
= "ID_" + mtype
.c_name
195 self.classids
[mtype
] = idname
196 v
.add_decl
("#define {idname} {idnum} /* {mtype} */")
198 v
.add_decl
("struct {mtype.c_name} \{")
199 v
.add_decl
("int classid; /* must be {idname} */")
201 if mtype
.mclass
.name
== "NativeArray" then
202 # NativeArrays are just a instance header followed by an array of values
203 v
.add_decl
("int length;")
204 v
.add_decl
("{mtype.arguments.first.ctype} values[1];")
207 if mtype
.ctype_extern
!= "val*" then
208 # Is the Nit type is native then the struct is a box with two fields:
209 # * the `classid` to be polymorph
210 # * the `value` that contains the native value.
211 v
.add_decl
("{mtype.ctype_extern} value;")
214 # Collect all attributes and associate them a field in the structure.
215 # Note: we do not try to optimize the order and helps CC to optimize the client code.
216 for cd
in mtype
.collect_mclassdefs
(self.mainmodule
) do
217 for p
in cd
.intro_mproperties
do
218 if not p
isa MAttribute then continue
219 var t
= p
.intro
.static_mtype
.as(not null)
220 t
= t
.anchor_to
(self.mainmodule
, mtype
)
221 v
.add_decl
("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
227 # Generate the init-instance of a live type (allocate + init-instance)
228 fun generate_init_instance
(mtype
: MClassType)
230 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
231 assert not mtype
.is_c_primitive
232 var v
= self.new_visitor
234 var is_native_array
= mtype
.mclass
.name
== "NativeArray"
237 if is_native_array
then
243 self.header
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig});")
244 v
.add_decl
("/* allocate {mtype} */")
245 v
.add_decl
("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
246 var res
= v
.new_var
(mtype
)
248 if is_native_array
then
249 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof(val*));")
250 v
.add
("((struct {mtype.c_name}*){res})->length = length;")
252 v
.add
("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
254 v
.add
("{res}->classid = {self.classid(mtype)};")
256 self.generate_init_attr
(v
, res
, mtype
)
258 v
.add
("return {res};")
262 fun generate_box_instance
(mtype
: MClassType)
264 assert self.runtime_type_analysis
.live_types
.has
(mtype
)
265 var v
= self.new_visitor
267 self.header
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype});")
268 v
.add_decl
("/* allocate {mtype} */")
269 v
.add_decl
("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
270 v
.add
("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
271 v
.add
("res->classid = {self.classid(mtype)};")
272 v
.add
("res->value = value;")
273 v
.add
("return (val*)res;")
277 redef fun new_visitor
do return new GlobalCompilerVisitor(self)
279 private var collect_types_cache
: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
281 redef fun compile_nitni_structs
283 self.header
.add_decl
"""
284 struct nitni_instance \{
285 struct nitni_instance *next,
286 *prev; /* adjacent global references in global list */
287 int count; /* number of time this global reference has been marked */
294 # A visitor on the AST of property definition that generate the C code.
295 # Because of inlining, a visitor can visit more than one property.
296 class GlobalCompilerVisitor
297 super AbstractCompilerVisitor
299 redef type COMPILER: GlobalCompiler
301 redef fun autobox
(value
, mtype
)
303 if value
.mtype
== mtype
then
305 else if not value
.mtype
.is_c_primitive
and not mtype
.is_c_primitive
then
307 else if not value
.mtype
.is_c_primitive
then
308 return self.new_expr
("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype
)
309 else if not mtype
.is_c_primitive
then
310 var valtype
= value
.mtype
.as(MClassType)
311 var res
= self.new_var
(mtype
)
312 if not compiler
.runtime_type_analysis
.live_types
.has
(valtype
) then
313 self.add
("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
314 self.add
("PRINT_ERROR(\"Dead code executed
!\\n\
"); fatal_exit(1);")
317 self.add
("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
319 else if value
.mtype
.ctype
== "void*" and mtype
.ctype
== "void*" then
322 # Bad things will appen!
323 var res
= self.new_var
(mtype
)
324 self.add
("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
325 self.add
("PRINT_ERROR(\"Cast error
: Cannot cast
%s to
%s
.\\n\
", \"{value.mtype}\
", \"{mtype}\
"); fatal_exit(1);")
330 redef fun unbox_extern
(value
, mtype
)
332 if mtype
isa MClassType and mtype
.mclass
.kind
== extern_kind
and
333 mtype
.mclass
.name
!= "NativeString" then
334 var res
= self.new_var_extern
(mtype
)
335 self.add
"{res} = ((struct {mtype.c_name}*){value})->value; /* unboxing {value.mtype} */"
342 redef fun box_extern
(value
, mtype
)
344 if not mtype
isa MClassType or mtype
.mclass
.kind
!= extern_kind
or
345 mtype
.mclass
.name
== "NativeString" then return value
347 var valtype
= value
.mtype
.as(MClassType)
348 var res
= self.new_var
(mtype
)
349 if not compiler
.runtime_type_analysis
.live_types
.has
(value
.mtype
.as(MClassType)) then
350 self.add
("/*no boxing of {value.mtype}: {value.mtype} is not live! */")
351 self.add
("PRINT_ERROR(\"Dead code executed
!\\n\
"); fatal_exit(1);")
354 self.add
("{res} = BOX_{valtype.c_name}({value}); /* boxing {value.mtype} */")
358 # The runtime types that are acceptable for a given receiver.
359 fun collect_types
(recv
: RuntimeVariable): Array[MClassType]
361 var mtype
= recv
.mcasttype
362 if recv
.is_exact
then
363 assert mtype
isa MClassType
364 assert self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
)
368 var cache
= self.compiler
.collect_types_cache
369 if cache
.has_key
(mtype
) then
372 var types
= new Array[MClassType]
373 var mainmodule
= self.compiler
.mainmodule
374 for t
in self.compiler
.runtime_type_analysis
.live_types
do
375 if not t
.is_subtype
(mainmodule
, null, mtype
) then continue
382 redef fun native_array_def
(pname
, ret_type
, arguments
)
384 var elttype
= arguments
.first
.mtype
385 var recv
= "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
386 if pname
== "[]" then
387 self.ret
(self.new_expr
("{recv}[{arguments[1]}]", ret_type
.as(not null)))
389 else if pname
== "[]=" then
390 self.add
("{recv}[{arguments[1]}]={arguments[2]};")
392 else if pname
== "length" then
393 self.ret
(self.new_expr
("((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->length", ret_type
.as(not null)))
395 else if pname
== "copy_to" then
396 var recv1
= "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
397 self.add
("memmove({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
399 else if pname
== "memmove" then
400 # fun memmove(start: Int, length: Int, dest: NativeArray[E], dest_start: Int) is intern do
401 var recv1
= "((struct {arguments[3].mcasttype.c_name}*){arguments[3]})->values"
402 self.add
("memmove({recv1}+{arguments[4]}, {recv}+{arguments[1]}, {arguments[2]}*sizeof({elttype.ctype}));")
408 redef fun native_array_instance
(elttype
: MType, length
: RuntimeVariable): RuntimeVariable
410 var ret_type
= mmodule
.native_array_type
(elttype
)
411 ret_type
= anchor
(ret_type
).as(MClassType)
412 length
= autobox
(length
, compiler
.mainmodule
.int_type
)
413 return self.new_expr
("NEW_{ret_type.c_name}({length})", ret_type
)
416 redef fun native_array_get
(nat
, i
)
418 var recv
= "((struct {nat.mcasttype.c_name}*){nat})->values"
419 var ret_type
= nat
.mcasttype
.as(MClassType).arguments
.first
420 return self.new_expr
("{recv}[{i}]", ret_type
)
423 redef fun native_array_set
(nat
, i
, val
)
425 var recv
= "((struct {nat.mcasttype.c_name}*){nat})->values"
426 self.add
("{recv}[{i}]={val};")
429 redef fun calloc_array
(ret_type
, arguments
)
431 self.ret
(self.new_expr
("NEW_{ret_type.c_name}({arguments[1]})", ret_type
))
434 redef fun send
(m
, args
)
436 var types
= self.collect_types
(args
.first
)
438 var res
: nullable RuntimeVariable
439 var ret
= m
.intro
.msignature
.return_mtype
443 ret
= self.resolve_for
(ret
, args
.first
)
444 res
= self.new_var
(ret
)
447 self.add
("/* send {m} on {args.first.inspect} */")
448 if args
.first
.mtype
.is_c_primitive
then
449 var mclasstype
= args
.first
.mtype
.as(MClassType)
450 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
451 self.add
("/* skip, dead class {mclasstype} */")
454 if not mclasstype
.has_mproperty
(self.compiler
.mainmodule
, m
) then
455 self.add
("/* skip, no method {m} */")
458 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, mclasstype
)
459 var res2
= self.call
(propdef
, mclasstype
, args
)
460 if res
!= null then self.assign
(res
, res2
.as(not null))
463 var consider_null
= not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_null
.value
or m
.name
== "==" or m
.name
== "!="
464 if args
.first
.mcasttype
isa MNullableType or args
.first
.mcasttype
isa MNullType and consider_null
then
465 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
466 self.add
("if ({args.first} == NULL) \{ /* Special null case */")
467 if m
.name
== "==" or m
.name
== "is_same_instance" then
469 if args
[1].mcasttype
isa MNullableType then
470 self.add
("{res} = ({args[1]} == NULL);")
471 else if args
[1].mcasttype
isa MNullType then
472 self.add
("{res} = 1; /* is null */")
474 self.add
("{res} = 0; /* {args[1].inspect} cannot be null */")
476 else if m
.name
== "!=" then
478 if args
[1].mcasttype
isa MNullableType then
479 self.add
("{res} = ({args[1]} != NULL);")
480 else if args
[1].mcasttype
isa MNullType then
481 self.add
("{res} = 0; /* is null */")
483 self.add
("{res} = 1; /* {args[1].inspect} cannot be null */")
486 self.add_abort
("Receiver is null")
490 if types
.is_empty
then
492 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
493 self.bugtype
(args
.first
)
498 self.add
("switch({args.first}->classid) \{")
499 var last
= types
.last
500 var defaultpropdef
: nullable MMethodDef = null
502 var propdef
= m
.lookup_first_definition
(self.compiler
.mainmodule
, t
)
503 if propdef
.mclassdef
.mclass
.name
== "Object" and not t
.is_c_primitive
then
504 defaultpropdef
= propdef
507 if not self.compiler
.hardening
and t
== last
and defaultpropdef
== null then
508 self.add
("default: /* test {t} */")
510 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
512 var res2
= self.call
(propdef
, t
, args
)
513 if res
!= null then self.assign
(res
, res2
.as(not null))
516 if defaultpropdef
!= null then
517 self.add
("default: /* default is Object */")
518 var res2
= self.call
(defaultpropdef
, defaultpropdef
.mclassdef
.bound_mtype
, args
)
519 if res
!= null then self.assign
(res
, res2
.as(not null))
520 else if self.compiler
.hardening
then
521 self.add
("default: /* bug */")
522 self.bugtype
(args
.first
)
528 fun check_valid_reciever
(recvtype
: MClassType)
530 if self.compiler
.runtime_type_analysis
.live_types
.has
(recvtype
) or recvtype
.mclass
.name
== "Object" then return
531 print
"{recvtype} is not a live type"
535 # Subpart of old call function
537 # Checks if the type of the receiver is valid and corrects it if necessary
538 private fun get_recvtype
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): MClassType
540 check_valid_reciever
(recvtype
)
544 redef fun call
(m
, recvtype
, args
)
546 var recv_type
= get_recvtype
(m
, recvtype
, args
)
547 var recv
= self.autoadapt
(self.autobox
(args
.first
, recvtype
), recvtype
)
548 if m
.is_extern
then recv
= unbox_extern
(recv
, recv_type
)
553 assert args
.length
== m
.msignature
.arity
+ 1 else debug
("Invalid arity for {m}. {args.length} arguments given.")
555 var rm
= new CustomizedRuntimeFunction(m
, recvtype
)
556 return rm
.call
(self, args
)
559 redef fun supercall
(m
: MMethodDef, recvtype
: MClassType, args
: Array[RuntimeVariable]): nullable RuntimeVariable
561 var types
= self.collect_types
(args
.first
)
563 var res
: nullable RuntimeVariable
564 var ret
= m
.mproperty
.intro
.msignature
.return_mtype
568 ret
= self.resolve_for
(ret
, args
.first
)
569 res
= self.new_var
(ret
)
572 self.add
("/* super {m} on {args.first.inspect} */")
573 if args
.first
.mtype
.is_c_primitive
then
574 var mclasstype
= args
.first
.mtype
.as(MClassType)
575 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mclasstype
) then
576 self.add
("/* skip, no method {m} */")
579 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, mclasstype
)
580 var res2
= self.call
(propdef
, mclasstype
, args
)
581 if res
!= null then self.assign
(res
, res2
.as(not null))
585 if types
.is_empty
then
587 self.add
("/*BUG: no live types for {args.first.inspect} . {m}*/")
588 self.bugtype
(args
.first
)
593 self.add
("switch({args.first}->classid) \{")
594 var last
= types
.last
596 var propdef
= m
.lookup_next_definition
(self.compiler
.mainmodule
, t
)
597 if not self.compiler
.hardening
and t
== last
then
598 self.add
("default: /* test {t} */")
600 self.add
("case {self.compiler.classid(t)}: /* test {t} */")
602 var res2
= self.call
(propdef
, t
, args
)
603 if res
!= null then self.assign
(res
, res2
.as(not null))
606 if self.compiler
.hardening
then
607 self.add
("default: /* bug */")
608 self.bugtype
(args
.first
)
614 redef fun adapt_signature
(m
, args
)
616 var recv
= args
.first
617 for i
in [0..m
.msignature
.arity
[ do
618 var mp
= m
.msignature
.mparameters
[i
]
623 t
= self.resolve_for
(t
, recv
)
624 args
[i
+1] = self.autobox
(args
[i
+1], t
)
628 redef fun unbox_signature_extern
(m
, args
)
630 var recv
= args
.first
631 for i
in [0..m
.msignature
.arity
[ do
632 var mp
= m
.msignature
.mparameters
[i
]
637 t
= self.resolve_for
(t
, recv
)
638 if m
.is_extern
then args
[i
+1] = self.unbox_extern
(args
[i
+1], t
)
642 # FIXME: this is currently buggy since recv is not exact
643 redef fun vararg_instance
(mpropdef
, recv
, varargs
, elttype
)
645 elttype
= self.resolve_for
(elttype
, recv
)
646 return self.array_instance
(varargs
, elttype
)
649 fun bugtype
(recv
: RuntimeVariable)
651 if recv
.mtype
.is_c_primitive
then return
652 self.add
("PRINT_ERROR(\"BTD BUG: Dynamic type is %s
, static
type is %s\\n\
", class_names[{recv}->classid], \"{recv.mcasttype}\
");")
653 self.add
("fatal_exit(1);")
656 redef fun isset_attribute
(a
, recv
)
658 check_recv_notnull
(recv
)
660 var types
= self.collect_types
(recv
)
661 var res
= self.new_var
(bool_type
)
663 if types
.is_empty
then
664 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
668 self.add
("/* isset {a} on {recv.inspect} */")
669 self.add
("switch({recv}->classid) \{")
670 var last
= types
.last
672 if not self.compiler
.hardening
and t
== last
then
673 self.add
("default: /*{self.compiler.classid(t)}*/")
675 self.add
("case {self.compiler.classid(t)}:")
677 var recv2
= self.autoadapt
(recv
, t
)
678 var ta
= a
.intro
.static_mtype
.as(not null)
679 ta
= self.resolve_for
(ta
, recv2
)
680 var attr
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
681 if not ta
isa MNullableType then
682 if not ta
.is_c_primitive
then
683 self.add
("{res} = ({attr} != NULL);")
685 self.add
("{res} = 1; /*NOTYET isset on primitive attributes*/")
690 if self.compiler
.hardening
then
691 self.add
("default: /* Bug */")
699 redef fun read_attribute
(a
, recv
)
701 check_recv_notnull
(recv
)
703 var types
= self.collect_types
(recv
)
705 var ret
= a
.intro
.static_mtype
.as(not null)
706 ret
= self.resolve_for
(ret
, recv
)
707 var res
= self.new_var
(ret
)
709 if types
.is_empty
then
710 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
714 self.add
("/* read {a} on {recv.inspect} */")
715 self.add
("switch({recv}->classid) \{")
716 var last
= types
.last
718 if not self.compiler
.hardening
and t
== last
then
719 self.add
("default: /*{self.compiler.classid(t)}*/")
721 self.add
("case {self.compiler.classid(t)}:")
723 var recv2
= self.autoadapt
(recv
, t
)
724 var ta
= a
.intro
.static_mtype
.as(not null)
725 ta
= self.resolve_for
(ta
, recv2
)
726 var res2
= self.new_expr
("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta
)
727 if not ta
isa MNullableType and not self.compiler
.modelbuilder
.toolcontext
.opt_no_check_attr_isset
.value
then
728 if not ta
.is_c_primitive
then
729 self.add
("if ({res2} == NULL) \{")
730 self.add_abort
("Uninitialized attribute {a.name}")
733 self.add
("/*NOTYET isset on primitive attributes*/")
736 self.assign
(res
, res2
)
739 if self.compiler
.hardening
then
740 self.add
("default: /* Bug */")
748 redef fun write_attribute
(a
, recv
, value
)
750 check_recv_notnull
(recv
)
752 var types
= self.collect_types
(recv
)
754 if types
.is_empty
then
755 self.add
("/*BUG: no live types for {recv.inspect} . {a}*/")
759 self.add
("/* write {a} on {recv.inspect} */")
760 self.add
("switch({recv}->classid) \{")
761 var last
= types
.last
763 if not self.compiler
.hardening
and t
== last
then
764 self.add
("default: /*{self.compiler.classid(t)}*/")
766 self.add
("case {self.compiler.classid(t)}:")
768 var recv2
= self.autoadapt
(recv
, t
)
769 var ta
= a
.intro
.static_mtype
.as(not null)
770 ta
= self.resolve_for
(ta
, recv2
)
771 self.add
("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
774 if self.compiler
.hardening
then
775 self.add
("default: /* Bug*/")
781 redef fun init_instance
(mtype
)
783 mtype
= self.anchor
(mtype
).as(MClassType)
784 if not self.compiler
.runtime_type_analysis
.live_types
.has
(mtype
) then
785 debug
"problem: {mtype} was detected dead"
787 var res
= self.new_expr
("NEW_{mtype.c_name}()", mtype
)
792 redef fun type_test
(value
, mtype
, tag
)
794 mtype
= self.anchor
(mtype
)
795 if not self.compiler
.runtime_type_analysis
.live_cast_types
.has
(mtype
) then
796 debug
"problem: {mtype} was detected cast-dead"
800 var types
= self.collect_types
(value
)
801 var res
= self.new_var
(bool_type
)
803 self.add
("/* isa {mtype} on {value.inspect} */")
804 if value
.mtype
.is_c_primitive
then
805 if value
.mtype
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
806 self.add
("{res} = 1;")
808 self.add
("{res} = 0;")
812 if value
.mcasttype
isa MNullableType or value
.mcasttype
isa MNullType then
813 self.add
("if ({value} == NULL) \{")
814 if mtype
isa MNullableType then
815 self.add
("{res} = 1; /* isa {mtype} */")
817 self.add
("{res} = 0; /* not isa {mtype} */")
821 self.add
("switch({value}->classid) \{")
823 if t
.is_subtype
(self.compiler
.mainmodule
, null, mtype
) then
824 self.add
("case {self.compiler.classid(t)}: /* {t} */")
827 self.add
("{res} = 1;")
830 self.add
("{res} = 0;")
836 redef fun is_same_type_test
(value1
, value2
)
838 var res
= self.new_var
(bool_type
)
839 if not value2
.mtype
.is_c_primitive
then
840 if not value1
.mtype
.is_c_primitive
then
841 self.add
"{res} = {value1}->classid == {value2}->classid;"
843 self.add
"{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
846 if not value1
.mtype
.is_c_primitive
then
847 self.add
"{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
848 else if value1
.mcasttype
== value2
.mcasttype
then
849 self.add
"{res} = 1;"
851 self.add
"{res} = 0;"
857 redef fun class_name_string
(value
)
859 var res
= self.get_name
("var_class_name")
860 self.add_decl
("const char* {res};")
861 if not value
.mtype
.is_c_primitive
then
862 self.add
"{res} = class_names[{value}->classid];"
864 self.add
"{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
869 redef fun equal_test
(value1
, value2
)
871 var res
= self.new_var
(bool_type
)
872 if value2
.mtype
.is_c_primitive
and not value1
.mtype
.is_c_primitive
then
877 if value1
.mtype
.is_c_primitive
then
878 if value2
.mtype
== value1
.mtype
then
879 self.add
("{res} = {value1} == {value2};")
880 else if value2
.mtype
.is_c_primitive
then
881 self.add
("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
883 var mtype1
= value1
.mtype
.as(MClassType)
884 self.add
("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
885 self.add
("if ({res}) \{")
886 self.add
("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
890 var s
= new Array[String]
891 for t
in self.compiler
.live_primitive_types
do
892 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value1
.mcasttype
) then continue
893 if not t
.is_subtype
(self.compiler
.mainmodule
, null, value2
.mcasttype
) then continue
894 s
.add
"({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
897 if self.compiler
.mainmodule
.model
.get_mclasses_by_name
("Pointer") != null then
898 var pointer_type
= self.compiler
.mainmodule
.pointer_type
899 if value1
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) or
900 value2
.mcasttype
.is_subtype
(self.compiler
.mainmodule
, null, pointer_type
) then
901 s
.add
"(((struct {pointer_type.c_name}*){value1})->value == ((struct {pointer_type.c_name}*){value2})->value)"
906 self.add
("{res} = {value1} == {value2};")
908 self.add
("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
914 redef fun array_instance
(array
, elttype
)
916 elttype
= self.anchor
(elttype
)
917 var arraytype
= mmodule
.array_type
(elttype
)
918 var res
= self.init_instance
(arraytype
)
919 self.add
("\{ /* {res} = array_instance Array[{elttype}] */")
920 var nat
= self.new_var
(mmodule
.native_array_type
(elttype
))
922 self.add
("{nat} = NEW_{nat.mtype.c_name}({array.length});")
923 for i
in [0..array
.length
[ do
924 var r
= self.autobox
(array
[i
], elttype
)
925 self.add
("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
927 var length
= self.int_instance
(array
.length
)
928 self.send
(self.get_property
("with_native", arraytype
), [res
, nat
, length
])
934 # A runtime function customized on a specific monomrph receiver type
935 private class CustomizedRuntimeFunction
936 super AbstractRuntimeFunction
938 redef type COMPILER: GlobalCompiler
939 redef type VISITOR: GlobalCompilerVisitor
941 # The considered reciever
942 # (usually is a live type but no strong guarantee)
945 redef fun build_c_name
947 var res
= self.c_name_cache
948 if res
!= null then return res
949 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
950 res
= self.mmethoddef
.c_name
952 res
= "{mmethoddef.c_name}__{recv.c_name}"
954 self.c_name_cache
= res
958 # used in the compiler worklist
961 if not o
isa CustomizedRuntimeFunction then return false
962 if self.mmethoddef
!= o
.mmethoddef
then return false
963 if self.recv
!= o
.recv
then return false
967 # used in the compiler work-list
968 redef fun hash
do return self.mmethoddef
.hash
+ self.recv
.hash
972 if self.mmethoddef
.mclassdef
.bound_mtype
== self.recv
then
973 return self.mmethoddef
.to_s
975 return "{self.mmethoddef}@{self.recv}"
979 # compile the code customized for the reciever
980 redef fun compile_to_c
(compiler
)
983 var mmethoddef
= self.mmethoddef
984 if not recv
.is_subtype
(compiler
.mainmodule
, null, mmethoddef
.mclassdef
.bound_mtype
) then
985 print
("problem: why do we compile {self} for {recv}?")
989 var v
= compiler
.new_visitor
990 var selfvar
= new RuntimeVariable("self", recv
, recv
)
991 if compiler
.runtime_type_analysis
.live_types
.has
(recv
) then
992 selfvar
.is_exact
= true
994 var arguments
= new Array[RuntimeVariable]
995 var frame
= new StaticFrame(v
, mmethoddef
, recv
, arguments
)
998 var sig
= new FlatBuffer
999 var comment
= new FlatBuffer
1000 var ret
= mmethoddef
.msignature
.return_mtype
1002 ret
= v
.resolve_for
(ret
, selfvar
)
1003 sig
.append
("{ret.ctype} ")
1007 sig
.append
(self.c_name
)
1008 sig
.append
("({recv.ctype} {selfvar}")
1009 comment
.append
("(self: {recv}")
1010 arguments
.add
(selfvar
)
1011 for i
in [0..mmethoddef
.msignature
.arity
[ do
1012 var mp
= mmethoddef
.msignature
.mparameters
[i
]
1013 var mtype
= mp
.mtype
1014 if mp
.is_vararg
then
1015 mtype
= v
.mmodule
.array_type
(mtype
)
1017 mtype
= v
.resolve_for
(mtype
, selfvar
)
1018 comment
.append
(", {mtype}")
1019 sig
.append
(", {mtype.ctype} p{i}")
1020 var argvar
= new RuntimeVariable("p{i}", mtype
, mtype
)
1021 arguments
.add
(argvar
)
1026 comment
.append
(": {ret}")
1028 compiler
.header
.add_decl
("{sig};")
1030 v
.add_decl
("/* method {self} for {comment} */")
1031 v
.add_decl
("{sig} \{")
1032 #v.add("printf(\"method {self} for {comment}\\n\");")
1034 frame
.returnvar
= v
.new_var
(ret
)
1036 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1038 mmethoddef
.compile_inside_to_c
(v
, arguments
)
1040 v
.add
("{frame.returnlabel.as(not null)}:;")
1042 v
.add
("return {frame.returnvar.as(not null)};")
1045 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})"
1048 redef fun call
(v
: VISITOR, arguments
: Array[RuntimeVariable]): nullable RuntimeVariable
1050 var ret
= self.mmethoddef
.msignature
.return_mtype
1052 ret
= v
.resolve_for
(ret
, arguments
.first
)
1054 if self.mmethoddef
.can_inline
(v
) then
1055 var frame
= new StaticFrame(v
, self.mmethoddef
, self.recv
, arguments
)
1056 frame
.returnlabel
= v
.get_name
("RET_LABEL")
1058 frame
.returnvar
= v
.new_var
(ret
)
1060 var old_frame
= v
.frame
1062 v
.add
("\{ /* Inline {self} ({arguments.join(",")}) */")
1063 self.mmethoddef
.compile_inside_to_c
(v
, arguments
)
1064 v
.add
("{frame.returnlabel.as(not null)}:(void)0;")
1067 return frame
.returnvar
1069 v
.adapt_signature
(self.mmethoddef
, arguments
)
1070 v
.compiler
.todo
(self)
1072 v
.add
("{self.c_name}({arguments.join(",")});")
1075 var res
= v
.new_var
(ret
)
1076 v
.add
("{res} = {self.c_name}({arguments.join(",")});")