src: create groups for related things
[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 intrude 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 init_naive_interpreter(interpreter, 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 and garbage collection
45 var memory_manager: MemoryManager = new MemoryManager
46
47 # Subtyping test for the virtual machine
48 redef fun is_subtype(sub, sup: MType): Bool
49 do
50 var anchor = self.frame.arguments.first.mtype.as(MClassType)
51 var sup_accept_null = false
52 if sup isa MNullableType then
53 sup_accept_null = true
54 sup = sup.mtype
55 else if sup isa MNullType then
56 sup_accept_null = true
57 end
58
59 # Can `sub` provides null or not?
60 # Thus we can match with `sup_accept_null`
61 # Also discard the nullable marker if it exists
62 if sub isa MNullableType then
63 if not sup_accept_null then return false
64 sub = sub.mtype
65 else if sub isa MNullType then
66 return sup_accept_null
67 end
68 # Now the case of direct null and nullable is over
69
70 # An unfixed formal type can only accept itself
71 if sup isa MParameterType or sup isa MVirtualType then
72 return sub == sup
73 end
74
75 if sub isa MParameterType or sub isa MVirtualType then
76 sub = sub.anchor_to(mainmodule, anchor)
77 # Manage the second layer of null/nullable
78 if sub isa MNullableType then
79 if not sup_accept_null then return false
80 sub = sub.mtype
81 else if sub isa MNullType then
82 return sup_accept_null
83 end
84 end
85
86 assert sub isa MClassType
87
88 # `sup` accepts only null
89 if sup isa MNullType then return false
90
91 assert sup isa MClassType
92
93 # Create the sup vtable if not create
94 if not sup.mclass.loaded then create_class(sup.mclass)
95
96 # Sub can be discovered inside a Generic type during the subtyping test
97 if not sub.mclass.loaded then create_class(sub.mclass)
98
99 if anchor == null then anchor = sub
100 if sup isa MGenericType then
101 var sub2 = sub.supertype_to(mainmodule, anchor, sup.mclass)
102 assert sub2.mclass == sup.mclass
103
104 for i in [0..sup.mclass.arity[ do
105 var sub_arg = sub2.arguments[i]
106 var sup_arg = sup.arguments[i]
107 var res = is_subtype(sub_arg, sup_arg)
108
109 if res == false then return false
110 end
111 return true
112 end
113
114 var super_id = sup.mclass.vtable.id
115 var mask = sub.mclass.vtable.mask
116
117 return inter_is_subtype(super_id, mask, sub.mclass.vtable.internal_vtable)
118 end
119
120 # Subtyping test with perfect hashing
121 private fun inter_is_subtype(id: Int, mask:Int, vtable: Pointer): Bool `{
122 // hv is the position in hashtable
123 int hv = id & mask;
124
125 // Follow the pointer to somewhere in the vtable
126 long unsigned int *offset = (long unsigned int*)(((long int *)vtable)[-hv]);
127
128 // If the pointed value is corresponding to the identifier, the test is true, otherwise false
129 return *offset == id;
130 `}
131
132 # Redef init_instance to simulate the loading of a class
133 redef fun init_instance(recv: Instance)
134 do
135 if not recv.mtype.as(MClassType).mclass.loaded then create_class(recv.mtype.as(MClassType).mclass)
136
137 recv.vtable = recv.mtype.as(MClassType).mclass.vtable
138
139 assert(recv isa MutableInstance)
140
141 recv.internal_attributes = init_internal_attributes(null_instance, recv.mtype.as(MClassType).mclass.cached_attributes.length)
142
143 super
144 end
145
146 # Initialize the internal representation of an object (its attribute values)
147 private fun init_internal_attributes(null_instance: Instance, size: Int): Pointer
148 import Array[Instance].length, Array[Instance].[] `{
149
150 Instance* attributes = malloc(sizeof(Instance) * size);
151
152 int i;
153 for(i=0; i<size; i++)
154 attributes[i] = null_instance;
155
156 Instance_incr_ref(null_instance);
157 return attributes;
158 `}
159
160 # Creates the runtime structures for this class
161 fun create_class(mclass: MClass) do mclass.make_vt(self)
162
163 # Return the value of the attribute `mproperty for the object `recv
164 redef fun read_attribute(mproperty: MAttribute, recv: Instance): Instance
165 do
166 assert recv isa MutableInstance
167
168 # Read the attribute value with perfect hashing
169 var id = mproperty.intro_mclassdef.mclass.vtable.id
170
171 var i = read_attribute_ph(recv.internal_attributes, recv.vtable.internal_vtable,
172 recv.vtable.mask, id, mproperty.offset)
173
174 return i
175 end
176
177 # Return the attribute value in `instance with a sequence of perfect_hashing
178 # `instance is the attributes array of the receiver
179 # `vtable is the pointer to the virtual table of the class (of the receiver)
180 # `mask is the perfect hashing mask of the class
181 # `id is the identifier of the class
182 # `offset is the relative offset of this attribute
183 private fun read_attribute_ph(instance: Pointer, vtable: Pointer, mask: Int, id: Int, offset: Int): Instance `{
184 // Perfect hashing position
185 int hv = mask & id;
186 long unsigned int *pointer = (long unsigned int*)(((long int *)vtable)[-hv]);
187
188 // pointer+1 is the position where the delta of the class is
189 int absolute_offset = *(pointer + 1);
190
191 Instance res = ((Instance *)instance)[absolute_offset + offset];
192
193 return res;
194 `}
195
196 # Replace in `recv the value of the attribute `mproperty by `value
197 redef fun write_attribute(mproperty: MAttribute, recv: Instance, value: Instance)
198 do
199 assert recv isa MutableInstance
200
201 var id = mproperty.intro_mclassdef.mclass.vtable.id
202
203 # Replace the old value of mproperty in recv
204 write_attribute_ph(recv.internal_attributes, recv.vtable.internal_vtable,
205 recv.vtable.mask, id, mproperty.offset, value)
206 end
207
208 # Replace the value of an attribute in an instance
209 # `instance is the attributes array of the receiver
210 # `vtable is the pointer to the virtual table of the class (of the receiver)
211 # `mask is the perfect hashing mask of the class
212 # `id is the identifier of the class
213 # `offset is the relative offset of this attribute
214 # `value is the new value for this attribute
215 private fun write_attribute_ph(instance: Pointer, vtable: Pointer, mask: Int, id: Int, offset: Int, value: Instance) `{
216 // Perfect hashing position
217 int hv = mask & id;
218 long unsigned int *pointer = (long unsigned int*)(((long int *)vtable)[-hv]);
219
220 // pointer+1 is the position where the delta of the class is
221 int absolute_offset = *(pointer + 1);
222
223 ((Instance *)instance)[absolute_offset + offset] = value;
224 Instance_incr_ref(value);
225 `}
226 end
227
228 redef class MClass
229 # A reference to the virtual table of this class
230 var vtable: nullable VTable
231
232 # True when the class is effectively loaded by the vm, false otherwise
233 var loaded: Bool = false
234
235 # Cached attributes for faster instanciations of this class
236 var cached_attributes: Array[MAttribute] = new Array[MAttribute]
237
238 # Allocates a VTable for this class and gives it an id
239 private fun make_vt(v: VirtualMachine)
240 do
241 if loaded then return
242
243 # Superclasses contains all superclasses except self
244 var superclasses = new Array[MClass]
245 superclasses.add_all(ancestors)
246 superclasses.remove(self)
247 v.mainmodule.linearize_mclasses(superclasses)
248
249 # Make_vt for super-classes
250 var ids = new Array[Int]
251 var nb_methods = new Array[Int]
252 var nb_attributes = new Array[Int]
253
254 for parent in superclasses do
255 if parent.vtable == null then parent.make_vt(v)
256
257 # Get the number of introduced methods and attributes for this class
258 var methods = 0
259 var attributes = 0
260
261 for p in parent.intro_mproperties(none_visibility) do
262 if p isa MMethod then methods += 1
263 if p isa MAttribute then
264 attributes += 1
265 end
266 end
267
268 ids.push(parent.vtable.id)
269 nb_methods.push(methods)
270 nb_attributes.push(attributes)
271 end
272
273 # When all super-classes have their identifiers and vtables, allocate current one
274 allocate_vtable(v, ids, nb_methods, nb_attributes)
275 loaded = true
276 # The virtual table now needs to be filled with pointer to methods
277 end
278
279 # Allocate a single vtable
280 # ids : Array of superclasses identifiers
281 # nb_methods : Array which contain the number of introducted methods for each class in ids
282 # nb_attributes : Array which contain the number of introducted attributes for each class in ids
283 private fun allocate_vtable(v: VirtualMachine, ids: Array[Int], nb_methods: Array[Int], nb_attributes: Array[Int])
284 do
285 vtable = new VTable
286 var idc = new Array[Int]
287
288 vtable.mask = v.ph.pnand(ids, 1, idc) - 1
289 vtable.id = idc[0]
290 vtable.classname = name
291
292 # Add current id to Array of super-ids
293 var ids_total = new Array[Int]
294 ids_total.add_all(ids)
295 ids_total.push(vtable.id)
296
297 var nb_methods_total = new Array[Int]
298 var nb_attributes_total = new Array[Int]
299
300 var self_methods = 0
301 var self_attributes = 0
302
303 # For self attributes, fixing offsets
304 var relative_offset = 0
305 for p in intro_mproperties(none_visibility) do
306 if p isa MMethod then self_methods += 1
307 if p isa MAttribute then
308 self_attributes += 1
309 p.offset = relative_offset
310 relative_offset += 1
311 cached_attributes.push(p)
312 end
313 end
314
315 nb_methods_total.add_all(nb_methods)
316 nb_methods_total.push(self_methods)
317
318 nb_attributes_total.add_all(nb_attributes)
319 nb_attributes_total.push(self_attributes)
320
321 # Since we have the number of attributes for each class, calculate the delta
322 var d = calculate_delta(nb_attributes_total)
323 vtable.internal_vtable = v.memory_manager.init_vtable(ids_total, nb_methods_total, d, vtable.mask)
324 end
325
326 # Computes delta for each class
327 # A delta represents the offset for this group of attributes in the object
328 # nb_attributes : number of attributes for each class (classes are linearized from Object to current)
329 # return deltas for each class
330 private fun calculate_delta(nb_attributes: Array[Int]): Array[Int]
331 do
332 var deltas = new Array[Int]
333
334 var total = 0
335 for nb in nb_attributes do
336 deltas.push(total)
337 total += nb
338 end
339
340 return deltas
341 end
342 end
343
344 redef class MAttribute
345 # Represents the relative offset of this attribute in the runtime instance
346 var offset: Int
347 end
348
349 # Redef MutableInstance to improve implementation of attributes in objects
350 redef class MutableInstance
351
352 # C-array to store pointers to attributes of this Object
353 var internal_attributes: Pointer
354 end
355
356 # A VTable contains the virtual method table for the dispatch
357 # and informations to perform subtyping tests
358 class VTable
359 # The mask to perform perfect hashing
360 var mask: Int is noinit
361
362 # Unique identifier given by perfect hashing
363 var id: Int is noinit
364
365 # Pointer to the c-allocated area, represents the virtual table
366 var internal_vtable: Pointer is noinit
367
368 # The short classname of this class
369 var classname: String is noinit
370 end
371
372 redef class Instance
373 var vtable: nullable VTable
374 end
375
376 # Handle memory, used for allocate virtual table and associated structures
377 class MemoryManager
378
379 # Allocate and fill a virtual table
380 fun init_vtable(ids: Array[Int], nb_methods: Array[Int], nb_attributes: Array[Int], mask: Int): Pointer
381 do
382 # Allocate in C current virtual table
383 var res = intern_init_vtable(ids, nb_methods, nb_attributes, mask)
384
385 return res
386 end
387
388 # Construct virtual tables with a bi-dimensional layout
389 private fun intern_init_vtable(ids: Array[Int], nb_methods: Array[Int], deltas: Array[Int], mask: Int): Pointer
390 import Array[Int].length, Array[Int].[] `{
391
392 // Allocate and fill current virtual table
393 int i;
394 int total_size = 0; // total size of this virtual table
395 int nb_classes = Array_of_Int_length(nb_methods);
396 for(i = 0; i<nb_classes; i++) {
397 /* - One for each method of this class
398 * - One for the delta (offset of this group of attributes in objects)
399 * - One for the id
400 */
401 total_size += Array_of_Int__index(nb_methods, i);
402 total_size += 2;
403 }
404
405 // Add the size of the perfect hashtable (mask +1)
406 // Add one because we start to fill the vtable at position 1 (0 is the init position)
407 total_size += mask+2;
408 long unsigned int* vtable = malloc(sizeof(long unsigned int)*total_size);
409
410 // Initialisation to the first position of the virtual table (ie : Object)
411 long unsigned int *init = vtable + mask + 2;
412 for(i=0; i<total_size; i++)
413 vtable[i] = (long unsigned int)init;
414
415 // Set the virtual table to its position 0
416 // ie: after the hashtable
417 vtable = vtable + mask + 1;
418
419 int current_size = 1;
420 for(i = 0; i < nb_classes; i++) {
421 /*
422 vtable[hv] contains a pointer to the group of introducted methods
423 For each superclasse we have in virtual table :
424 (id | delta | introduced methods)
425 */
426 int hv = mask & Array_of_Int__index(ids, i);
427
428 vtable[current_size] = Array_of_Int__index(ids, i);
429 vtable[current_size + 1] = Array_of_Int__index(deltas, i);
430 vtable[-hv] = (long unsigned int)&(vtable[current_size]);
431
432 current_size += 2;
433 current_size += Array_of_Int__index(nb_methods, i);
434 }
435
436 return vtable;
437 `}
438 end