nitg-sep: inline primitive call on intern methods
[nit.git] / src / separate_compiler.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Separate compilation of a Nit program
16 module separate_compiler
17
18
19 import global_compiler # TODO better separation of concerns
20 intrude import coloring
21 redef class ToolContext
22 # --separate
23 var opt_separate: OptionBool = new OptionBool("Use separate compilation", "--separate")
24
25 redef init
26 do
27 super
28 self.option_context.add_option(self.opt_separate)
29 end
30 end
31
32 redef class ModelBuilder
33 fun run_separate_compiler(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis)
34 do
35 var time0 = get_time
36 self.toolcontext.info("*** COMPILING TO C ***", 1)
37
38 var compiler = new SeparateCompiler(mainmodule, runtime_type_analysis, self)
39 var v = compiler.new_visitor
40 compiler.header = v
41 v.add_decl("#include <stdlib.h>")
42 v.add_decl("#include <stdio.h>")
43 v.add_decl("#include <string.h>")
44 v.add_decl("#include <gc/gc.h>")
45 v.add_decl("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
46 v.add_decl("typedef void* nitattribute_t; /* general C type representing a Nit attribute. */")
47
48 # Class abstract representation
49 v.add_decl("struct class \{ nitmethod_t vft[1]; \}; /* general C type representing a Nit class. */")
50 # Type abstract representation
51 v.add_decl("struct type \{ int id; int color; int livecolor; short int is_nullable; struct vts_table *vts_table; struct fts_table *fts_table; int table_size; int type_table[1]; \}; /* general C type representing a Nit type. */")
52 v.add_decl("struct fts_table \{ struct type *fts[1]; \}; /* fts list of a C type representation. */")
53 v.add_decl("struct vts_table \{ struct type *vts[1]; \}; /* vts list of a C type representation. */")
54 # Instance abstract representation
55 v.add_decl("typedef struct \{ struct type *type; struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
56
57 # Declare global instances
58 v.add_decl("extern int glob_argc;")
59 v.add_decl("extern char **glob_argv;")
60 v.add_decl("extern val *glob_sys;")
61
62 # The main function of the C
63 compiler.compile_main_function
64
65 # compile class structures
66 for m in mainmodule.in_importation.greaters do
67 for mclass in m.intro_mclasses do
68 compiler.compile_class_to_c(mclass)
69 end
70 end
71
72 # compile methods
73 for m in mainmodule.in_importation.greaters do
74 compiler.compile_module_to_c(m)
75 end
76
77 # compile live & cast type structures
78 var mtypes = compiler.do_global_type_coloring
79 for t in mtypes do
80 compiler.compile_type_to_c(t)
81 end
82
83 # compile live generic types selection structures
84 for mclass in model.mclasses do
85 compiler.compile_live_gentype_to_c(mclass)
86 end
87
88 # for the class_name and output_class_name methods
89 compiler.compile_class_names
90
91 write_and_make(compiler)
92 end
93 end
94
95 # Singleton that store the knowledge about the separate compilation process
96 class SeparateCompiler
97 super GlobalCompiler # TODO better separation of concerns
98
99 private var undead_types: Set[MType] = new HashSet[MType]
100 protected var typeids: HashMap[MType, Int] protected writable = new HashMap[MType, Int]
101
102 private var type_colors: Map[MType, Int] = typeids
103 private var type_tables: nullable Map[MType, Array[nullable MType]] = null
104
105 private var livetypes_colors: nullable Map[MType, Int]
106 private var livetypes_tables: nullable Map[MClass, Array[nullable Object]]
107 private var livetypes_tables_sizes: nullable Map[MClass, Array[Int]]
108
109 protected var class_colors: Map[MClass, Int] protected writable
110
111 protected var method_colors: Map[MMethod, Int] protected writable
112 protected var method_tables: Map[MClass, Array[nullable MMethodDef]] protected writable
113
114 protected var attr_colors: Map[MAttribute, Int] protected writable
115 protected var attr_tables: Map[MClass, Array[nullable MAttributeDef]] protected writable
116
117 private var vt_colors: Map[MVirtualTypeProp, Int]
118 private var vt_tables: Map[MClass, Array[nullable MVirtualTypeDef]]
119
120 private var ft_colors: Map[MParameterType, Int]
121 private var ft_tables: Map[MClass, Array[nullable MParameterType]]
122
123 init(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis, mmbuilder: ModelBuilder) do
124 # classes coloration
125 var class_coloring = new ClassColoring(mainmodule)
126 self.class_colors = class_coloring.colorize(mmbuilder.model.mclasses)
127
128 # methods coloration
129 var method_coloring = new MethodColoring(class_coloring)
130 self.method_colors = method_coloring.colorize
131 self.method_tables = method_coloring.build_property_tables
132
133 # attributes coloration
134 var attribute_coloring = new AttributeColoring(class_coloring)
135 self.attr_colors = attribute_coloring.colorize
136 self.attr_tables = attribute_coloring.build_property_tables
137
138 # vt coloration
139 var vt_coloring = new VTColoring(class_coloring)
140 self.vt_colors = vt_coloring.colorize
141 self.vt_tables = vt_coloring.build_property_tables
142
143 # fts coloration
144 var ft_coloring = new FTColoring(class_coloring)
145 self.ft_colors = ft_coloring.colorize
146 self.ft_tables = ft_coloring.build_ft_tables
147 end
148
149 protected fun compile_class_names do
150
151 # Build type names table
152 var type_array = new Array[nullable MType]
153 for t, i in typeids do
154 if i >= type_array.length then
155 type_array[i] = null
156 end
157 type_array[i] = t
158 end
159
160 var v = self.new_visitor
161 self.header.add_decl("extern const char const * class_names[];")
162 v.add("const char const * class_names[] = \{")
163 for t in type_array do
164 if t == null then
165 v.add("NULL,")
166 else
167 v.add("\"{t}\",")
168 end
169 end
170 v.add("\};")
171 end
172
173 # colorize live types of the program
174 private fun do_global_type_coloring: Set[MType] do
175 var mtypes = new HashSet[MType]
176 mtypes.add_all(self.runtime_type_analysis.live_types)
177 mtypes.add_all(self.runtime_type_analysis.live_cast_types)
178 mtypes.add_all(self.undead_types)
179
180 self.undead_types.clear
181 for mtype in mtypes do
182 # add formal types arguments to mtypes
183 if mtype isa MGenericType then
184 for ft in mtype.arguments do
185 if ft.need_anchor then
186 print("Why do we need anchor here ?")
187 abort
188 end
189 self.undead_types.add(ft)
190 end
191 end
192 var mclass_type: MClassType
193 if mtype isa MNullableType then
194 mclass_type = mtype.mtype.as(MClassType)
195 else
196 mclass_type = mtype.as(MClassType)
197 end
198 # add virtual types to mtypes
199 for vt in self.vt_tables[mclass_type.mclass] do
200 if vt != null then
201 var anchored = vt.bound.anchor_to(self.mainmodule, mclass_type)
202 self.undead_types.add(anchored)
203 end
204 end
205 end
206 mtypes.add_all(self.undead_types)
207
208 # set type unique id
209 for mtype in mtypes do
210 self.typeids[mtype] = self.typeids.length
211 end
212
213 # colorize live entries
214 var entries_coloring = new LiveEntryColoring
215 self.livetypes_colors = entries_coloring.colorize(mtypes)
216 self.livetypes_tables = entries_coloring.build_livetype_tables(mtypes)
217 self.livetypes_tables_sizes = entries_coloring.livetypes_tables_sizes
218
219 # colorize types
220 var type_coloring = new TypeColoring(self.mainmodule, mtypes)
221 self.type_colors = type_coloring.colorize(mtypes)
222 self.type_tables = type_coloring.build_type_tables(mtypes, type_colors)
223
224 return mtypes
225 end
226
227 # declare live generic types tables selection
228 private fun compile_live_gentype_to_c(mclass: MClass) do
229 if mclass.arity > 0 then
230 if self.livetypes_tables.has_key(mclass) then
231 var table = self.livetypes_tables[mclass]
232 var sign = self.livetypes_tables_sizes[mclass]
233 var table_buffer = new Buffer.from("const struct type *livetypes_{mclass.c_name}[{sign.join("][")}] = \{\n")
234 compile_livetype_table(table, table_buffer, 1, mclass.arity)
235 table_buffer.append("\};")
236
237 var v = new SeparateCompilerVisitor(self)
238 self.header.add_decl("extern const struct type *livetypes_{mclass.c_name}[{sign.join("][")}];")
239 v.add_decl(table_buffer.to_s)
240 else
241 var sign = new Array[Int].filled_with(0, mclass.arity)
242 var v = new SeparateCompilerVisitor(self)
243 self.header.add_decl("extern const struct type *livetypes_{mclass.c_name}[{sign.join("][")}];")
244 v.add_decl("const struct type *livetypes_{mclass.c_name}[{sign.join("][")}];")
245 end
246 end
247 end
248
249 private fun compile_livetype_table(table: Array[nullable Object], buffer: Buffer, depth: Int, max: Int) do
250 for obj in table do
251 if obj == null then
252 if depth == max then
253 buffer.append("NULL,\n")
254 else
255 buffer.append("\{\},\n")
256 end
257 else if obj isa MClassType then
258 buffer.append("(struct type*) &type_{obj.c_name}, /* {obj} */\n")
259 else if obj isa Array[nullable Object] then
260 buffer.append("\{\n")
261 compile_livetype_table(obj, buffer, depth + 1, max)
262 buffer.append("\},\n")
263 end
264 end
265 end
266
267 # Separately compile all the method definitions of the module
268 fun compile_module_to_c(mmodule: MModule)
269 do
270 for cd in mmodule.mclassdefs do
271 for pd in cd.mpropdefs do
272 if not pd isa MMethodDef then continue
273 #print "compile {pd} @ {cd} @ {mmodule}"
274 var r = new SeparateRuntimeFunction(pd)
275 r.compile_to_c(self)
276 if true or cd.bound_mtype.ctype != "val*" then
277 var r2 = new VirtualRuntimeFunction(pd)
278 r2.compile_to_c(self)
279 end
280 end
281 end
282 end
283
284 # Globaly compile the type structure of a live type
285 fun compile_type_to_c(mtype: MType)
286 do
287 var c_name = mtype.c_name
288 var v = new SeparateCompilerVisitor(self)
289 v.add_decl("/* runtime type {mtype} */")
290
291 var mclass_type: MClassType
292 if mtype isa MNullableType then
293 mclass_type = mtype.mtype.as(MClassType)
294 else
295 mclass_type = mtype.as(MClassType)
296 end
297
298 # extern const struct type_X
299 self.header.add_decl("extern const struct type_{c_name} type_{c_name};")
300 self.header.add_decl("struct type_{c_name} \{")
301 self.header.add_decl("int id;")
302 self.header.add_decl("int color;")
303 self.header.add_decl("int livecolor;")
304 self.header.add_decl("short int is_nullable;")
305 self.header.add_decl("const struct vts_table_{c_name} *vts_table;")
306 self.header.add_decl("const struct fts_table_{c_name} *fts_table;")
307 self.header.add_decl("int table_size;")
308 self.header.add_decl("int type_table[{self.type_tables[mtype].length}];")
309 self.header.add_decl("\};")
310
311 # extern const struct vts_table_X vts_table_X
312 self.header.add_decl("extern const struct vts_table_{c_name} vts_table_{c_name};")
313 self.header.add_decl("struct vts_table_{c_name} \{")
314 self.header.add_decl("struct type *vts[{self.vt_tables[mclass_type.mclass].length}];")
315 self.header.add_decl("\};")
316
317 # extern const struct fst_table_X fst_table_X
318 self.header.add_decl("extern const struct fts_table_{c_name} fts_table_{c_name};")
319 self.header.add_decl("struct fts_table_{c_name} \{")
320 self.header.add_decl("struct type *fts[{self.ft_tables[mclass_type.mclass].length}];")
321 self.header.add_decl("\};")
322
323 # const struct type_X
324 v.add_decl("const struct type_{c_name} type_{c_name} = \{")
325 v.add_decl("{self.typeids[mtype]},")
326 v.add_decl("{self.type_colors[mtype]},")
327 v.add_decl("{self.livetypes_colors[mtype]},")
328 if mtype isa MNullableType then
329 v.add_decl("1,")
330 else
331 v.add_decl("0,")
332 end
333 v.add_decl("&vts_table_{c_name},")
334 v.add_decl("&fts_table_{c_name},")
335 v.add_decl("{self.type_tables[mtype].length},")
336 v.add_decl("\{")
337 for stype in self.type_tables[mtype] do
338 if stype == null then
339 v.add_decl("-1, /* empty */")
340 else
341 v.add_decl("{self.typeids[stype]}, /* {stype} */")
342 end
343 end
344 v.add_decl("\},")
345 v.add_decl("\};")
346
347 build_fts_table(mtype, v)
348 build_vts_table(mtype, v)
349 end
350
351 # const struct fst_table_X fst_table_X
352 private fun build_fts_table(mtype: MType, v: SeparateCompilerVisitor) do
353 v.add_decl("const struct fts_table_{mtype.c_name} fts_table_{mtype.c_name} = \{")
354 v.add_decl("\{")
355
356 var mclass_type: MClassType
357 if mtype isa MNullableType then
358 mclass_type = mtype.mtype.as(MClassType)
359 else
360 mclass_type = mtype.as(MClassType)
361 end
362
363 for ft in self.ft_tables[mclass_type.mclass] do
364 if ft == null then
365 v.add_decl("NULL, /* empty */")
366 else
367 var ntype: MType
368 if ft.mclass == mclass_type.mclass then
369 ntype = mclass_type.arguments[ft.rank]
370 else
371 ntype = ft.anchor_to(self.mainmodule, mclass_type)
372 end
373 if self.typeids.has_key(ntype) then
374 v.add_decl("(struct type*)&type_{ntype.c_name}, /* {ft} ({ntype}) */")
375 else
376 v.add_decl("NULL, /* empty ({ft} not a live type) */")
377 end
378 end
379 end
380 v.add_decl("\},")
381 v.add_decl("\};")
382 end
383
384 # const struct vts_table_X vts_table_X
385 private fun build_vts_table(mtype: MType, v: SeparateCompilerVisitor) do
386 v.add_decl("const struct vts_table_{mtype.c_name} vts_table_{mtype.c_name} = \{")
387 v.add_decl("\{")
388
389 var mclass_type: MClassType
390 if mtype isa MNullableType then
391 mclass_type = mtype.mtype.as(MClassType)
392 else
393 mclass_type = mtype.as(MClassType)
394 end
395
396 for vt in self.vt_tables[mclass_type.mclass] do
397 if vt == null then
398 v.add_decl("NULL, /* empty */")
399 else
400 var bound = vt.bound
401 if bound == null then
402 #FIXME how can a bound be null here ?
403 print "No bound found for virtual type {vt} ?"
404 abort
405 else
406 var ntype = bound
407 if ntype isa MNullableType then ntype = ntype.mtype
408 if ntype isa MVirtualType then
409 bound = ntype.anchor_to(self.mainmodule, mclass_type)
410 else if ntype isa MParameterType then
411 bound = ntype.anchor_to(self.mainmodule, mclass_type)
412 else if ntype isa MGenericType and bound.need_anchor then
413 bound = ntype.anchor_to(self.mainmodule, mclass_type)
414 else if ntype isa MClassType then
415 else
416 print "NOT YET IMPLEMENTED: mtype_to_livetype with type: {ntype}"
417 abort
418 end
419
420 if self.typeids.has_key(bound) then
421 v.add_decl("(struct type*)&type_{bound.c_name}, /* {ntype} */")
422 else
423 v.add_decl("NULL, /* dead type {ntype} */")
424 end
425 end
426 end
427 end
428 v.add_decl("\},")
429 v.add_decl("\};")
430 end
431
432 # Globally compile the table of the class mclass
433 # In a link-time optimisation compiler, tables are globally computed
434 # In a true separate compiler (a with dynamic loading) you cannot do this unfortnally
435 fun compile_class_to_c(mclass: MClass)
436 do
437 var mtype = mclass.intro.bound_mtype
438 var c_name = mclass.c_name
439
440 var vft = self.method_tables[mclass]
441 var attrs = self.attr_tables[mclass]
442 var v = new SeparateCompilerVisitor(self)
443
444 v.add_decl("/* runtime class {c_name} */")
445 var idnum = classids.length
446 var idname = "ID_" + c_name
447 self.classids[mtype] = idname
448 #self.header.add_decl("#define {idname} {idnum} /* {c_name} */")
449
450 self.header.add_decl("struct class_{c_name} \{")
451 self.header.add_decl("nitmethod_t vft[{vft.length}];")
452 self.header.add_decl("\};")
453
454 # Build class vft
455 self.header.add_decl("extern const struct class_{c_name} class_{c_name};")
456 v.add_decl("const struct class_{c_name} class_{c_name} = \{")
457 v.add_decl("\{")
458 for i in [0 .. vft.length[ do
459 var mpropdef = vft[i]
460 if mpropdef == null then
461 v.add_decl("NULL, /* empty */")
462 else
463 if true or mpropdef.mclassdef.bound_mtype.ctype != "val*" then
464 v.add_decl("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
465 else
466 v.add_decl("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
467 end
468 end
469 end
470 v.add_decl("\}")
471 v.add_decl("\};")
472
473 if mtype.ctype != "val*" then
474 #Build instance struct
475 self.header.add_decl("struct instance_{c_name} \{")
476 self.header.add_decl("const struct type *type;")
477 self.header.add_decl("const struct class *class;")
478 self.header.add_decl("{mtype.ctype} value;")
479 self.header.add_decl("\};")
480
481 if not self.runtime_type_analysis.live_types.has(mtype) then return
482
483 self.header.add_decl("val* BOX_{c_name}({mtype.ctype});")
484 v.add_decl("/* allocate {mtype} */")
485 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
486 v.add("struct instance_{c_name}*res = GC_MALLOC(sizeof(struct instance_{c_name}));")
487 v.add("res->type = (struct type*) &type_{c_name};")
488 v.add("res->class = (struct class*) &class_{c_name};")
489 v.add("res->value = value;")
490 v.add("return (val*)res;")
491 v.add("\}")
492 return
493 end
494
495 var is_native_array = mclass.name == "NativeArray"
496
497 var sig
498 if is_native_array then
499 sig = "int length, struct type* type"
500 else
501 sig = "struct type* type"
502 end
503
504 #Build instance struct
505 #extern const struct instance_array__NativeArray instance_array__NativeArray;
506 self.header.add_decl("struct instance_{c_name} \{")
507 self.header.add_decl("const struct type *type;")
508 self.header.add_decl("const struct class *class;")
509 self.header.add_decl("nitattribute_t attrs[{attrs.length}];")
510 if is_native_array then
511 # NativeArrays are just a instance header followed by an array of values
512 self.header.add_decl("val* values[0];")
513 end
514 self.header.add_decl("\};")
515
516
517 self.header.add_decl("{mtype.ctype} NEW_{c_name}({sig});")
518 v.add_decl("/* allocate {mtype} */")
519 v.add_decl("{mtype.ctype} NEW_{c_name}({sig}) \{")
520 var res = v.new_named_var(mtype, "self")
521 res.is_exact = true
522 if is_native_array then
523 var mtype_elt = mtype.arguments.first
524 v.add("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
525 else
526 v.add("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
527 end
528 #v.add("{res} = calloc(sizeof(struct instance_{c_name}), 1);")
529 v.add("{res}->type = type;")
530 v.add("{res}->class = (struct class*) &class_{c_name};")
531
532 for cd in mtype.collect_mclassdefs(self.mainmodule)
533 do
534 var n = self.modelbuilder.mclassdef2nclassdef[cd]
535 for npropdef in n.n_propdefs do
536 if npropdef isa AAttrPropdef then
537 npropdef.init_expr(v, res)
538 end
539 end
540 end
541 v.add("return {res};")
542 v.add("\}")
543 end
544
545 redef fun new_visitor do return new SeparateCompilerVisitor(self)
546 end
547
548 # The C function associated to a methoddef separately compiled
549 class SeparateRuntimeFunction
550 super AbstractRuntimeFunction
551
552 redef fun build_c_name: String
553 do
554 return "{mmethoddef.c_name}"
555 end
556
557 redef fun to_s do return self.mmethoddef.to_s
558
559 redef fun compile_to_c(compiler)
560 do
561 var mmethoddef = self.mmethoddef
562
563 var recv = self.mmethoddef.mclassdef.bound_mtype
564 var v = compiler.new_visitor
565 var selfvar = new RuntimeVariable("self", recv, recv)
566 var arguments = new Array[RuntimeVariable]
567 var frame = new Frame(v, mmethoddef, recv, arguments)
568 v.frame = frame
569
570 var msignature = mmethoddef.msignature.resolve_for(mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.mmodule, true)
571
572 var sig = new Buffer
573 var comment = new Buffer
574 var ret = msignature.return_mtype
575 if ret != null then
576 sig.append("{ret.ctype} ")
577 else if mmethoddef.mproperty.is_new then
578 ret = recv
579 sig.append("{ret.ctype} ")
580 else
581 sig.append("void ")
582 end
583 sig.append(self.c_name)
584 sig.append("({selfvar.mtype.ctype} {selfvar}")
585 comment.append("(self: {selfvar}")
586 arguments.add(selfvar)
587 for i in [0..msignature.arity[ do
588 var mtype = msignature.mparameters[i].mtype
589 if i == msignature.vararg_rank then
590 mtype = v.get_class("Array").get_mtype([mtype])
591 end
592 comment.append(", {mtype}")
593 sig.append(", {mtype.ctype} p{i}")
594 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
595 arguments.add(argvar)
596 end
597 sig.append(")")
598 comment.append(")")
599 if ret != null then
600 comment.append(": {ret}")
601 end
602 compiler.header.add_decl("{sig};")
603
604 v.add_decl("/* method {self} for {comment} */")
605 v.add_decl("{sig} \{")
606 if ret != null then
607 frame.returnvar = v.new_var(ret)
608 end
609 frame.returnlabel = v.get_name("RET_LABEL")
610
611 if recv != arguments.first.mtype then
612 #print "{self} {recv} {arguments.first}"
613 end
614 mmethoddef.compile_inside_to_c(v, arguments)
615
616 v.add("{frame.returnlabel.as(not null)}:;")
617 if ret != null then
618 v.add("return {frame.returnvar.as(not null)};")
619 end
620 v.add("\}")
621 end
622 end
623
624 # The C function associated to a methoddef on a primitive type, stored into a VFT of a class
625 # The first parameter (the reciever) is always typed by val* in order to accept an object value
626 class VirtualRuntimeFunction
627 super AbstractRuntimeFunction
628
629 redef fun build_c_name: String
630 do
631 return "VIRTUAL_{mmethoddef.c_name}"
632 end
633
634 redef fun to_s do return self.mmethoddef.to_s
635
636 redef fun compile_to_c(compiler)
637 do
638 var mmethoddef = self.mmethoddef
639
640 var recv = self.mmethoddef.mclassdef.bound_mtype
641 var v = compiler.new_visitor
642 var selfvar = new RuntimeVariable("self", v.object_type, recv)
643 var arguments = new Array[RuntimeVariable]
644 var frame = new Frame(v, mmethoddef, recv, arguments)
645 v.frame = frame
646
647 var sig = new Buffer
648 var comment = new Buffer
649
650 # Because the function is virtual, the signature must match the one of the original class
651 var intromclassdef = self.mmethoddef.mproperty.intro.mclassdef
652 var msignature = mmethoddef.mproperty.intro.msignature.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
653 var ret = msignature.return_mtype
654 if ret != null then
655 sig.append("{ret.ctype} ")
656 else if mmethoddef.mproperty.is_new then
657 ret = recv
658 sig.append("{ret.ctype} ")
659 else
660 sig.append("void ")
661 end
662 sig.append(self.c_name)
663 sig.append("({selfvar.mtype.ctype} {selfvar}")
664 comment.append("(self: {selfvar}")
665 arguments.add(selfvar)
666 for i in [0..msignature.arity[ do
667 var mtype = msignature.mparameters[i].mtype
668 if i == msignature.vararg_rank then
669 mtype = v.get_class("Array").get_mtype([mtype])
670 end
671 comment.append(", {mtype}")
672 sig.append(", {mtype.ctype} p{i}")
673 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
674 arguments.add(argvar)
675 end
676 sig.append(")")
677 comment.append(")")
678 if ret != null then
679 comment.append(": {ret}")
680 end
681 compiler.header.add_decl("{sig};")
682
683 v.add_decl("/* method {self} for {comment} */")
684 v.add_decl("{sig} \{")
685 if ret != null then
686 frame.returnvar = v.new_var(ret)
687 end
688 frame.returnlabel = v.get_name("RET_LABEL")
689
690 if recv != arguments.first.mtype then
691 #print "{self} {recv} {arguments.first}"
692 end
693 mmethoddef.compile_inside_to_c(v, arguments)
694
695 v.add("{frame.returnlabel.as(not null)}:;")
696 if ret != null then
697 v.add("return {frame.returnvar.as(not null)};")
698 end
699 v.add("\}")
700 end
701
702 redef fun call(v, arguments)
703 do
704 abort
705 # TODO ?
706 end
707 end
708
709 # A visitor on the AST of property definition that generate the C code of a separate compilation process.
710 class SeparateCompilerVisitor
711 super GlobalCompilerVisitor # TODO better separation of concerns
712
713 redef fun adapt_signature(m: MMethodDef, args: Array[RuntimeVariable])
714 do
715 var msignature = m.msignature.resolve_for(m.mclassdef.bound_mtype, m.mclassdef.bound_mtype, m.mclassdef.mmodule, true)
716 var recv = args.first
717 if recv.mtype.ctype != m.mclassdef.mclass.mclass_type.ctype then
718 args.first = self.autobox(args.first, m.mclassdef.mclass.mclass_type)
719 end
720 for i in [0..msignature.arity[ do
721 var t = msignature.mparameters[i].mtype
722 if i == msignature.vararg_rank then
723 t = args[i+1].mtype
724 end
725 args[i+1] = self.autobox(args[i+1], t)
726 end
727 end
728
729 # Box or unbox a value to another type iff a C type conversion is needed
730 # ENSURE: result.mtype.ctype == mtype.ctype
731 redef fun autobox(value: RuntimeVariable, mtype: MType): RuntimeVariable
732 do
733 if value.mtype.ctype == mtype.ctype then
734 return value
735 else if value.mtype.ctype == "val*" then
736 return self.new_expr("((struct instance_{mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype)
737 else if mtype.ctype == "val*" then
738 var valtype = value.mtype.as(MClassType)
739 var res = self.new_var(mtype)
740 if not compiler.runtime_type_analysis.live_types.has(valtype) then
741 self.add("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
742 self.add("printf(\"Dead code executed!\\n\"); exit(1);")
743 return res
744 end
745 self.add("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
746 return res
747 else
748 # Bad things will appen!
749 var res = self.new_var(mtype)
750 self.add("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
751 self.add("printf(\"Cast error: Cannot cast %s to %s.\\n\", \"{value.mtype}\", \"{mtype}\"); exit(1);")
752 return res
753 end
754 end
755
756 redef fun send(mmethod, arguments)
757 do
758 if arguments.first.mcasttype.ctype != "val*" then
759 return self.monomorphic_send(mmethod, arguments.first.mcasttype, arguments)
760 end
761
762 var res: nullable RuntimeVariable
763 var msignature = mmethod.intro.msignature.resolve_for(mmethod.intro.mclassdef.bound_mtype, mmethod.intro.mclassdef.bound_mtype, mmethod.intro.mclassdef.mmodule, true)
764 var ret = msignature.return_mtype
765 if mmethod.is_new then
766 ret = arguments.first.mtype
767 res = self.new_var(ret)
768 else if ret == null then
769 res = null
770 else
771 res = self.new_var(ret)
772 end
773
774 var s = new Buffer
775 var ss = new Buffer
776
777 var recv = arguments.first
778 s.append("val*")
779 ss.append("{recv}")
780 self.varargize(msignature, arguments)
781 for i in [0..msignature.arity[ do
782 var a = arguments[i+1]
783 var t = msignature.mparameters[i].mtype
784 if i == msignature.vararg_rank then
785 t = arguments[i+1].mcasttype
786 end
787 s.append(", {t.ctype}")
788 a = self.autobox(a, t)
789 ss.append(", {a}")
790 end
791
792 var maybenull = recv.mcasttype isa MNullableType
793 if maybenull then
794 self.add("if ({recv} == NULL) \{")
795 if mmethod.name == "==" then
796 assert res != null
797 var arg = arguments[1]
798 if arg.mcasttype isa MNullableType then
799 self.add("{res} = ({arg} == NULL);")
800 else if arg.mcasttype isa MNullType then
801 self.add("{res} = 1; /* is null */")
802 else
803 self.add("{res} = 0; /* {arg.inspect} cannot be null */")
804 end
805 else if mmethod.name == "!=" then
806 assert res != null
807 var arg = arguments[1]
808 if arg.mcasttype isa MNullableType then
809 self.add("{res} = ({arg} != NULL);")
810 else if arg.mcasttype isa MNullType then
811 self.add("{res} = 0; /* is null */")
812 else
813 self.add("{res} = 1; /* {arg.inspect} cannot be null */")
814 end
815 else
816 self.add_abort("Reciever is null")
817 end
818 self.add("\} else \{")
819 end
820
821 var color = self.compiler.as(SeparateCompiler).method_colors[mmethod]
822 var r
823 if ret == null then r = "void" else r = ret.ctype
824 var call = "(({r} (*)({s}))({arguments.first}->class->vft[{color}]))({ss}) /* {mmethod} on {arguments.first.inspect}*/"
825
826 if res != null then
827 self.add("{res} = {call};")
828 else
829 self.add("{call};")
830 end
831
832 if maybenull then
833 self.add("\}")
834 end
835
836 return res
837 end
838
839 redef fun call(mmethoddef, recvtype, arguments)
840 do
841 var res: nullable RuntimeVariable
842 var ret = mmethoddef.msignature.return_mtype
843 if mmethoddef.mproperty.is_new then
844 ret = arguments.first.mtype
845 res = self.new_var(ret)
846 else if ret == null then
847 res = null
848 else
849 ret = ret.resolve_for(mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.bound_mtype, mmethoddef.mclassdef.mmodule, true)
850 res = self.new_var(ret)
851 end
852
853 if self.compiler.modelbuilder.mpropdef2npropdef.has_key(mmethoddef) and
854 self.compiler.modelbuilder.mpropdef2npropdef[mmethoddef] isa AInternMethPropdef then
855 var frame = new Frame(self, mmethoddef, recvtype, arguments)
856 frame.returnlabel = self.get_name("RET_LABEL")
857 frame.returnvar = res
858 var old_frame = self.frame
859 self.frame = frame
860 self.add("\{ /* Inline {mmethoddef} ({arguments.join(",")}) */")
861 mmethoddef.compile_inside_to_c(self, arguments)
862 self.add("{frame.returnlabel.as(not null)}:(void)0;")
863 self.add("\}")
864 self.frame = old_frame
865 return res
866 end
867
868 # Autobox arguments
869 self.adapt_signature(mmethoddef, arguments)
870
871 if res == null then
872 self.add("{mmethoddef.c_name}({arguments.join(", ")});")
873 return null
874 else
875 self.add("{res} = {mmethoddef.c_name}({arguments.join(", ")});")
876 end
877
878 return res
879 end
880
881 redef fun isset_attribute(a, recv)
882 do
883 self.check_recv_notnull(recv)
884 var res = self.new_var(bool_type)
885 self.add("{res} = {recv}->attrs[{self.compiler.as(SeparateCompiler).attr_colors[a]}] != NULL; /* {a} on {recv.inspect}*/")
886 return res
887 end
888
889 redef fun read_attribute(a, recv)
890 do
891 self.check_recv_notnull(recv)
892
893 # What is the declared type of the attribute?
894 var ret = a.intro.static_mtype.as(not null)
895 var intromclassdef = a.intro.mclassdef
896 ret = ret.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
897
898 # Get the attribute or a box (ie. always a val*)
899 var cret = self.object_type.as_nullable
900 var res = self.new_var(cret)
901 res.mcasttype = ret
902 self.add("{res} = {recv}->attrs[{self.compiler.as(SeparateCompiler).attr_colors[a]}]; /* {a} on {recv.inspect} */")
903
904 # Check for Uninitialized attribute
905 if not ret isa MNullableType then
906 self.add("if ({res} == NULL) \{")
907 self.add_abort("Uninitialized attribute {a.name}")
908 self.add("\}")
909 end
910
911 # Return the attribute or its unboxed version
912 # Note: it is mandatory since we reuse the box on write, we do not whant that the box escapes
913 return self.autobox(res, ret)
914 end
915
916 redef fun write_attribute(a, recv, value)
917 do
918 self.check_recv_notnull(recv)
919
920 # What is the declared type of the attribute?
921 var mtype = a.intro.static_mtype.as(not null)
922 var intromclassdef = a.intro.mclassdef
923 mtype = mtype.resolve_for(intromclassdef.bound_mtype, intromclassdef.bound_mtype, intromclassdef.mmodule, true)
924
925 # Adapt the value to the declared type
926 value = self.autobox(value, mtype)
927 var attr = "{recv}->attrs[{self.compiler.as(SeparateCompiler).attr_colors[a]}]"
928 if mtype.ctype != "val*" then
929 assert mtype isa MClassType
930 # The attribute is primitive, thus we store it in a box
931 # The trick is to create the box the first time then resuse the box
932 self.add("if ({attr} != NULL) \{")
933 self.add("((struct instance_{mtype.c_name}*){attr})->value = {value}; /* {a} on {recv.inspect} */")
934 self.add("\} else \{")
935 value = self.autobox(value, self.object_type.as_nullable)
936 self.add("{attr} = {value}; /* {a} on {recv.inspect} */")
937 self.add("\}")
938 else
939 # The attribute is not primitive, thus store it direclty
940 self.add("{attr} = {value}; /* {a} on {recv.inspect} */")
941 end
942 end
943
944 # Build livetype structure retrieving
945 #ENSURE: mtype.need_anchor
946 fun retrieve_anchored_livetype(mtype: MGenericType, buffer: Buffer) do
947 assert mtype.need_anchor
948
949 var compiler = self.compiler.as(SeparateCompiler)
950 for ft in mtype.arguments do
951
952 var ntype = ft
953 var s: String = ""
954 if ntype isa MNullableType then
955 ntype = ntype.mtype
956 end
957
958 if ntype isa MParameterType then
959 var ftcolor = compiler.ft_colors[ntype]
960 buffer.append("[self->type->fts_table->fts[{ftcolor}]->livecolor]")
961 else if ntype isa MVirtualType then
962 var vtcolor = compiler.vt_colors[ntype.mproperty.as(MVirtualTypeProp)]
963 buffer.append("[self->type->vts_table->vts[{vtcolor}]->livecolor]")
964 else if ntype isa MGenericType and ntype.need_anchor then
965 var bbuff = new Buffer
966 retrieve_anchored_livetype(ntype, bbuff)
967 buffer.append("[livetypes_{ntype.mclass.c_name}{bbuff.to_s}->livecolor]")
968 else if ntype isa MClassType then
969 compiler.undead_types.add(ft)
970 buffer.append("[type_{ft.c_name}.livecolor]")
971 else
972 self.add("printf(\"NOT YET IMPLEMENTED: init_instance(%s, {mtype}).\\n\", \"{ft}\"); exit(1);")
973 end
974 end
975 end
976
977 redef fun init_instance(mtype)
978 do
979 var compiler = self.compiler.as(SeparateCompiler)
980 if mtype isa MGenericType and mtype.need_anchor then
981 var buff = new Buffer
982 retrieve_anchored_livetype(mtype, buff)
983 mtype = self.anchor(mtype).as(MClassType)
984 return self.new_expr("NEW_{mtype.mclass.c_name}((struct type *) livetypes_{mtype.mclass.c_name}{buff.to_s})", mtype)
985 end
986 compiler.undead_types.add(mtype)
987 return self.new_expr("NEW_{mtype.mclass.c_name}((struct type *) &type_{mtype.c_name})", mtype)
988 end
989
990 redef fun type_test(value, mtype)
991 do
992 var compiler = self.compiler.as(SeparateCompiler)
993
994 var recv = self.frame.arguments.first
995 var recv_boxed = self.autobox(recv, self.object_type)
996
997 var res = self.new_var(bool_type)
998
999 var cltype = self.get_name("cltype")
1000 self.add_decl("int {cltype};")
1001 var idtype = self.get_name("idtype")
1002 self.add_decl("int {idtype};")
1003
1004 var is_nullable = self.get_name("is_nullable")
1005 self.add_decl("short int {is_nullable};")
1006
1007 var boxed = self.autobox(value, self.object_type)
1008
1009 var ntype = mtype
1010 if ntype isa MNullableType then
1011 ntype = ntype.mtype
1012 end
1013
1014 if ntype isa MParameterType then
1015 var ftcolor = compiler.ft_colors[ntype]
1016 self.add("{cltype} = {recv_boxed}->type->fts_table->fts[{ftcolor}]->color;")
1017 self.add("{idtype} = {recv_boxed}->type->fts_table->fts[{ftcolor}]->id;")
1018 self.add("{is_nullable} = {recv_boxed}->type->fts_table->fts[{ftcolor}]->is_nullable;")
1019 else if ntype isa MGenericType and ntype.need_anchor then
1020 var buff = new Buffer
1021 retrieve_anchored_livetype(ntype, buff)
1022 self.add("{cltype} = livetypes_{ntype.mclass.c_name}{buff.to_s}->color;")
1023 self.add("{idtype} = livetypes_{ntype.mclass.c_name}{buff.to_s}->id;")
1024 self.add("{is_nullable} = livetypes_{ntype.mclass.c_name}{buff.to_s}->is_nullable;")
1025 else if ntype isa MClassType then
1026 compiler.undead_types.add(mtype)
1027 self.add("{cltype} = type_{mtype.c_name}.color;")
1028 self.add("{idtype} = type_{mtype.c_name}.id;")
1029 self.add("{is_nullable} = type_{mtype.c_name}.is_nullable;")
1030 else if ntype isa MVirtualType then
1031 var vtcolor = compiler.vt_colors[ntype.mproperty.as(MVirtualTypeProp)]
1032 self.add("{cltype} = {recv_boxed}->type->vts_table->vts[{vtcolor}]->color;")
1033 self.add("{idtype} = {recv_boxed}->type->vts_table->vts[{vtcolor}]->id;")
1034 self.add("{is_nullable} = {recv_boxed}->type->vts_table->vts[{vtcolor}]->is_nullable;")
1035 else
1036 self.add("printf(\"NOT YET IMPLEMENTED: type_test(%s, {mtype}).\\n\", \"{boxed.inspect}\"); exit(1);")
1037 end
1038
1039 if mtype isa MNullableType then
1040 self.add("{is_nullable} = 1;")
1041 end
1042
1043 # check color is in table
1044 self.add("if({boxed} == NULL) \{")
1045 self.add("{res} = {is_nullable};")
1046 self.add("\} else \{")
1047 self.add("if({cltype} >= {boxed}->type->table_size) \{")
1048 self.add("{res} = 0;")
1049 self.add("\} else \{")
1050 self.add("{res} = {boxed}->type->type_table[{cltype}] == {idtype};")
1051 self.add("\}")
1052 self.add("\}")
1053
1054 return res
1055 end
1056
1057 redef fun is_same_type_test(value1, value2)
1058 do
1059 var res = self.new_var(bool_type)
1060 # Swap values to be symetric
1061 if value2.mtype.ctype != "val*" and value1.mtype.ctype == "val*" then
1062 var tmp = value1
1063 value1 = value2
1064 value2 = tmp
1065 end
1066 if value1.mtype.ctype != "val*" then
1067 if value2.mtype.ctype == value1.mtype.ctype then
1068 self.add("{res} = 1; /* is_same_type_test: compatible types {value1.mtype} vs. {value2.mtype} */")
1069 else if value2.mtype.ctype != "val*" then
1070 self.add("{res} = 0; /* is_same_type_test: incompatible types {value1.mtype} vs. {value2.mtype}*/")
1071 else
1072 var mtype1 = value1.mtype.as(MClassType)
1073 self.add("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name}); /* is_same_type_test */")
1074 end
1075 else
1076 self.add("{res} = ({value1} == {value2}) || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class); /* is_same_type_test */")
1077 end
1078 return res
1079 end
1080
1081 redef fun class_name_string(value)
1082 do
1083 var res = self.get_name("var_class_name")
1084 self.add_decl("const char *{res};")
1085 self.add("{res} = class_names[{value}->type->id];")
1086 return res
1087 end
1088
1089 redef fun equal_test(value1, value2)
1090 do
1091 var res = self.new_var(bool_type)
1092 if value2.mtype.ctype != "val*" and value1.mtype.ctype == "val*" then
1093 var tmp = value1
1094 value1 = value2
1095 value2 = tmp
1096 end
1097 if value1.mtype.ctype != "val*" then
1098 if value2.mtype.ctype == value1.mtype.ctype then
1099 self.add("{res} = {value1} == {value2};")
1100 else if value2.mtype.ctype != "val*" then
1101 self.add("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
1102 else
1103 var mtype1 = value1.mtype.as(MClassType)
1104 self.add("{res} = ({value2} != NULL) && ({value2}->class == (struct class*) &class_{mtype1.c_name});")
1105 self.add("if ({res}) \{")
1106 self.add("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
1107 self.add("\}")
1108 end
1109 else
1110 var s = new Array[String]
1111 # This is just ugly on so many level. this works but must be rewriten
1112 for t in self.compiler.live_primitive_types do
1113 if not t.is_subtype(self.compiler.mainmodule, null, value1.mcasttype) then continue
1114 if not t.is_subtype(self.compiler.mainmodule, null, value2.mcasttype) then continue
1115 s.add "({value1}->class == (struct class*)&class_{t.c_name} && ((struct instance_{t.c_name}*){value1})->value == ((struct instance_{t.c_name}*){value2})->value)"
1116 end
1117 if s.is_empty then
1118 self.add("{res} = {value1} == {value2};")
1119 else
1120 self.add("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->class == {value2}->class && ({s.join(" || ")}));")
1121 end
1122 end
1123 return res
1124 end
1125
1126 redef fun array_instance(array, elttype)
1127 do
1128 var compiler = self.compiler.as(SeparateCompiler)
1129 var nclass = self.get_class("NativeArray")
1130 elttype = self.anchor(elttype)
1131 var arraytype = self.get_class("Array").get_mtype([elttype])
1132 var res = self.init_instance(arraytype)
1133 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
1134 var nat = self.new_var(self.get_class("NativeArray").get_mtype([elttype]))
1135 nat.is_exact = true
1136 compiler.undead_types.add(nat.mtype.as(MClassType))
1137 self.add("{nat} = NEW_{nclass.c_name}({array.length}, (struct type *) &type_{nat.mtype.c_name});")
1138 for i in [0..array.length[ do
1139 var r = self.autobox(array[i], self.object_type)
1140 self.add("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
1141 end
1142 var length = self.int_instance(array.length)
1143 self.send(self.get_property("with_native", arraytype), [res, nat, length])
1144 self.check_init_instance(res)
1145 self.add("\}")
1146 return res
1147 end
1148
1149 redef fun native_array_def(pname, ret_type, arguments)
1150 do
1151 var elttype = arguments.first.mtype
1152 var nclass = self.get_class("NativeArray")
1153 var recv = "((struct instance_{nclass.c_name}*){arguments[0]})->values"
1154 if pname == "[]" then
1155 self.ret(self.new_expr("{recv}[{arguments[1]}]", ret_type.as(not null)))
1156 return
1157 else if pname == "[]=" then
1158 self.add("{recv}[{arguments[1]}]={arguments[2]};")
1159 return
1160 else if pname == "copy_to" then
1161 var recv1 = "((struct instance_{nclass.c_name}*){arguments[1]})->values"
1162 self.add("memcpy({recv1}, {recv}, {arguments[2]}*sizeof({elttype.ctype}));")
1163 return
1164 end
1165 end
1166
1167 redef fun calloc_array(ret_type, arguments)
1168 do
1169 var ret = ret_type.as(MGenericType)
1170 var compiler = self.compiler.as(SeparateCompiler)
1171 compiler.undead_types.add(ret)
1172 var mclass = self.get_class("ArrayCapable")
1173 var ft = mclass.mclass_type.arguments.first.as(MParameterType)
1174 var color = compiler.ft_colors[ft]
1175 self.ret(self.new_expr("NEW_{ret.mclass.c_name}({arguments[1]}, (struct type*) livetypes_array__NativeArray[self->type->fts_table->fts[{color}]->livecolor])", ret_type))
1176 end
1177 end
1178
1179 redef class MClass
1180 # Return the name of the C structure associated to a Nit class
1181 fun c_name: String do
1182 var res = self.c_name_cache
1183 if res != null then return res
1184 res = "{intro_mmodule.name.to_cmangle}__{name.to_cmangle}"
1185 self.c_name_cache = res
1186 return res
1187 end
1188 private var c_name_cache: nullable String
1189 end