e65136df59445531406ed40a9ac7e79bc2ea0a3a
[cacao.git] / doc / handbook / jit.tex
1 \chapter{The Just-In-Time Compiler}
2
3 \section{Introduction}
4
5 \section{The Java Virtual Machine}
6
7 \label{chapjvm}
8
9 The JavaVM is a typed stack architecture \cite{javavm96}. There are
10 different instructions for integer, long integer, floating point and
11 address types. Byte and character types have only special memory access
12 instructions and are treated as integers for arithmetic operations. The
13 main instruction set consists of arithmetic/logical and load/store/constant
14 instructions. There are special instructions for array access and for
15 accessing the fields of objects (memory access), for method invocation,
16 and  for type checking. A JavaVM has to check the program for type
17 correctness and executes only correct programs. The following examples show
18 some important JavaVM instructions and how a Java program is represented by
19 these instructions.
20
21 \begin{tabular}{ll}
22 {\tt iload  n}& load contents of local variable n      \\
23 {\tt istore n}& store stack top in local variable n    \\
24 {\tt imul    }& product of 2 topmost stack elements    \\ 
25 {\tt isub    }& difference of 2 topmost stack elements \\
26 \end{tabular} 
27
28 The Java assignment statement {\tt a = b - c * d} is translated into
29
30 \begin{tabular}{ll}
31 {\tt iload b }& load contents of variable b   \\
32 {\tt iload c }& load contents of variable c   \\
33 {\tt iload d }& load contents of variable d   \\
34 {\tt imul    }& compute c * d                 \\
35 {\tt isub    }& compute b - (c * d)           \\
36 {\tt istore a}& store stack top in variable a \\
37 \end{tabular} 
38
39 Accessing the fields of objects is handled by the instructions {\tt
40 getfield} and {\tt putfield}. The instruction {\tt getfield} expects an
41 object reference on the stack and has an index into the constant pool as an
42 operand. The index into the constant pool must be a reference to a pair
43 containing the class name and a field name. The types of the classes
44 referenced by the constant pool index and by the object reference must be
45 compatible, a fact which is usually checked statically at load time. The
46 object reference has to be different from the {\tt null} pointer, a fact
47 which must usually be checked at run time.
48
49 Array access is handled by the {\tt aload} and {\tt astore} instructions.
50 Separate versions of these instructions exist for each of the basic types
51 ({\tt byte}, {\tt int}, {\tt float}, {\tt ref}, etc.). The {\tt aload}
52 instruction expects a reference to an array and an index (of type {\tt
53 int}) on the stack. The array reference must not be the {\tt null} pointer.
54 The index must be greater than or equal to zero and less than the array
55 length.
56
57 There a special commands for method invocation. Each method has its own
58 virtual stack and an area for local variables. After the method invocation,
59 the stack of the caller is empty and the arguments are copied into the
60 first local variables of the called method. After execution of a {\tt
61 return} instruction, the called method returns to its caller. If the called
62 method is a function, it pops the return value from its own stack and
63 pushes it onto the stack of the caller.
64
65 The {\tt instanceof} and {\tt checkcast} instructions are used for subtype
66 testing. Both expect a reference to an object on the stack and have an
67 index into the constant pool as operand. The index must reference a class,
68 array or interface type. The two instructions differ in their result and in
69 their behavior if the object reference is {\tt null}.
70
71
72 \section{Translation of stack code to register code}
73
74 \label{chaptranslation}
75
76 The architecture of a RISC processor is completely different from the stack
77 architecture of the JavaVM. RISC processors have large sets of registers.
78 (The Alpha has 32 integer registers and 32 floating point registers which
79 are both 64 bits wide.) They execute arithmetic and logic operations only
80 on values which are held in registers. Load and store instructions are
81 provided to move data between memory and registers. Local variables of
82 methods usually reside in registers and are saved in memory only during a
83 method call or if there are too few registers. The use of registers for
84 parameter passing is defined by calling conventions.
85
86 \subsection{Machine code translation examples}
87
88 The previous example expression {\tt a = b - c * d} would be translated
89 by an optimizing C compiler to the following two Alpha instructions (the
90 variables {\tt a}, {\tt b}, {\tt c} and {\tt d} reside in registers):
91
92 \begin{quote}
93 \begin{tabular}{ll}
94 {\tt MULL c,d,tmp0 }&{\tt ; tmp0 = c * d }\\
95 {\tt SUBL b,tmp0,a }&{\tt ; a = b - tmp0 }\\
96 \end{tabular} 
97 \end{quote}
98
99 If JavaVM code is translated to machine code, the stack is eliminated and
100 the stack slots are represented by temporary variables usually residing in
101 registers. A naive translation of the previous example would result in the
102 following Alpha instructions:
103
104 \begin{quote}
105 \begin{tabular}{ll}
106 {\tt MOVE b,t0    }&{\tt ; iload b } \\
107 {\tt MOVE c,t1    }&{\tt ; iload c } \\
108 {\tt MOVE d,t2    }&{\tt ; iload d } \\
109 {\tt MULL t1,t2,t1}&{\tt ; imul    } \\
110 {\tt SUBL t0,t1,t0}&{\tt ; isub    } \\
111 {\tt MOVE t0,a    }&{\tt ; istore a} \\
112 \end{tabular} 
113 \end{quote}
114
115 The problems of translating JavaVM code to machine code are primarily the
116 elimination of the unnecessary copy instructions and finding an efficient
117 register allocation algorithm. A common but expensive technique is to do
118 the naive translation and use an additional pass for copy elimination and
119 coalescing.
120
121
122 \section{The translation algorithm}
123
124 The new translation algorithm can get by with three passes. The first pass
125 determines basic blocks and builds a representation of the JavaVM 
126 instructions which is faster to decode. The second pass analyses the stack
127 and generates a static stack structure. During stack analysis variable
128 dependencies are tracked and register requirements are computed. In the
129 final pass register allocation of temporary registers is combined with
130 machine code generation.
131
132 The new compiler computes the exact number of objects needed or computes an
133 upper bound and allocates the memory for the necessary temporary data
134 structures in three big blocks (the basic block array, the instruction
135 array and the stack array). Eliminating all the double linked lists also
136 reduced the memory requirements by a factor of five.
137
138
139 \subsection{Basic block determination}
140
141 The first pass scans the JavaVM instructions, determines the basic blocks
142 and generates an array of instructions which has fixed size and is easier
143 to decode in the following passes. Each instruction contains the opcode,
144 two operands and a pointer to the static stack structure after the
145 instruction (see next sections). The different opcodes of JavaVM
146 instructions which fold operands into the opcode are represented by just
147 one opcode in the instruction array.
148
149
150 \subsection{Basic block interfacing convention}
151
152 The handling of control flow joins was quite complicated in the old
153 compiler. We therefore introduced a fixed interface at basic block
154 boundaries. Every stack slot at a basic block boundary is assigned a fixed
155 interface register. The stack analysis pass determines the type of the
156 register and if it has to be saved across method invocations. To enlarge
157 the size of basic blocks method invocations do not end basic blocks. To
158 guide our compiler design we did some static analysis on a large
159 application written in Java: the javac compiler and the libraries it uses.
160 Table \ref{tab-1} shows that in more than 93\% of the cases the stack is
161 empty at basic block boundaries and that the maximal stack depth is 6.
162 Using this data it becomes clear that the old join handling did not improve
163 the quality of the machine code.
164
165 \begin{table*}
166 \begin{center}
167 \begin{tabular}[b]{|l|c|c|c|c|c|c|c|c|}
168 \hline 
169 stack depth &   0  &  1  &  2  &  3  &  4  &  5  &  6 & $>$6 \\ \hline           
170 occurrences & 7930 & 258 & 136 & 112 &  36 &  8  &  3 &  0   \\ \hline           
171 \end{tabular}
172 \caption{distribution of stack depth at block boundary}
173 \label{tab-1}
174 \end{center}
175 \end{table*}
176
177
178 \subsection{Copy elimination}
179
180 To eliminate unnecessary copies the loading of values is delayed until the
181 instruction is reached which consumes the value. To compute the information
182 a the run time stack is simulated at compile time. Instead of values the
183 compile time stack contains the type of the value, if a local variable was
184 loaded to a stack location and similar information. Adl-Tabatabai
185 \cite{Taba+98} used a dynamic stack which is changed at every instruction.
186 A dynamic stack only gives the possibility to move information from earlier
187 instructions to later instructions. We use a static stack structure which
188 enables information flow in both directions.
189
190 Fig.~\ref{Trans1} shows our instruction and stack representation. An
191 instruction has a reference to the stack before the instruction and the
192 stack after the instruction. The stack is represented as a linked list. The
193 two stacks can be seen as the source and destination operands of an
194 instruction. In the implementation only the destination stack is stored,
195 the source stack is the destination of stack of the previous instruction.
196
197 \begin{figure}[htb]
198 \begin{center}
199 \setlength{\unitlength}{1mm}
200 \begin{picture}(25,32)
201 \put( 0, 0  ){\makebox(10,5){\tt b}}
202 \put( 5, 2.5){\oval(10,5)}
203 \put( 5, 9  ){\vector(0,-1){4}}
204 \put( 0, 9  ){\makebox(10,5){\tt c}}
205 \put( 5,11.5){\oval(10,5)}
206 \put( 5,18  ){\vector(0,-1){4}}
207 \put( 0,18  ){\makebox(10,5){\tt d}}
208 \put( 5,20.5){\oval(10,5)}
209 %\put( 5,27  ){\vector(0,-1){4}}
210 \put(15, 9  ){\makebox(10,5){\tt c*d}}
211 \put(20,11.5){\oval(10,5)}
212 \put(20, 9  ){\line(0,-1){2}}
213 \put( 5, 7  ){\line(1,0){15}}
214 \put(10,27  ){\framebox(15,5){\tt imul}}
215 \put(20,27  ){\vector(0,-1){13}}
216 \put(15,27  ){\line(0,-1){6.5}}
217 \put(15,20.5){\vector(-1,0){5}}
218 \end{picture}
219 \caption{instruction and stack representation}
220 \label{Trans1}
221 \end{center}
222 \end{figure}
223
224 This representation can easily be used for copy elimination. Each stack
225 element not only contains the type of the stack slot but also the local
226 variable number of which it is a copy, the argument number if it is an
227 argument, the interface register number if it is an interface. Load (push
228 the content of a variable onto the stack) and store store instructions do
229 no generate a copy machine instruction if the stack slot contains the same
230 local variable. Generated machine instructions for arithmetic operations
231 directly use the local variables as their operands.
232
233 There are some pitfalls with this scheme. Take the example of
234 fig.~\ref{Trans2}. The stack bottom contains the local variable {\tt a}.
235 The instruction {\tt istore a} will write a new value for {\tt a} and will
236 make a later use of this variable invalid. To avoid this we have to copy 
237 the local variable to a stack variable. An important decision is at which
238 position the copy instruction should be inserted. Since there is a high
239 number of {\tt dup} instructions in Java programs (around 4\%) and it is
240 possible that a local variable resides in memory, the copy should be done
241 with the {\tt load} instruction. Since the stack is represented as a linked
242 list only the destination stack has to be checked for occurrences of the
243 offending variable and these occurrences are replaced by a stack variable.
244
245
246 \begin{figure}[htb]
247 \begin{center}
248 \setlength{\unitlength}{1mm}
249 \begin{picture}(79,32)
250 \put( 0,27  ){\framebox(15,5){\tt iload a}}
251 \put(16,27  ){\framebox(13,5){\tt dup}}
252 \put(30,27  ){\framebox(17,5){\tt iconst 1}}
253 \put(48,27  ){\framebox(13,5){\tt iadd}}
254 \put(62,27  ){\framebox(17,5){\tt istore a}}
255 \put(10,27  ){\vector(0,-1){22}}
256 \put( 5,27  ){\vector(0,-1){4}}
257 \put( 5, 0  ){\makebox(10,5){\tt a}}
258 \put(10, 2.5){\oval(10,5)}
259 \put(20,27  ){\line(0,-1){2}}
260 \put(20,25  ){\line(-1,0){10}}
261 \put(25,27  ){\vector(0,-1){13}}
262 \put(20, 9  ){\makebox(10,5){\tt a}}
263 \put(25,11.5){\oval(10,5)}
264 \put(25, 9  ){\line(0,-1){2}}
265 \put(10, 7  ){\line(1,0){63}}
266 \put(36,27  ){\line(0,-1){2}}
267 \put(36,25  ){\line(-1,0){11}}
268 \put(41,27  ){\vector(0,-1){4}}
269 \put(36,18  ){\makebox(10,5){\tt 1}}
270 \put(41,20.5){\oval(10,5)}
271 \put(41,18  ){\line(0,-1){2}}
272 \put(41,16  ){\line(-1,0){16}}
273 \put(52,27  ){\line(0,-1){2}}
274 \put(52,25  ){\line(-1,0){11}}
275 \put(73,27  ){\line(0,-1){20}}
276 \put(57,27  ){\vector(0,-1){13}}
277 \put(52, 9  ){\makebox(10,5){\tt +}}
278 \put(57,11.5){\oval(10,5)}
279 \put(57,9   ){\line(0,-1){2}}
280 \put(68,27  ){\line(0,-1){2}}
281 \put(68,25  ){\line(-1,0){11}}
282 \end{picture}
283 \caption{anti dependence}
284 \label{Trans2}
285 \end{center}
286 \end{figure}
287
288 To answer the question of how often this could happen and how expensive
289 the stack search is, we analysed again the {\tt javac} compiler. In more
290 than 98\% of the cases the stack is empty (see table \ref{tab-2}). In only
291 0.2\% of the cases the stack depth is higher than 1 and the biggest stack
292 depth is 3.
293
294 \begin{table}[htb]
295 \begin{center}
296 \begin{tabular}[b]{|l|c|c|c|c|c|}
297 \hline 
298 stack depth &   0  &  1  &  2  &  3  & $>$3 \\ \hline           
299 occurrences & 2167 & 31  &  1  &  3  &  0   \\ \hline           
300 \end{tabular}
301 \caption{distribution of {\tt store} stack depth}
302 \label{tab-2}
303 \end{center}
304 \end{table}
305
306 \begin{table*}
307 \begin{center}
308 \begin{tabular}[b]{|l|c|c|c|c|c|c|c|c|c|c|}
309 \hline 
310 chain length &  1  &  2 &  3 &  4 &  5 &  6 &  7 & 8 & 9 & $>$9 \\ \hline           
311 occurrences  & 1892& 62 & 23 & 62 & 30 & 11 & 41 & 9 & 7 &  65  \\ \hline           
312 \end{tabular}
313 \caption{distribution of creator-store distances}
314 \label{tab-3}
315 \end{center}
316 \end{table*}
317
318 To avoid copy instructions when executing a {\tt store} it is necessary to
319 connect the  creation of a value with the store which consumes it. In that
320 case a {\tt store} not only can conflict with copies of a local variable
321 which result from {\tt load} instructions before the creator of the value,
322 but also with {\tt load} and {\tt store} instructions which exist between
323 the creation of value and the {\tt store}. In fig.~\ref{Trans3} the {\tt
324 iload a} instruction conflicts with the {\tt istore a} instruction.
325
326 \begin{figure}[htb]
327 \begin{center}
328 \setlength{\unitlength}{1mm}
329 \begin{picture}(67,27)
330 \put( 0,22  ){\framebox(15,5){\tt iadd}}
331 \put(16,22  ){\framebox(15,5){\tt iload a}}
332 \put(32,22  ){\framebox(17,5){\tt istore b}}
333 \put(50,22  ){\framebox(17,5){\tt istore a}}
334 \put(10,22  ){\vector(0,-1){13}}
335 \put( 5,22  ){\line(0,-1){2}}
336 \put( 5,20 ){\line(-1,0){3}}
337 \put( 2,20  ){\vector(0,-1){20}}
338 \put(10, 4  ){\line(0,-1){2}}
339 \put( 5, 4  ){\makebox(10,5){\tt +}}
340 \put(10, 6.5){\oval(10,5)}
341 \put(21,22  ){\line(0,-1){2}}
342 \put(21,20  ){\line(-1,0){11}}
343 \put(26,22  ){\vector(0,-1){4}}
344 \put(21,13  ){\makebox(10,5){\tt a}}
345 \put(26,15.5){\oval(10,5)}
346 \put(26,13  ){\line(0,-1){2}}
347 \put(10,11  ){\line(1,0){46}}
348 \put(38,22  ){\line(0,-1){2}}
349 \put(38,20  ){\line(-1,0){12}}
350 \put(43,22  ){\line(0,-1){11}}
351 \put(56,22  ){\line(0,-1){11}}
352 \put(61,22  ){\line(0,-1){20}}
353 \put( 2, 2  ){\line(1,0){59}}
354 \end{picture}
355 \caption{anti dependence}
356 \label{Trans3}
357 \end{center}
358 \end{figure}
359
360 The anti dependences are detected by checking the stack locations of the
361 previous instructions for conflicts. Since the stack locations are
362 allocated as one big array just the stack elements which have a higher
363 index than the current stack element have to be checked. Table \ref{tab-3}
364 gives the distribution of the distance between the creation of the value
365 and the corresponding store. In 86\% of the cases the distance is one.
366
367 \begin{figure*}[htb]
368 \begin{center}
369 %\small
370 \begin{verbatim}
371   java.io.ByteArrayOutputStream.write (int)void
372
373   Local Table:
374        0:                (adr) S15
375        1:    (int) S14
376        2:    (int) S13
377        3:    (int) S12   (adr) S12
378
379   Interface Table:
380        0:    (int) T24
381
382   [                 L00]        0  ALOAD         0
383   [                 T23]        1  GETFIELD      16
384   [                 L02]        2  IADDCONST     1
385   [                 L02]        3  NOP         
386   [                    ]        4  ISTORE        2
387   [                 L02]        5  ILOAD         2
388   [             L00 L02]        6  ALOAD         0
389   [             T23 L02]        7  GETFIELD      8
390   [             T23 L02]        8  ARRAYLENGTH  
391   [                    ]        9  IF_ICMPLE     L005
392                                 ...............
393
394   [                    ]       18  IF_ICMPLT     L003
395   [                    ] L002:
396   [                 I00]       19  ILOAD         3
397   [                 I00]       20  GOTO          L004
398   [                    ] L003:
399   [                 I00]       21  ILOAD         2
400   [                 A00] L004:
401   [                 L03]       22  BUILTIN1      newarray_byte
402   [                    ]       23  ASTORE        3
403   [                 L00]       24  ALOAD         0
404   [                 A00]       25  GETFIELD      8
405   [             A01 A00]       26  ICONST        0
406   [         A02 A01 A00]       27  ALOAD         3
407   [     A03 A02 A01 A00]       28  ICONST        0
408   [ L00 A03 A02 A01 A00]       29  ALOAD         0
409   [ A04 A03 A02 A01 A00]       30  GETFIELD      16
410   [                    ]       31  INVOKESTATIC  java/lang/System.arraycopy
411   [                 L00]       32  ALOAD         0
412   [             L03 L00]       33  ALOAD         3
413   [                    ]       34  PUTFIELD      8
414   [                    ] L005:
415                                ...............
416
417   [                    ]       45  RETURN       
418 \end{verbatim}
419 \caption{Example: intermediate instructions and stack contents}
420 \label{IntermediateStack}
421 \end{center}
422 \end{figure*}
423
424 The output dependences are checked by storing the instruction number of the
425 last store in each local variable. If a store conflicts due to dependences
426 the creator places the value in a stack register. Additional dependences
427 arise because of exceptions. The exception mechanism in Java is precise.
428 Therefore {\tt store} instructions are not allowed to be executed before
429 an exception raising instruction. This is checked easily be remembering
430 the last instruction which could raise an exception. In methods which contain
431 no exception handler this conflict can be safely ignored because no
432 exception handler can have access to these variables.
433
434
435 \subsection{Register allocation}
436
437 Expensive register allocation algorithms are neither suitable nor necessary.
438 The {\tt javac} compiler does a coloring of the local variables and assigns
439 the same number to variables which are not active at the same time. The
440 stack variables have implicitly encoded their live ranges. When a value is
441 pushed, the live range start. When a value is popped, the live range ends.
442
443 Complications arise only with stack manipulation instructions like {\tt dup}
444 and {\tt swap}. We flag therefore the first creation of a stack variable and
445 mark a duplicated one as a copy. The register used for this variable can
446 be reused only after the last copy is popped.
447
448 During stack analysis stack variables are marked which have to survive a
449 method invocation. These stack variables and local variables are assigned
450 callee saved registers. If there are not enough registers available,
451 these variables are allocated in memory.
452
453 Efficient implementation of method invocation is crucial to the performance
454 of Java. Therefore, we preallocate the argument registers and the return
455 value in a similar way as we handle store instructions. Input arguments (in
456 Java input arguments are the first variables) for leaf procedures (and
457 input arguments for processors with register windows) are preassigned, too.
458
459
460 \subsection{Instruction combining}
461
462 Together with stack analysis we combine constant loading instructions with
463 selected instructions which are following immediately. In the class of
464 combinable instructions are add, subtract, multiply and divide instructions,
465 logical and shift instructions and compare/branch instructions. During code
466 generation the constant is checked if it lies in the range for immediate
467 operands of the target architecture and appropriate code is generated.
468
469 The old translator did for some complex instructions an expansion in
470 multiple instructions to avoid complex instructions in the later passes.
471 One of such instructions was the expansion of the {\tt lookup} instruction
472 in a series of load constant and compare and branch instructions. Since
473 the constants are usually quite small this unnecessarily increased the
474 size of the intermediate representation and the final code. The new
475 compiler delays the expansion into multiple instructions to the code
476 generation pass which reduces all representations and speeds up the
477 compilation.
478
479
480 \subsection{Example}
481
482 Fig. \ref{IntermediateStack} shows the intermediate representation and
483 stack information as produced by the compiler for debugging purposes. The
484 {\tt Local Table} gives the types and register assignment for the local
485 variables. The Java compiler reuses the same local variable slot for
486 different local variables if there life ranges do not overlap. In this
487 example the variable slot 3 is even used for local variables of different
488 types (integer and address). The JIT-compiler assigned the saved register
489 12 to this variable.
490
491 One interface register is used in this example entering the basic block
492 with label {\tt L004}. At the entry of the basic block the interface
493 register has to be copied to the argument register {\tt A00}. This is one
494 of the rare cases where a more sophisticated coalescing algorithm could
495 have allocated an argument register for the interface.
496
497 At instruction 2 and 3 you can see the combining of a constant with an
498 arithmetic instruction. Since the instructions are allocated in an array
499 the empty slot has to be filled with a {\tt NOP} instruction. The {\tt
500 ADDCONSTANT} instruction already has the local variable {\tt L02} as
501 destination, an information which comes from the later {\tt ISTORE} at
502 number 4. Similarly the {\tt INVOKESTATIC} at number 31 has marked all its
503 operands as arguments. In this example all copy (beside the one to the
504 interface register) have been eliminated.
505
506
507 \subsection{Complexity of the algorithm}
508
509 The complexity of the algorithm is mostly linear with respect to the number
510 of instructions and the number of local variables plus the number of stack
511 slots. There are only a small number of spots where it is not linear. 
512
513 \begin{itemize}
514 \item At the begin of a basic block the stack has to be copied to separate
515       the stacks of different basic blocks. Table \ref{tab-1} shows that
516       the stack at the boundary of a basic block is in most cases zero.
517       Therefore, this copying does not influence the linear performance of
518       the algorithm.
519 \item A store has to check for a later use of the same variable. Table
520       \ref{tab-2} shows that this is not a problem, too.
521 \item A store additionally has to check for the previous use of the same
522       variable between creation of the value and the store. The distances
523       between the creation and the use are small (in most case only 1) as
524       shown by table \ref{tab-3}.
525 \end{itemize}
526
527 Compiling {\tt javac} 29\% of the compile time are spent in parsing and
528 basic block determination, 18\% are spent in stack analysis, 16\% are spent
529 in register allocation and 37\% are spent in machine code generation.
530
531