0

There is something that I can't quite really understand about stack-based virtual machines: What is the type of the value that is stored in the stack? What I mean is that for example, if I pushed an integer onto the stack, it's clear that it's type is a 32-bit integer. However, if I push a float, a string or even an object reference (in OOPs), their types change. When the stack is created, does it figure out their type as they are pushed on the stack, or does the stack have a predefined entry type, such as only integers, or maybe a pointer? I can't really figure it out, so any help is appreciated.

Seki
  • 11,135
  • 7
  • 46
  • 70
Kai
  • 398
  • 2
  • 11
  • You are implementing the language, not writing. Source cod Si. The language. The stack element can be whatever you deem it to be, based on your needs as the implementor. – user207421 Jun 16 '18 at 11:00

1 Answers1

0

There are various approaches, I just give few examples here.

In V8 JavaScript engine VM (form Chrome browser and Node.js) all objects on a stack a pointers to a structure wich might be similar to this:

class Value {
   char type;
   union {
      Number, String, Object, Array, Date, Set
   }
};

JavaScript VM of Firefox's SpiderMonkey holds 64 bit values on stack, those values are so called NaN-boxed. If higher 3 bits are all set to 1 the next few bits are used to determine the object type, and the rest 48 bits are used as a pointer to the object structure. If the 3 most significant bits are not all 111 then the whole 64 bit value is a double.

The VM stack in a garbage collected environment usually must hold homogenous objects, i.e. objects of the same type, not mixing pointers and integers for instance, so that garbage collector can successfully walk through and check every object recursively starting from stack. For example a value on stack that looks like 0x123456789 can be both a valid integer and a valid pointer, and a garbage collector has no idea to ignore it (if it was an integer) or dereference it (to a potentially wrong memory location).

In fact there are advanced garbage collectors that can actually work with mixed data in the stack making some assumptions, guessing, and keeping extra book keeping.

exebook
  • 32,014
  • 33
  • 141
  • 226