JVMで動作するプログラミング言語を作るにはどうしたらよいのだろう?(6)

東北オープンソースカンファレンスがあと2日です。
ドキドキしてきたきょうこのごろです。
結構疲れてるので日記書くのもめんどくさくなって来てますが、継続は力なりだ。
と思って、ちみちみ書いてきます。


今日はローカル変数を扱う、load,store命令を使ってみます。
load,storeっていう名前はスタックマシンを作ってみたりするときに良く使う名前だったりするようです。
なので、難しいことは何もないように思います。

class a{
	int n() {
		int x, y = 2;
		x = y;
		return x;
	}
}

とりあえず、こんなクラスファイルをjasperでディスアセンブルしますと。

.source                  a.java
.class                   a
.super                   java/lang/Object


.method                  <init>()V
   .limit stack          1
   .limit locals         1
   .line                 1
   aload_0               
   invokespecial         java/lang/Object/<init>()V
   return                
.end method              

.method                  n()I
   .limit stack          1
   .limit locals         3
   .line                 3
   iconst_2                  ; 2をスタックに積む
   istore_2                  ; スタックの2をローカル変数の2番目に入れる
   .line                 4
   iload_2                   ; ローカル変数の2番目の値(2)をスタックに入れる
   istore_1                  ; ローカル変数の1番目に(2)を入れる。
   .line                 5
   iload_1                   ; ローカル変数の1番目の値(2)をスタックに入れる
   ireturn               
.end method              

こんな感じになります。
storeがスタックの内容をpopしてローカル変数に値を入れます。
loadがローカル変数の値をスタックにpushします。
iload,istoreはint型の物で、iload_1,iload_2等、小さい番号ならば1バイトで済みます。


thisの扱いがどうなってるのかを下のソースをディスアセンブルしてみましょう。

class a{
	int n() {
		return b(this);
	}
	static int b(a a_){
		return 1;
	}
}

クラスのthisはどこにはいっているかというとローカル変数の0番目に入っています。
aload_0を使うことで取り出せます。

.method                  n()I
   .limit stack          1
   .limit locals         1
   .line                 3
   aload_0                         ; thisをスタックにpush
   invokestatic          a/b(La;)I ; b関数を呼び出す。
   ireturn               
.end method              

.method                  static b(La;)I ; b関数
   .limit stack          1
   .limit locals         1
   .line                 6
   iconst_1              
   ireturn               
.end method