eed0d475728f8d7561c238abede430c8a4fa01aa
[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 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 return attributes;
157 `}
158
159 # Creates the runtime structures for this class
160 fun create_class(mclass: MClass) do mclass.make_vt(self)
161
162 # Return the value of the attribute `mproperty for the object `recv
163 redef fun read_attribute(mproperty: MAttribute, recv: Instance): Instance
164 do
165 assert recv isa MutableInstance
166
167 # Read the attribute value with perfect hashing
168 var id = mproperty.intro_mclassdef.mclass.vtable.id
169
170 var i = read_attribute_ph(recv.internal_attributes, recv.vtable.internal_vtable,
171 recv.vtable.mask, id, mproperty.offset)
172
173 return i
174 end
175
176 # Return the attribute value in `instance with a sequence of perfect_hashing
177 # `instance is the attributes array of the receiver
178 # `vtable is the pointer to the virtual table of the class (of the receiver)
179 # `mask is the perfect hashing mask of the class
180 # `id is the identifier of the class
181 # `offset is the relative offset of this attribute
182 private fun read_attribute_ph(instance: Pointer, vtable: Pointer, mask: Int, id: Int, offset: Int): Instance `{
183 // Perfect hashing position
184 int hv = mask & id;
185 long unsigned int *pointer = (long unsigned int*)(((long int *)vtable)[-hv]);
186
187 // pointer+1 is the position where the delta of the class is
188 int absolute_offset = *(pointer + 1);
189
190 Instance res = ((Instance *)instance)[absolute_offset + offset];
191
192 return res;
193 `}
194
195 # Replace in `recv the value of the attribute `mproperty by `value
196 redef fun write_attribute(mproperty: MAttribute, recv: Instance, value: Instance)
197 do
198 assert recv isa MutableInstance
199
200 var id = mproperty.intro_mclassdef.mclass.vtable.id
201
202 # TODO : ugly hack
203 recv.attributes[mproperty] = value
204
205 # Replace the old value of mproperty in recv
206 write_attribute_ph(recv.internal_attributes, recv.vtable.internal_vtable,
207 recv.vtable.mask, id, mproperty.offset, value)
208 end
209
210 # Replace the value of an attribute in an instance
211 # `instance is the attributes array of the receiver
212 # `vtable is the pointer to the virtual table of the class (of the receiver)
213 # `mask is the perfect hashing mask of the class
214 # `id is the identifier of the class
215 # `offset is the relative offset of this attribute
216 # `value is the new value for this attribute
217 private fun write_attribute_ph(instance: Pointer, vtable: Pointer, mask: Int, id: Int, offset: Int, value: Instance) `{
218 // Perfect hashing position
219 int hv = mask & id;
220 long unsigned int *pointer = (long unsigned int*)(((long int *)vtable)[-hv]);
221
222 // pointer+1 is the position where the delta of the class is
223 int absolute_offset = *(pointer + 1);
224
225 ((Instance *)instance)[absolute_offset + offset] = value;
226 `}
227 end
228
229 redef class MClass
230 # A reference to the virtual table of this class
231 var vtable: nullable VTable
232
233 # True when the class is effectively loaded by the vm, false otherwise
234 var loaded: Bool = false
235
236 # Cached attributes for faster instanciations of this class
237 var cached_attributes: Array[MAttribute] = new Array[MAttribute]
238
239 # Allocates a VTable for this class and gives it an id
240 private fun make_vt(v: VirtualMachine)
241 do
242 if loaded then return
243
244 # Superclasses contains all superclasses except self
245 var superclasses = new Array[MClass]
246 superclasses.add_all(ancestors)
247 superclasses.remove(self)
248 v.mainmodule.linearize_mclasses(superclasses)
249
250 # Make_vt for super-classes
251 var ids = new Array[Int]
252 var nb_methods = new Array[Int]
253 var nb_attributes = new Array[Int]
254
255 for parent in superclasses do
256 if parent.vtable == null then parent.make_vt(v)
257
258 # Get the number of introduced methods and attributes for this class
259 var methods = 0
260 var attributes = 0
261
262 for p in parent.intro_mproperties(none_visibility) do
263 if p isa MMethod then methods += 1
264 if p isa MAttribute then
265 attributes += 1
266 end
267 end
268
269 ids.push(parent.vtable.id)
270 nb_methods.push(methods)
271 nb_attributes.push(attributes)
272 end
273
274 # When all super-classes have their identifiers and vtables, allocate current one
275 allocate_vtable(v, ids, nb_methods, nb_attributes)
276 loaded = true
277 # The virtual table now needs to be filled with pointer to methods
278 end
279
280 # Allocate a single vtable
281 # ids : Array of superclasses identifiers
282 # nb_methods : Array which contain the number of introducted methods for each class in ids
283 # nb_attributes : Array which contain the number of introducted attributes for each class in ids
284 private fun allocate_vtable(v: VirtualMachine, ids: Array[Int], nb_methods: Array[Int], nb_attributes: Array[Int])
285 do
286 vtable = new VTable
287 var idc = new Array[Int]
288
289 vtable.mask = v.ph.pnand(ids, 1, idc) - 1
290 vtable.id = idc[0]
291 vtable.classname = name
292
293 # Add current id to Array of super-ids
294 var ids_total = new Array[Int]
295 ids_total.add_all(ids)
296 ids_total.push(vtable.id)
297
298 var nb_methods_total = new Array[Int]
299 var nb_attributes_total = new Array[Int]
300
301 var self_methods = 0
302 var self_attributes = 0
303
304 # For self attributes, fixing offsets
305 var relative_offset = 0
306 for p in intro_mproperties(none_visibility) do
307 if p isa MMethod then self_methods += 1
308 if p isa MAttribute then
309 self_attributes += 1
310 p.offset = relative_offset
311 relative_offset += 1
312 cached_attributes.push(p)
313 end
314 end
315
316 nb_methods_total.add_all(nb_methods)
317 nb_methods_total.push(self_methods)
318
319 nb_attributes_total.add_all(nb_attributes)
320 nb_attributes_total.push(self_attributes)
321
322 # Since we have the number of attributes for each class, calculate the delta
323 var d = calculate_delta(nb_attributes_total)
324 vtable.internal_vtable = v.memory_manager.init_vtable(ids_total, nb_methods_total, d, vtable.mask)
325 end
326
327 # Computes delta for each class
328 # A delta represents the offset for this group of attributes in the object
329 # nb_attributes : number of attributes for each class (classes are linearized from Object to current)
330 # return deltas for each class
331 private fun calculate_delta(nb_attributes: Array[Int]): Array[Int]
332 do
333 var deltas = new Array[Int]
334
335 var total = 0
336 for nb in nb_attributes do
337 deltas.push(total)
338 total += nb
339 end
340
341 return deltas
342 end
343 end
344
345 redef class MAttribute
346 # Represents the relative offset of this attribute in the runtime instance
347 var offset: Int
348 end
349
350 # Redef MutableInstance to improve implementation of attributes in objects
351 redef class MutableInstance
352
353 # C-array to store pointers to attributes of this Object
354 var internal_attributes: Pointer
355 end
356
357 # A VTable contains the virtual method table for the dispatch
358 # and informations to perform subtyping tests
359 class VTable
360 # The mask to perform perfect hashing
361 var mask: Int
362
363 # Unique identifier given by perfect hashing
364 var id: Int
365
366 # Pointer to the c-allocated area, represents the virtual table
367 var internal_vtable: Pointer
368
369 # The short classname of this class
370 var classname: String
371
372 init do end
373 end
374
375 redef class Instance
376 var vtable: nullable VTable
377 end
378
379 # Handle memory, used for allocate virtual table and associated structures
380 class MemoryManager
381
382 # Allocate and fill a virtual table
383 fun init_vtable(ids: Array[Int], nb_methods: Array[Int], nb_attributes: Array[Int], mask: Int): Pointer
384 do
385 # Allocate in C current virtual table
386 var res = intern_init_vtable(ids, nb_methods, nb_attributes, mask)
387
388 return res
389 end
390
391 # Construct virtual tables with a bi-dimensional layout
392 private fun intern_init_vtable(ids: Array[Int], nb_methods: Array[Int], deltas: Array[Int], mask: Int): Pointer
393 import Array[Int].length, Array[Int].[] `{
394
395 // Allocate and fill current virtual table
396 int i;
397 int total_size = 0; // total size of this virtual table
398 int nb_classes = Array_of_Int_length(nb_methods);
399 for(i = 0; i<nb_classes; i++) {
400 /* - One for each method of this class
401 * - One for the delta (offset of this group of attributes in objects)
402 * - One for the id
403 */
404 total_size += Array_of_Int__index(nb_methods, i);
405 total_size += 2;
406 }
407
408 // Add the size of the perfect hashtable
409 total_size += mask+1;
410 long unsigned int* vtable = malloc(sizeof(long unsigned int)*total_size);
411
412 // Initialisation to the first position of the virtual table (ie : Object)
413 long unsigned int *init = vtable + mask + 2;
414 for(i=0; i<total_size; i++)
415 vtable[i] = (long unsigned int)init;
416
417 // Set the virtual table to its position 0
418 // ie: after the hashtable
419 vtable = vtable + mask + 1;
420
421 int current_size = 1;
422 for(i = 0; i < nb_classes; i++) {
423 /*
424 vtable[hv] contains a pointer to the group of introducted methods
425 For each superclasse we have in virtual table :
426 (id | delta | introduced methods)
427 */
428 int hv = mask & Array_of_Int__index(ids, i);
429
430 vtable[current_size] = Array_of_Int__index(ids, i);
431 vtable[current_size + 1] = Array_of_Int__index(deltas, i);
432 vtable[-hv] = (long unsigned int)&(vtable[current_size]);
433
434 current_size += 2;
435 current_size += Array_of_Int__index(nb_methods, i);
436 }
437
438 return vtable;
439 `}
440 end