nitvm: Method dispatch is implemented with direct access
[nit.git] / src / vm.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2014 Julien Pagès <julien.pages@lirmm.fr>
4 #
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
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
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.
16
17 # Implementation of the Nit virtual machine
18 module vm
19
20 import interpreter::naive_interpreter
21 import model_utils
22 import perfect_hashing
23
24 redef class ModelBuilder
25 redef fun run_naive_interpreter(mainmodule: MModule, arguments: Array[String])
26 do
27 var time0 = get_time
28 self.toolcontext.info("*** NITVM STARTING ***", 1)
29
30 var interpreter = new VirtualMachine(self, mainmodule, arguments)
31 interpreter.start(mainmodule)
32
33 var time1 = get_time
34 self.toolcontext.info("*** NITVM STOPPING : {time1-time0} ***", 2)
35 end
36 end
37
38 # A virtual machine based on the naive_interpreter
39 class VirtualMachine super NaiveInterpreter
40
41 # Perfect hashing and perfect numbering
42 var ph: Perfecthashing = new Perfecthashing
43
44 # Handles memory allocated in C
45 var memory_manager: MemoryManager = new MemoryManager
46
47 # The unique instance of the `MInit` value
48 var initialization_value: Instance is noinit
49
50 init
51 do
52 var init_type = new MInitType(mainmodule.model)
53 initialization_value = new MutableInstance(init_type)
54 super
55 end
56
57 # Subtyping test for the virtual machine
58 redef fun is_subtype(sub, sup: MType): Bool
59 do
60 var anchor = self.frame.arguments.first.mtype.as(MClassType)
61 var sup_accept_null = false
62 if sup isa MNullableType then
63 sup_accept_null = true
64 sup = sup.mtype
65 else if sup isa MNullType then
66 sup_accept_null = true
67 end
68
69 # Can `sub` provides null or not?
70 # Thus we can match with `sup_accept_null`
71 # Also discard the nullable marker if it exists
72 if sub isa MNullableType then
73 if not sup_accept_null then return false
74 sub = sub.mtype
75 else if sub isa MNullType then
76 return sup_accept_null
77 end
78 # Now the case of direct null and nullable is over
79
80 # An unfixed formal type can only accept itself
81 if sup isa MParameterType or sup isa MVirtualType then
82 return sub == sup
83 end
84
85 if sub isa MParameterType or sub isa MVirtualType then
86 sub = sub.anchor_to(mainmodule, anchor)
87 # Manage the second layer of null/nullable
88 if sub isa MNullableType then
89 if not sup_accept_null then return false
90 sub = sub.mtype
91 else if sub isa MNullType then
92 return sup_accept_null
93 end
94 end
95
96 assert sub isa MClassType
97
98 # `sup` accepts only null
99 if sup isa MNullType then return false
100
101 assert sup isa MClassType
102
103 # Create the sup vtable if not create
104 if not sup.mclass.loaded then create_class(sup.mclass)
105
106 # Sub can be discovered inside a Generic type during the subtyping test
107 if not sub.mclass.loaded then create_class(sub.mclass)
108
109 if sup isa MGenericType then
110 var sub2 = sub.supertype_to(mainmodule, anchor, sup.mclass)
111 assert sub2.mclass == sup.mclass
112
113 for i in [0..sup.mclass.arity[ do
114 var sub_arg = sub2.arguments[i]
115 var sup_arg = sup.arguments[i]
116 var res = is_subtype(sub_arg, sup_arg)
117
118 if res == false then return false
119 end
120 return true
121 end
122
123 var super_id = sup.mclass.vtable.id
124 var mask = sub.mclass.vtable.mask
125
126 return inter_is_subtype(super_id, mask, sub.mclass.vtable.internal_vtable)
127 end
128
129 # Subtyping test with perfect hashing
130 private fun inter_is_subtype(id: Int, mask:Int, vtable: Pointer): Bool `{
131 // hv is the position in hashtable
132 int hv = id & mask;
133
134 // Follow the pointer to somewhere in the vtable
135 long unsigned int *offset = (long unsigned int*)(((long int *)vtable)[-hv]);
136
137 // If the pointed value is corresponding to the identifier, the test is true, otherwise false
138 return *offset == id;
139 `}
140
141 # Redef init_instance to simulate the loading of a class
142 redef fun init_instance(recv: Instance)
143 do
144 if not recv.mtype.as(MClassType).mclass.loaded then create_class(recv.mtype.as(MClassType).mclass)
145
146 recv.vtable = recv.mtype.as(MClassType).mclass.vtable
147
148 assert recv isa MutableInstance
149
150 recv.internal_attributes = init_internal_attributes(initialization_value, recv.mtype.as(MClassType).mclass.all_mattributes(mainmodule, none_visibility).length)
151 super
152 end
153
154 # Associate a `PrimitiveInstance` to its `VTable`
155 redef fun init_instance_primitive(recv: Instance)
156 do
157 if not recv.mtype.as(MClassType).mclass.loaded then create_class(recv.mtype.as(MClassType).mclass)
158
159 recv.vtable = recv.mtype.as(MClassType).mclass.vtable
160 end
161
162 # Create a virtual table for this `MClass` if not already done
163 redef fun get_primitive_class(name: String): MClass
164 do
165 var mclass = super
166
167 if not mclass.loaded then create_class(mclass)
168
169 return mclass
170 end
171
172 # Initialize the internal representation of an object (its attribute values)
173 # `init_instance` is the initial value of attributes
174 private fun init_internal_attributes(init_instance: Instance, size: Int): Pointer
175 import Array[Instance].length, Array[Instance].[] `{
176
177 Instance* attributes = malloc(sizeof(Instance) * size);
178
179 int i;
180 for(i=0; i<size; i++)
181 attributes[i] = init_instance;
182
183 Instance_incr_ref(init_instance);
184 return attributes;
185 `}
186
187 # Creates the runtime structures for this class
188 fun create_class(mclass: MClass) do mclass.make_vt(self)
189
190 # Execute `mproperty` for a `args` (where `args[0]` is the receiver).
191 redef fun send(mproperty: MMethod, args: Array[Instance]): nullable Instance
192 do
193 var recv = args.first
194 var mtype = recv.mtype
195 var ret = send_commons(mproperty, args, mtype)
196 if ret != null then return ret
197
198 var propdef = method_dispatch(mproperty, recv.vtable.as(not null), recv)
199
200 return self.call(propdef, args)
201 end
202
203 # Method dispatch, for a given global method `mproperty`
204 # returns the most specific local method in the class corresponding to `vtable`
205 private fun method_dispatch(mproperty: MMethod, vtable: VTable, recv: Instance): MMethodDef
206 do
207 if mproperty.intro_mclassdef.mclass.positions_methods[recv.mtype.as(MClassType).mclass] != -1 then
208 return method_dispatch_sst(vtable.internal_vtable, mproperty.absolute_offset)
209 else
210 return method_dispatch_ph(vtable.internal_vtable, vtable.mask,
211 mproperty.intro_mclassdef.mclass.vtable.id, mproperty.offset)
212 end
213 end
214
215 # Execute a method dispatch with perfect hashing
216 private fun method_dispatch_ph(vtable: Pointer, mask: Int, id: Int, offset: Int): MMethodDef `{
217 // Perfect hashing position
218 int hv = mask & id;
219 long unsigned int *pointer = (long unsigned int*)(((long int *)vtable)[-hv]);
220
221 // pointer+2 is the position where methods are
222 // Add the offset of property and get the method implementation
223 MMethodDef propdef = (MMethodDef)*(pointer + 2 + offset);
224
225 return propdef;
226 `}
227
228 # Execute a method dispatch with direct access and return the appropriate `MMethodDef`
229 # `vtable` : Pointer to the internal pointer of the class
230 # `absolute_offset` : Absolute offset from the beginning of the virtual table
231 private fun method_dispatch_sst(vtable: Pointer, absolute_offset: Int): MMethodDef `{
232 // pointer+2 is the position where methods are
233 // Add the offset of property and get the method implementation
234 MMethodDef propdef = (MMethodDef)((long int *)vtable)[absolute_offset];
235
236 return propdef;
237 `}
238
239 # Return the value of the attribute `mproperty` for the object `recv`
240 redef fun read_attribute(mproperty: MAttribute, recv: Instance): Instance
241 do
242 assert recv isa MutableInstance
243
244 var i: Instance
245
246 if mproperty.intro_mclassdef.mclass.positions_attributes[recv.mtype.as(MClassType).mclass] != -1 then
247 # if this attribute class has an unique position for this receiver, then use direct access
248 i = read_attribute_sst(recv.internal_attributes, mproperty.absolute_offset)
249 else
250 # Otherwise, read the attribute value with perfect hashing
251 var id = mproperty.intro_mclassdef.mclass.vtable.id
252
253 i = read_attribute_ph(recv.internal_attributes, recv.vtable.internal_vtable,
254 recv.vtable.mask, id, mproperty.offset)
255 end
256
257 # If we get a `MInit` value, throw an error
258 if i == initialization_value then
259 fatal("Uninitialized attribute {mproperty.name}")
260 abort
261 end
262
263 return i
264 end
265
266 # Return the attribute value in `instance` with a sequence of perfect_hashing
267 # * `instance` is the attributes array of the receiver
268 # * `vtable` is the pointer to the virtual table of the class (of the receiver)
269 # * `mask` is the perfect hashing mask of the class
270 # * `id` is the identifier of the class
271 # * `offset` is the relative offset of this attribute
272 private fun read_attribute_ph(instance: Pointer, vtable: Pointer, mask: Int, id: Int, offset: Int): Instance `{
273 // Perfect hashing position
274 int hv = mask & id;
275 long unsigned int *pointer = (long unsigned int*)(((long int *)vtable)[-hv]);
276
277 // pointer+1 is the position where the delta of the class is
278 int absolute_offset = *(pointer + 1);
279
280 Instance res = ((Instance *)instance)[absolute_offset + offset];
281
282 return res;
283 `}
284
285 # Return the attribute value in `instance` with a direct access (SST)
286 # * `instance` is the attributes array of the receiver
287 # * `offset` is the absolute offset of this attribute
288 private fun read_attribute_sst(instance: Pointer, offset: Int): Instance `{
289 /* We can make a direct access to the attribute value
290 because this attribute is always at the same position
291 for the class of this receiver */
292 Instance res = ((Instance *)instance)[offset];
293
294 return res;
295 `}
296
297 # Replace in `recv` the value of the attribute `mproperty` by `value`
298 redef fun write_attribute(mproperty: MAttribute, recv: Instance, value: Instance)
299 do
300 assert recv isa MutableInstance
301
302 # Replace the old value of mproperty in recv
303 if mproperty.intro_mclassdef.mclass.positions_attributes[recv.mtype.as(MClassType).mclass] != -1 then
304 # if this attribute class has an unique position for this receiver, then use direct access
305 write_attribute_sst(recv.internal_attributes, mproperty.absolute_offset, value)
306 else
307 # Otherwise, use perfect hashing to replace the old value
308 var id = mproperty.intro_mclassdef.mclass.vtable.id
309
310 write_attribute_ph(recv.internal_attributes, recv.vtable.internal_vtable,
311 recv.vtable.mask, id, mproperty.offset, value)
312 end
313 end
314
315 # Replace the value of an attribute in an instance
316 # * `instance` is the attributes array of the receiver
317 # * `vtable` is the pointer to the virtual table of the class (of the receiver)
318 # * `mask` is the perfect hashing mask of the class
319 # * `id` is the identifier of the class
320 # * `offset` is the relative offset of this attribute
321 # * `value` is the new value for this attribute
322 private fun write_attribute_ph(instance: Pointer, vtable: Pointer, mask: Int, id: Int, offset: Int, value: Instance) `{
323 // Perfect hashing position
324 int hv = mask & id;
325 long unsigned int *pointer = (long unsigned int*)(((long int *)vtable)[-hv]);
326
327 // pointer+1 is the position where the delta of the class is
328 int absolute_offset = *(pointer + 1);
329
330 ((Instance *)instance)[absolute_offset + offset] = value;
331 Instance_incr_ref(value);
332 `}
333
334 # Replace the value of an attribute in an instance with direct access
335 # * `instance` is the attributes array of the receiver
336 # * `offset` is the absolute offset of this attribute
337 # * `value` is the new value for this attribute
338 private fun write_attribute_sst(instance: Pointer, offset: Int, value: Instance) `{
339 // Direct access to the position with the absolute offset
340 ((Instance *)instance)[offset] = value;
341 Instance_incr_ref(value);
342 `}
343
344 # Is the attribute `mproperty` initialized in the instance `recv`?
345 redef fun isset_attribute(mproperty: MAttribute, recv: Instance): Bool
346 do
347 assert recv isa MutableInstance
348
349 # Read the attribute value with internal perfect hashing read
350 # because we do not want to throw an error if the value is `initialization_value`
351 var id = mproperty.intro_mclassdef.mclass.vtable.id
352
353 var i = read_attribute_ph(recv.internal_attributes, recv.vtable.internal_vtable,
354 recv.vtable.mask, id, mproperty.offset)
355
356 return i != initialization_value
357 end
358 end
359
360 redef class MClass
361 # A reference to the virtual table of this class
362 var vtable: nullable VTable
363
364 # True when the class is effectively loaded by the vm, false otherwise
365 var loaded: Bool = false
366
367 # For each loaded subclass, keep the position of the group of attributes
368 # introduced by self class in the object
369 var positions_attributes: HashMap[MClass, Int] = new HashMap[MClass, Int]
370
371 # For each loaded subclass, keep the position of the group of methods
372 # introduced by self class in the vtable
373 var positions_methods: HashMap[MClass, Int] = new HashMap[MClass, Int]
374
375 # Allocates a VTable for this class and gives it an id
376 private fun make_vt(v: VirtualMachine)
377 do
378 if loaded then return
379
380 # `superclasses` contains the order of superclasses for virtual tables
381 var superclasses = superclasses_ordering(v)
382 superclasses.remove(self)
383
384 # Make_vt for super-classes
385 var ids = new Array[Int]
386 var nb_methods = new Array[Int]
387 var nb_attributes = new Array[Int]
388
389 # Absolute offset of attribute from the beginning of the attributes table
390 var offset_attributes = 0
391
392 # Absolute offset of method from the beginning of the methods table,
393 # is initialize to 3 because the first position is empty in the virtual table
394 # and the second and third are respectively class id and delta
395 var offset_methods = 3
396
397 # The previous element in `superclasses`
398 var previous_parent: nullable MClass = null
399 if superclasses.length > 0 then previous_parent = superclasses[0]
400 for parent in superclasses do
401 if not parent.loaded then parent.make_vt(v)
402
403 # Get the number of introduced methods and attributes for this class
404 var methods = 0
405 var attributes = 0
406
407 for p in parent.intro_mproperties(none_visibility) do
408 if p isa MMethod then methods += 1
409 if p isa MAttribute then attributes += 1
410 end
411
412 ids.push(parent.vtable.id)
413 nb_methods.push(methods)
414 nb_attributes.push(attributes)
415
416 # Update `positions_attributes` and `positions_methods` in `parent`.
417 # If the position is invariant for this parent, store this position
418 # else store a special value (-1)
419 var pos_attr = -1
420 var pos_meth = -1
421
422 if previous_parent.as(not null).positions_attributes[parent] == offset_attributes then pos_attr = offset_attributes
423 if previous_parent.as(not null).positions_methods[parent] == offset_methods then pos_meth = offset_methods
424
425 parent.update_positions(pos_attr, pos_meth, self)
426
427 offset_attributes += attributes
428 offset_methods += methods
429 offset_methods += 2 # Because each block starts with an id and the delta
430 end
431
432 # When all super-classes have their identifiers and vtables, allocate current one
433 allocate_vtable(v, ids, nb_methods, nb_attributes, offset_attributes, offset_methods)
434 loaded = true
435
436 # The virtual table now needs to be filled with pointer to methods
437 superclasses.add(self)
438 for cl in superclasses do
439 fill_vtable(v, vtable.as(not null), cl)
440 end
441 end
442
443 # Allocate a single vtable
444 # * `ids : Array of superclasses identifiers
445 # * `nb_methods : Array which contain the number of introduced methods for each class in ids
446 # * `nb_attributes : Array which contain the number of introduced attributes for each class in ids
447 # * `offset_attributes : Offset from the beginning of the table of the group of attributes
448 # * `offset_methods : Offset from the beginning of the table of the group of methods
449 private fun allocate_vtable(v: VirtualMachine, ids: Array[Int], nb_methods: Array[Int], nb_attributes: Array[Int],
450 offset_attributes: Int, offset_methods: Int)
451 do
452 vtable = new VTable
453 var idc = new Array[Int]
454
455 vtable.mask = v.ph.pnand(ids, 1, idc) - 1
456 vtable.id = idc[0]
457 vtable.classname = name
458
459 # Add current id to Array of super-ids
460 var ids_total = new Array[Int]
461 ids_total.add_all(ids)
462 ids_total.push(vtable.id)
463
464 var nb_methods_total = new Array[Int]
465 var nb_attributes_total = new Array[Int]
466
467 var self_methods = 0
468 var nb_introduced_attributes = 0
469
470 # Fixing offsets for self attributes and methods
471 var relative_offset_attr = 0
472 var relative_offset_meth = 0
473 for p in intro_mproperties(none_visibility) do
474 if p isa MMethod then
475 self_methods += 1
476 p.offset = relative_offset_meth
477 p.absolute_offset = offset_methods + relative_offset_meth
478 relative_offset_meth += 1
479 end
480 if p isa MAttribute then
481 nb_introduced_attributes += 1
482 p.offset = relative_offset_attr
483 p.absolute_offset = offset_attributes + relative_offset_attr
484 relative_offset_attr += 1
485 end
486 end
487
488 nb_methods_total.add_all(nb_methods)
489 nb_methods_total.push(self_methods)
490
491 nb_attributes_total.add_all(nb_attributes)
492 nb_attributes_total.push(nb_introduced_attributes)
493
494 # Save the offsets of self class
495 update_positions(offset_attributes, offset_methods, self)
496
497 # Since we have the number of attributes for each class, calculate the delta
498 var deltas = calculate_delta(nb_attributes_total)
499 vtable.internal_vtable = v.memory_manager.init_vtable(ids_total, nb_methods_total, deltas, vtable.mask)
500 end
501
502 # Fill the vtable with methods of `self` class
503 # * `v` : Current instance of the VirtualMachine
504 # * `table` : the table of self class, will be filled with its methods
505 private fun fill_vtable(v:VirtualMachine, table: VTable, cl: MClass)
506 do
507 var methods = new Array[MMethodDef]
508 for m in cl.intro_mproperties(none_visibility) do
509 if m isa MMethod then
510 # `propdef` is the most specific implementation for this MMethod
511 var propdef = m.lookup_first_definition(v.mainmodule, self.intro.bound_mtype)
512 methods.push(propdef)
513 end
514 end
515
516 # Call a method in C to put propdefs of self methods in the vtables
517 v.memory_manager.put_methods(vtable.internal_vtable, vtable.mask, cl.vtable.id, methods)
518 end
519
520 # Computes delta for each class
521 # A delta represents the offset for this group of attributes in the object
522 # *`nb_attributes` : number of attributes for each class (classes are linearized from Object to current)
523 # * return deltas for each class
524 private fun calculate_delta(nb_attributes: Array[Int]): Array[Int]
525 do
526 var deltas = new Array[Int]
527
528 var total = 0
529 for nb in nb_attributes do
530 deltas.push(total)
531 total += nb
532 end
533
534 return deltas
535 end
536
537 # Order superclasses of self
538 # Return the order of superclasses in runtime structures of this class
539 private fun superclasses_ordering(v: VirtualMachine): Array[MClass]
540 do
541 var superclasses = new Array[MClass]
542 superclasses.add_all(ancestors)
543
544 var res = new Array[MClass]
545 if superclasses.length > 1 then
546 # Starting at self
547 var ordering = self.dfs(v, res)
548
549 return ordering
550 else
551 # There is no super-class, self is Object
552 return superclasses
553 end
554 end
555
556 # A kind of Depth-First-Search for superclasses ordering
557 # *`v` : the current executed instance of VirtualMachine
558 # * `res` : Result Array, ie current superclasses ordering
559 private fun dfs(v: VirtualMachine, res: Array[MClass]): Array[MClass]
560 do
561 # Add this class at the beginning
562 res.insert(self, 0)
563
564 var direct_parents = self.in_hierarchy(v.mainmodule).direct_greaters.to_a
565
566 if direct_parents.length > 1 then
567 # Prefix represents the class which has the most properties
568 # we try to choose it in first to reduce the number of potential recompilations
569 var prefix = null
570 var max = -1
571 for cl in direct_parents do
572 # If we never have visited this class
573 if not res.has(cl) then
574 var properties_length = cl.all_mproperties(v.mainmodule, none_visibility).length
575 if properties_length > max then
576 max = properties_length
577 prefix = cl
578 end
579 end
580 end
581
582 if prefix != null then
583 # Add the prefix class ordering at the beginning of our sequence
584 var prefix_res = new Array[MClass]
585 prefix_res = prefix.dfs(v, prefix_res)
586
587 # Then we recurse on other classes
588 for cl in direct_parents do
589 if cl != prefix then
590 res = new Array[MClass]
591 res = cl.dfs(v, res)
592
593 for cl_res in res do
594 if not prefix_res.has(cl_res) then prefix_res.push(cl_res)
595 end
596 end
597 end
598 res = prefix_res
599 end
600
601 res.push(self)
602 else
603 if direct_parents.length > 0 then
604 res = direct_parents.first.dfs(v, res)
605 end
606 end
607
608 if not res.has(self) then res.push(self)
609
610 return res
611 end
612
613 # Update positions of the class `cl`
614 # * `attributes_offset`: absolute offset of introduced attributes
615 # * `methods_offset`: absolute offset of introduced methods
616 private fun update_positions(attributes_offsets: Int, methods_offset:Int, cl: MClass)
617 do
618 positions_attributes[cl] = attributes_offsets
619 positions_methods[cl] = methods_offset
620 end
621 end
622
623 redef class MAttribute
624 # Relative offset of this attribute in the runtime instance
625 # (beginning of the block of its introducing class)
626 var offset: Int
627
628 # Absolute offset of this attribute in the runtime instance (beginning of the attribute table)
629 var absolute_offset: Int
630 end
631
632 redef class MMethod
633 # Relative offset of this method in the virtual table (from the beginning of the block)
634 var offset: Int
635
636 # Absolute offset of this method in the virtual table (from the beginning of the vtable)
637 var absolute_offset: Int
638 end
639
640 # Redef MutableInstance to improve implementation of attributes in objects
641 redef class MutableInstance
642
643 # C-array to store pointers to attributes of this Object
644 var internal_attributes: Pointer
645 end
646
647 # Redef to associate an `Instance` to its `VTable`
648 redef class Instance
649
650 # Associate a runtime instance to its virtual table which contains methods, types etc.
651 var vtable: nullable VTable
652 end
653
654 # Is the type of the initial value inside attributes
655 class MInitType
656 super MType
657
658 redef var model: Model
659
660 redef fun to_s do return "InitType"
661 redef fun as_nullable do return self
662 redef fun need_anchor do return false
663 redef fun resolve_for(mtype, anchor, mmodule, cleanup_virtual) do return self
664 redef fun can_resolve_for(mtype, anchor, mmodule) do return true
665
666 redef fun collect_mclassdefs(mmodule) do return new HashSet[MClassDef]
667
668 redef fun collect_mclasses(mmodule) do return new HashSet[MClass]
669
670 redef fun collect_mtypes(mmodule) do return new HashSet[MClassType]
671 end
672
673 # A VTable contains the virtual method table for the dispatch
674 # and informations to perform subtyping tests
675 class VTable
676 # The mask to perform perfect hashing
677 var mask: Int is noinit
678
679 # Unique identifier given by perfect hashing
680 var id: Int is noinit
681
682 # Pointer to the c-allocated area, represents the virtual table
683 var internal_vtable: Pointer is noinit
684
685 # The short classname of this class
686 var classname: String is noinit
687 end
688
689 # Handle memory, used for allocate virtual table and associated structures
690 class MemoryManager
691
692 # Allocate and fill a virtual table
693 fun init_vtable(ids: Array[Int], nb_methods: Array[Int], nb_attributes: Array[Int], mask: Int): Pointer
694 do
695 # Allocate in C current virtual table
696 var res = intern_init_vtable(ids, nb_methods, nb_attributes, mask)
697
698 return res
699 end
700
701 # Construct virtual tables with a bi-dimensional layout
702 private fun intern_init_vtable(ids: Array[Int], nb_methods: Array[Int], deltas: Array[Int], mask: Int): Pointer
703 import Array[Int].length, Array[Int].[] `{
704
705 // Allocate and fill current virtual table
706 int i;
707 int total_size = 0; // total size of this virtual table
708 int nb_classes = Array_of_Int_length(nb_methods);
709 for(i = 0; i<nb_classes; i++) {
710 /* - One for each method of this class
711 * - One for the delta (offset of this group of attributes in objects)
712 * - One for the id
713 */
714 total_size += Array_of_Int__index(nb_methods, i);
715 total_size += 2;
716 }
717
718 // Add the size of the perfect hashtable (mask +1)
719 // Add one because we start to fill the vtable at position 1 (0 is the init position)
720 total_size += mask+2;
721 long unsigned int* vtable = malloc(sizeof(long unsigned int)*total_size);
722
723 // Initialisation to the first position of the virtual table (ie : Object)
724 long unsigned int *init = vtable + mask + 2;
725 for(i=0; i<total_size; i++)
726 vtable[i] = (long unsigned int)init;
727
728 // Set the virtual table to its position 0
729 // ie: after the hashtable
730 vtable = vtable + mask + 1;
731
732 int current_size = 1;
733 for(i = 0; i < nb_classes; i++) {
734 /*
735 vtable[hv] contains a pointer to the group of introduced methods
736 For each superclasse we have in virtual table :
737 (id | delta | introduced methods)
738 */
739 int hv = mask & Array_of_Int__index(ids, i);
740
741 vtable[current_size] = Array_of_Int__index(ids, i);
742 vtable[current_size + 1] = Array_of_Int__index(deltas, i);
743 vtable[-hv] = (long unsigned int)&(vtable[current_size]);
744
745 current_size += 2;
746 current_size += Array_of_Int__index(nb_methods, i);
747 }
748
749 return vtable;
750 `}
751
752 # Put implementation of methods of a class in `vtable`
753 # * `vtable` : Pointer to the C-virtual table
754 # * `mask` : perfect-hashing mask of the class corresponding to the vtable
755 # * `id` : id of the target class
756 # * `methods` : array of MMethodDef of the target class
757 fun put_methods(vtable: Pointer, mask: Int, id: Int, methods: Array[MMethodDef])
758 import Array[MMethodDef].length, Array[MMethodDef].[] `{
759
760 // Get the area to fill with methods by a sequence of perfect hashing
761 int hv = mask & id;
762 long unsigned int *pointer = (long unsigned int*)(((long unsigned int *)vtable)[-hv]);
763
764 // pointer+2 is the beginning of the area for methods implementation
765 int length = Array_of_MMethodDef_length(methods);
766 long unsigned int *area = (pointer + 2);
767 int i;
768
769 for(i=0; i<length; i++)
770 {
771 MMethodDef method = Array_of_MMethodDef__index(methods, i);
772 area[i] = (long unsigned int)method;
773 MMethodDef_incr_ref(method);
774 }
775 `}
776 end