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