解释器指令入口——转发表

张开发
2026/4/4 20:28:46 15 分钟阅读
解释器指令入口——转发表
解释器指令入口——转发表JVM虚拟机当执行到某个字节码指令时,并不是像想象中的采用下列C语言的形式执行void Execute(ByteCode code){ switch(code){ case NOP: do_nop(); break; case ACONST_NULL: do_aconst_null(); break; ... } }之所以hotspot不能用上述方法的原因是计算机的流水线会由于分支判断而冲刷,因此采用查表的方式。考虑到JVM模拟栈式计算机,栈式计算机每次计算后的结果都保存在栈顶,x86架构下其结果保存在rax寄存器中。为了充分利用CPU的流水线机制,hotspot根据栈顶的状态配合一张转发表来决定下一条指令的用法。该表保存了各个字节的具体实现的入口地址。当JVM在逐个执行字节码的指令时,CPU会查表直接加载各指令实现的汇编序列,这样可以有效地利用CPU的流水线机制以提高计算机执行的速度。转发表转发表是一个二维表,该表有2列,一列为栈顶状态,一列保存字节码栈顶状态在_x86中就是rax中保存的值的类型转发表的定义如下classDispatchTable{public:enum{length=1BitsPerByte};//字节码个数,256个private:address _table[number_of_states][length];其中,number_of_states是栈顶的状态个数,栈顶状态定义如下enumTosState{// describes the tos cache contentsbtos=0,// byte, bool tos cachedztos=1,// byte, bool tos cachedctos=2,// char tos cachedstos=3,// short tos cacheditos=4,// int tos cachedltos=5,// long tos cachedftos=6,// float tos cacheddtos=7,// double tos cachedatos=8,// object cachedvtos=9,// tos not cachednumber_of_states,ilgl// illegal state: should not occur};转发表的布局如下栈顶状态字节码btos0x0 (nop)btos0x1 (aconst_null)btos0x2 (iconst_m1)……ztos0x0 (nop)ztos0x1 (aconst_null)ztos0x2 (iconst_m1)……解释器的转发表定义如下/*templateInterpreter.cpp*/DispatchTable TemplateInterpreter::_active_table;JVM虚拟机初始化对该表进行了初始化操作/*templateInterpreterGenerator.cpp*///生成解释器所需要的一切内容voidTemplateInterpreterGenerator::generate_all(){...// Bytecodes

更多文章