Mercurial > hg > graal-compiler
view doc/design/graal_compiler.tex @ 2857:c6af2af32b3d
Merge.
author | Thomas Wuerthinger <thomas@wuerthinger.net> |
---|---|
date | Tue, 07 Jun 2011 15:59:08 +0200 |
parents | 3396862d4cee |
children |
line wrap: on
line source
\documentclass[twocolumn]{svjour3} \usepackage{listings} \usepackage[pdftex]{graphicx} \usepackage{environ} \usepackage{amsmath} \usepackage{amsfonts} \usepackage[english]{babel} \usepackage[utf8]{inputenc} \usepackage{lmodern} \usepackage[T1]{fontenc} \usepackage{color} \input{graphdrawing} \renewcommand*\descriptionlabel[1]{\hspace\labelsep\normalfont\bf #1} \newcommand{\Sa}{{\Large$^*$}} \newcommand{\Sb}{{\Large$^\dag$}} \newcommand{\Sc}{{\Large$^\S$}} \newcommand{\mynote}[2]{ \textcolor{red}{\fbox{\bfseries\sffamily\scriptsize#1} {\small\textsf{\emph{#2}}} \fbox{\bfseries\sffamily\scriptsize }}} \newcommand\TODO[1]{\mynote{TODO}{#1}} \newcommand\cw[1]{\mynote{CW}{#1}} \newcommand\ls[1]{\mynote{LS}{#1}} \newcommand\nodename[1]{\texttt{#1}} \smartqed % flush right qed marks, e.g. at end of proof \journalname{Graal Compiler Design} \def\makeheadbox{{% \hbox to0pt{\vbox{\baselineskip=10dd\hrule\hbox to\hsize{\vrule\kern3pt\vbox{\kern3pt \hbox{\bfseries The Graal Compiler - Design and Strategy} \kern3pt}\hfil\kern3pt\vrule}\hrule}% \hss}}} \begin{document} \author{Thomas W\"{u}rthinger \Sa, Lukas Stadler \Sc, Gilles Duboscq \Sa} \institute{\Sa Oracle, \Sc Johannes Kepler University, Linz} \date{Created: \today} \title{The Graal Compiler} \subtitle{Design and Strategy \\ \textcolor{red}{work in progress (Oracle internal)}} \maketitle \abstract{ The Graal compiler (simply referred to as \emph{the compiler} in the rest of this document) aims at improving upon C1X, the Java port of the HotSpot client compiler, both in terms of modularity and peak performance. The compiler should work with the Maxine VM and the HotSpot VM. This document contains information about the proposed design and strategy for developing the compiler.} \section{Context} In 2009, the Maxine team started with creating C1X, a Java port of the HotSpot client compiler, and integrated it into the Maxine VM. Part of this effort was the development of a clear and clean compiler-runtime interface that allows the separation of the compiler and the VM. This compiler-runtime interface enables the use of one compiler for multiple VMs. In June 2010, we started integrating C1X into the HotSpot VM and we called the resulting system Graal~VM. Currently, the Graal~VM is fully functional and runs benchmarks (SciMark, DaCapo) at a similar speed as the HotSpot client compiler. \section{Goals} The compiler effort aims at rewriting the high-level intermediate representation of C1X with two main goals: \begin{description} \item[Modularity:] A modular design of the compiler should simplify the implementation of new languages, new back-ends, and new optimizations. \item[Peak Performance:] A more powerful intermediate representation should enable the implementation of aggressive optimizations that impact the peak performance of the resulting machine code. \end{description} \section{Design} For the implementation of the compiler, we rely on the following design decisions: \begin{description} \item[Graph Representation:] The compiler's intermediate representation is modeled as a graph with nodes that are connected with directed edges. There is only a single node base class and every node has an associated graph object that does not change during the node's lifetime. Every node is serializable and has an id that is unique within its graph. Every edge is classified as either a control flow edge (anti-dependency) or a data flow edge (dependency) and represented as a simple pointer from the source node to the target node. It is possible to replace a node with another node without traversing the full graph. The graph does not allow data flow edge cycles or control flow edge cycles. We achieve this by explicitly modeling loops (see Section~\ref{sec:loops}). \item[Extensibility:] The compiler is extensible by allowing developers to add new compiler phases and new node subclasses without modifying the compiler's sources. A node has an abstract way of expressing its semantics and new compiler phases can ask compiler nodes for their properties and capabilities. We use the ``everything is an extension'' concept. Even standard compiler optimizations are internally modeled as extensions, to show that the extension mechanism exposes all necessary functionality. \item[Detailing:] The compilation starts with a graph that contains nodes that represent the operations of the source language (e.g., one node for an array store to an object array). During the compilation, the nodes are replaced with more detailed nodes (e.g., the array store node is split into a null check, a bounds check, a store check, and a memory access). Compiler phases can choose whether they want to work on the earlier versions of the graph (e.g., escape analysis) or on later versions (e.g., null check elimination). \item[Generality:] The compiler does not require Java as its input. This is achieved by having a graph as the starting point of the compilation and not a Java bytecode array. Building the graph from the Java bytecodes must happen before giving a method to the compiler. This enables front-ends for different languages (e.g., Ruby or JavaScript) to provide their own graph. Also, there is no dependency on a specific back-end, but the output of the compiler is a graph that can then be converted to a different representation in a final compiler phase. \end{description} \section{Milestones} \label{sec:mile} The compiler is being developed starting from the current C1X source code base. This helps us test the compiler at every intermediate development step on a variety of Java benchmarks. We define the following development milestones (see Section~\ref{sec:conclusions} for planned dates): \begin{description} \item[M1:] We have a fully working Graal~VM version with a stripped down C1X compiler that does not perform any optimization. \item[M2:] We modified the high-level intermediate representation to be based on the compiler graph data structure. \item[M3:] We have reimplemented and reenabled compiler optimizations in the compiler that previously existed in C1X. \item[M4:] We have reintegrated the new compiler into the Maxine VM and can use it as a Maxine VM bootstrapping compiler. \end{description} After those four milestones, we see three different possible further development directions that can be followed in parallel: \begin{itemize} \item Removal of the XIR template mechanism and replacement with a snippet mechanism that works with the compiler graph. \item Improvements for peak performance (loop optimizations, escape analysis, bounds check elimination, processing additional interpreter runtime feedback). \item Implementation of a prototype front-end for a different language, e.g., JavaScript. \end{itemize} \section{Project Source Structure} In order to support the goal of a modular compiler, the code will be divided into the following source code projects (as subprojects of \textbf{com.oracle.max.graal}). \begin{description} \item[graph] contains the abstract node implementation, the graph implementation and all the associated tools and auxiliary classes. \item[nodes] contains the implementation of known basic nodes (e.g., phi nodes, control flow nodes, \ldots). Additional node classes should go into separate projects and be specializations of the known basic nodes. \item[java] contains code for building graphs from Java bytecodes and Java-specific nodes. \item[opt] contains optimizations such as global value numbering or conditional constant propagation. \item[compiler] contains the compiler, including: \begin{itemize} \item Scheduling of the compilation phases. \item Implementation of the \emph{compiler interface} (CI). \item Implementation of the final compilation phase that produces the low-level representation. \item Machine code creation, including debug info. \end{itemize} \end{description} \section{Graph} The \emph{intermediate representation}~(IR) of the compiler is designed as a directed graph. The graph allocates unique ids for new nodes and can be queried for the node corresponding to a given id as well as for an unordered list of nodes of the graph. Graphs can manage side data structures (e.g. dominator trees and temporary schedules), which will be automatically invalidated and lazily recomputed whenever the graph changes. These side data structures will usually be understood by more than one optimization. The nodes of the graph have the following properties: \begin{itemize} \item Each node is always associated with a single graph and this association is immutable. \item Each node has an immutable id that is unique within its associated graph. \item Nodes can have a data dependency, which means that one node requires the result of another node as its input. The fact that the result of the first node needs to be computed before the second node can be executed introduces a partial order to the set of nodes. \item Nodes can have a control flow dependency, which means that the execution of one node will be followed by the execution of another node. This includes conditional execution, memory access serialization and other reasons, and again introduces a partial order to the set of nodes. \item Nodes can only have data and control dependencies to nodes which belong to the same graph. \item Control dependencies and data dependencies each represent a \emph{directed acyclic graph} (DAG) on the same set of nodes. This means that data dependencies always point upwards, and control dependencies always point downwards in a drawing of the graph. Situations that normally incur cycles (like loops) are represented by special nodes (see Section~\ref{sec:loops}). \item Ordering between nodes is specified only to the extent which is required to correctly express the semantics of a given program. This gives the compiler flexibility for the possible scheduling of a node and therefore wiggle room for optimizations. For algorithms that require a fixed ordering of nodes, a temporary schedule can always be generated. \item Both data and control dependencies can be traversed in both directions, so that each node can be traversed in four directions (see Figure~\ref{fig:directions}): \begin{itemize} \item \emph{inputs} are all nodes that this node has data dependencies on. \item \emph{usages} are all nodes whose inputs contain this node. \item \emph{successors} are all nodes that have to be after this node in control flow. \item \emph{predecessors} are all nodes whose successors contain this node. \end{itemize} \item Only inputs and successors can be changed, and changes to them will update the usages and predecessors. \item Every node must be able to support cloning and serialization. \item The edges of a node also define \textit{happens-before} and \textit{happens-after} relationships as shown in Figure~\ref{fig:directions}. \end{itemize} \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{graphdirections} \node{node1}{Node} \textnode{inputs}{inputs} \textnode{usages}{usages} \textnode{successors}{successors} \textnode{predecessors}{predecessors} \data{node1}{inputs} \control{node1}{successors} \data{usages}{node1} \control{predecessors}{node1} \node{node2}{Node} \textnode{before}{happens-before} \textnode{after}{happens-after} \data{node2}{before} \control{node2}{after} \data{after}{node2} \control{before}{node2} \end{digraphenv} \caption{A node and its edges.} \label{fig:directions} \end{figure} \subsection{Inlining} Inlining is always performed by embedding one graph into another graph. Nodes cannot be reassigned to another graph, they are cloned instead. Therefore, inlining is performed by copying and rewiring the nodes of the inlined method into the graph of the outer method. While the copying will decrease compilation performance, it enables us to cache the graph for the inlined method, optimize it independently from the outer method, and use the optimized graph for subsequent inlinings. We do not expect a significant negative impact on overall compilation performance. We are able to perform the inlining at any point during the compilation of a method and can therefore selectively expand the inlining if a certain optimization turns out to depend on the inlining of a method. An example for this would be when the escape analysis finds out that a certain object only escapes because of one method call and this method call is not inlined, because the penalty was to high. In this case, we can chose to nevertheless inline the method in order to increase the chances for finding out that the object does not escape. \section{Control Flow} Control flow is managed in way where the predecessor node contains direct pointers to its successor nodes. We reserve the term \textit{instruction} for nodes that are embedded in the control flow. This is opposite to the approach taken in the server compiler, where control flow and data flow edges point in the same direction. The advantage that we see in our approach is that there is no need for projection nodes in case of control flow splits. An \texttt{If} instruction can directly point to its true and false successors without any intermediate nodes. This makes the graph more compact and simplifies graph traversal. Listing~\ref{lst:cfg2} shows an example Java program with an if statement where both paths do not contain any instruction with side effects. The \texttt{If} instruction can directly point its true and false successors to a \texttt{Merge} instruction. A \texttt{Phi} node that selects the appropriate value is appended to the \texttt{Merge} instruction. The \texttt{Return} instruction then has a data dependency on the \texttt{Phi} node. \begin{lstlisting}[label=lst:cfg2, caption=Control flow in the graph., captionpos=b] if (condition) { return 0; } else { return 1; } \end{lstlisting} \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{cfg2} \textnode{entry}{Entry} \textnode{condition}{condition} \textnode{const0}{0} \textnode{const1}{1} \nodesplit{if}{If} \control{entry}{if} \controllabel{if:succ1}{merge} \controllabel{if:succ2}{merge} \data{if}{condition} \node{merge}{Merge} \node{return}{Return} \nodetri{phi}{Phi} \datalabel{phi:in1}{merge} \datalabel{phi:in2}{const0} \datalabel{phi:in3}{const1} \data{return}{phi} \control{merge}{return} \end{digraphenv} \caption{A simple loop with two exits.} \label{fig:exc1} \end{figure} \section{Exceptions} \label{sec:Exceptions} We do not throw runtime exceptions (e.g., \texttt{IndexOutOf\-BoundsException}, \texttt{NullPointerException}, or \texttt{Out\-Of\-MemoryException}), but deoptimize instead. This reduces the places in the compiled code where an exact bytecode location and debug information must be known. Additionally, this greatly reduces the number of exception handler edges in the compiled code. The main advantage of this technique is however, that we are free in moving around bounds checks, memory allocation, memory accesses with implicit null checks, etc. There are only two kinds of instruction that need explicit exception edges, because they are the only instructions that can throw exceptions in compiled code: \texttt{Throw} instructions and \texttt{Invoke} instructions. They are modelled as instructions with an additional control flow continuation that points to an \texttt{ExceptionDispatch} instruction. The exception dispatch instruction decides based on the type of the exception object whether the control should flow to the catch handler or to another exception dispatch. If there is no catch handler in the currently compiled method, then the control flows into the \texttt{Unwind} instruction that handles the exception by forwarding it to the caller. Listing~\ref{lst:exc1} shows an example Java program with nested try blocks and Figure \ref{fig:exc1} shows the corresponding compiler graph. \begin{lstlisting}[label=lst:exc1, caption=Exception dispatch in the compiler graph., captionpos=b] try { m1(); try { m2(); } catch(ExtendedException e) { ... } m3(); throw exception; } catch(Exception e) { ... } \end{lstlisting} \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{exc1} \textnode{entry}{Entry} \textnode{catch1}{catch1} \textnode{catch2}{catch2} \nodesplit{m1}{Invoke m1} \nodesplit{m2}{Invoke m2} \nodesplit{m3}{Invoke m3} \nodesplit{dispatch1}{ExceptionDispatch} \nodesplit{dispatch2}{ExceptionDispatch} \node{throw}{Throw} \node{unwind}{Unwind} \control{entry}{m1} \controllabel{m1:succ1}{m2} \controllabel{m1:succ2}{dispatch2} \controllabel{m2:succ1}{m3} \controllabel{m2:succ2}{dispatch1} \controllabel{m3:succ1}{throw} \controllabel{m3:succ2}{dispatch2} \control{throw}{dispatch2} \controllabel{dispatch1:succ2}{catch1} \controllabel{dispatch1:succ1}{dispatch2} \controllabel{dispatch2:succ2}{catch2} \controllabel{dispatch2:succ1}{unwind} \end{digraphenv} \caption{A simple loop with two exits.} \label{fig:exc1} \end{figure} \section{Loops} \label{sec:loops} Loops form a first-class construct in the IR that is expressed by specialized IR nodes during all optimization phases. We only compile methods with a control flow where every loop has a single entry point. This entry point is a \nodename{LoopBegin} instruction. This instruction is connected to a \nodename{LoopEnd} instruction that merges all control flow paths that do not exit the loop. The edge between the \nodename{LoopBegin} and the \nodename{LoopEnd} is the backedge of the loop. It goes from the beginning to the end in order to make the graph acyclic. An algorithm that traverses the control flow has to explicitely decide whether it wants to incorporate backedges (i.e., special case of the treatment of \nodename{LoopEnd}) or ignore them. Figure \ref{fig:loop1} shows a simple example with a loop with a single entry and two exits. \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{layout1} \textnode{BeforeLoop}{Loop entry} \textnode{Exit1}{First loop exit} \textnode{Exit2}{Second loop exit} \nodesplit{LoopBegin}{LoopBegin} \node{LoopEnd}{LoopEnd} \nodesplit{If1}{If} \nodesplit{If2}{If} \controllabel{LoopBegin:succ1}{LoopEnd} \controllabel{LoopBegin:succ2}{If1} \controllabel{If1:succ1}{If2} \controllabel{If2:succ1}{LoopEnd} \controllabel{BeforeLoop}{LoopBegin} \controllabel{If1:succ2}{Exit1} \controllabel{If2:succ2}{Exit2} \end{digraphenv} \caption{A simple loop with two exits.} \label{fig:loop1} \end{figure} \subsection{Loop Phis} Data flow in loops is modeled with special phi nodes at the beginning and the end of the loop. The \nodename{LoopEnd} instruction merges every value that flows into the next loop iteration in associated \nodename{LoopEndPhi} nodes. A corresponding \nodename{LoopBeginPhi} node that is associated with the loop header has a control flow dependency on the \nodename{LoopEndPhi} node. Listing~\ref{lst:loop} shows a simple counting loop that is used as an example in the rest of this section. Figure~\ref{fig:loop2} shows how the loop is modelled immediately after building the graph. \begin{lstlisting}[label=lst:loop, caption=Loop example that counts from 0 to n-1., captionpos=b] for(int i=0; i<n; ++i) { } \end{lstlisting} \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{layout2} \textnode{BeforeLoop}{Loop entry} \textnode{Exit}{Loop exit} \textnode{n}{n} \textnode{Constant0}{0} \textnode{Constant1}{1} \nodesplit{LoopBegin}{LoopBegin} \node{LoopEnd}{LoopEnd} \nodesplit{If1}{If} \controllabel{LoopBegin:succ1}{LoopEnd} \controllabel{LoopBegin:succ2}{If1} \nodebi{Compare}{<} \nodebi{LoopBeginPhi}{LoopBeginPhi} \nodebi{Add}{+} \datalabel{Add:in1}{LoopBeginPhi} \datalabel{Add:in2}{Constant1} \nodebi{LoopEndPhi}{LoopEndPhi} \control{LoopBeginPhi}{LoopEndPhi} \data{LoopEndPhi:in1}{LoopEnd} \data{LoopEndPhi:in2}{Add} \datalabel{LoopBeginPhi:in1}{LoopBegin} \datalabel{LoopBeginPhi:in2}{Constant0} \datalabel{Compare:in1}{LoopBeginPhi} \datalabel{Compare:in2}{n} \data{If1}{Compare} \controllabel{If1:succ1}{LoopEnd} \controllabel{BeforeLoop}{LoopBegin} \controllabel{If1:succ2}{Exit} \end{digraphenv} \caption{Graph for a loop counting from 0 to n-1.} \label{fig:loop2} \end{figure} \subsection{Loop Counters} The compiler is capable of recognizing variables that are only increased within a loop. A potential overflow of such a variable is prohibited with a guard before the loop (this is not necessary in this example, because the loop variable cannot overflow). Figure \ref{fig:loop3} shows the compiler graph of the example loop after the loop counter transformation. \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{layout3} \textnode{BeforeLoop}{Loop entry} \textnode{Exit}{Loop exit} \textnode{n}{n} \textnode{Constant0}{0} \textnode{Constant1}{1} \nodesplit{LoopBegin}{LoopBegin} \node{LoopEnd}{LoopEnd} \nodesplit{If1}{If} \controllabel{LoopBegin:succ1}{LoopEnd} \controllabel{LoopBegin:succ2}{If1} \nodebi{Compare}{<} \nodetri{LoopCounter}{LoopCounter} \datalabel{LoopCounter:in1}{LoopBegin} \datalabeltext{LoopCounter:in2}{Constant0}{init} \datalabeltext{LoopCounter:in3}{Constant1}{stride} \datalabel{Compare:in1}{LoopCounter} \datalabel{Compare:in2}{n} \data{If1}{Compare} \controllabel{If1:succ1}{LoopEnd} \controllabel{BeforeLoop}{LoopBegin} \controllabel{If1:succ2}{Exit} \end{digraphenv} \caption{Graph after loop counter transformation.} \label{fig:loop3} \end{figure} \subsection{Bounded Loops} If the total maximum number of iterations of a loop is fixed, then the loop is converted into a bounded loop. The total number of iterations always denotes the number of full iterations of the loop with the control flowing from the loop begin to the loop end. If the total number of iterations is reached, the loop is exited directly from the loop header. In the example, we can infer from the loop exit with the comparison on the loop counter that the total number of iterations of the loop is limited to n. Figure \ref{fig:loop4} shows the compiler graph of the example loop after the bounded loop transformation. \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{layout4} \textnode{BeforeLoop}{Loop entry} \textnode{Exit}{Loop exit} \textnode{n}{n} \textnode{Constant0}{0} \textnode{Constant1}{1} \nodesplittri{LoopBegin}{BoundedLoopBegin} \node{LoopEnd}{LoopEnd} \controllabel{LoopBegin:succ1}{LoopEnd} \controllabel{LoopBegin:succ2}{LoopEnd} \controllabel{LoopBegin:succ3}{Exit} \nodetri{LoopCounter}{LoopCounter} \datalabel{LoopCounter:in1}{LoopBegin} \datalabeltext{LoopCounter:in2}{Constant0}{init} \datalabeltext{LoopCounter:in3}{Constant1}{stride} \data{LoopBegin}{n} \controllabel{BeforeLoop}{LoopBegin} \end{digraphenv} \caption{Graph after bounded loop transformation.} \label{fig:loop4} \end{figure} \subsection{Vectorization} If we have now a bounded loop with no additional loop exit and no associated phi nodes (only associated loop counters), we can vectorize the loop. We replace the loop header with a normal instruction that produces a vector of values from 0 to the number of loop iterations minus 1. The loop counters are replaced with \texttt{VectorAdd} and \texttt{VectorMul} nodes. The vectorization is only possible if every node of the loop can be replaced with a corresponding vector node. Figure \ref{fig:loop5} shows the compiler graph of the example loop after vectorization. The vector nodes all work on an ordered list of integer values and are subject to canonicalization and global value numbering like any other node. \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{layout5} \textnode{Entry}{Entry} \textnode{Exit}{Exit} \textnode{n}{n} \textnode{Constant0}{0} \textnode{Constant1}{1} \node{Vector}{Vector} \nodebi{VectorAdd}{VectorAdd} \nodebi{VectorMul}{VectorMul} \control{Entry}{Vector} \control{Vector}{Exit} \datalabel{VectorAdd:in1}{Vector} \datalabel{VectorAdd:in2}{Constant0} \datalabel{VectorMul:in1}{VectorAdd} \datalabel{VectorMul:in2}{Constant1} \data{Vector}{n} \end{digraphenv} \caption{Graph after vectorization.} \label{fig:loop5} \end{figure} \section{Frame States} A frame state captures the state of the program like it is seen in by an interpreter of the program. The frame state contains the information that is local to the current activation and will therefore disappear during SSA-form constructions or other compiler optimizations. For Java, the frame state is defined in terms of the Java bytecode specification (i.e., the values of the local variables, the operand stack, and the locked monitors). However, a frame state is not a concept specific to Java (e.g., the Crankshaft JavaScript engine uses frame states in their optimizing compiler to model the values of the AST interpreter). Frame states are necessary to support the deoptimization of the program, which is the precondition for performing aggressive optimizations that use optimistic assumptions. Therefore every point in the optimizing compiler that may revert execution back to the interpreter needs a valid frame state. However, the point where the interpreter continues execution need not correspond exactly to the execution position of the compiled code, because many Java bytecode instructions can be safely reexecuted. Thus, frame states need only be generated for the states after instructions that cannot be reexecuted, because they modify the state of the program. Examples for such instructions are: \begin{itemize} \item Array stores (in Java bytecodes {\tt IASTORE, LASTORE, FASTORE, \\DASTORE, AASTORE, BASTORE, CASTORE, SASTORE}) \item Field stores (in Java bytecodes {\tt PUTSTATIC, PUTFIELD}) \item Method calls (in Java bytecodes {\tt INVOKEVIRTUAL, INVOKESPECIAL, \\INVOKESTATIC, INVOKEINTERFACE}) \item Synchronization (in Java bytecodes {\tt MONITORENTER, MONITOREXIT}) \end{itemize} Within the graph a frame state is represented as a node that is attached to the instruction that caused it to be generated using a control dependency (see Figure~\ref{fig:fs1}). Frame states also have data dependencies on the contents of the state: the local variables and the expression stack. The frame state at the method beginning does not have to be explicitely in the graph, because it can always be reconstructed at a later stage. We save the frame state at control flow merges if there is at least one frame state on any control flow path between a node and its immediate dominator. \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{fs1} \nodetrisplit{store1}{ArrayStore} \nodebi{load1}{ArrayLoad} \controllabel{store1:succ1}{load1} \nodetrisplit{store2}{FieldStore} \control{load1}{store2} end [shape=plaintext, label="...", width="2.0"] store2:succ1:s -> end:n [color=red]; % \nodeframestate{fs1}{FrameState} \controllabel{store1:succ2}{fs1} \nodeframestate{fs2}{FrameState} \controllabel{store2:succ2}{fs2} \end{digraphenv} \caption{Simple example using two frame states.} \label{fig:fs1} \end{figure} A deoptimization node needs a valid frame state that specifies the location and state where the interpreter should continue. The algorithm for constructing frame states makes sure that every possible location in the graph has a well-defined frame state that can be used by a deoptimization instruction. Therefore, there are no direct links between the deoptimization instruction and its frame state thus allowing the deoptimization instructions to move freely around. \subsection{Partial Escape Analysis} A partial escape analysis can help to further reduce the number of frame states. A field or array store does not create a new frame state, when the object that is modified did not have a chance to escape between its creation and the store. Listing~\ref{lst:escape1} shows an example of a method that creates two \texttt{Point} objects, connects them, and returns them. The object allocation of the first \texttt{Point} object does not need a frame state. We can always reexecute the \texttt{NEW} bytecode again in the interpreter. The \texttt{Point} object allocated by the compiler will then simply disappear after the next garbage collection. The following field store is a thread-local memory store, because the \texttt{Point} object did not have any chance to escape. Same applies to the assignment of the \texttt{next} field and the third field assignment. Therefore, the whole method \texttt{getPoint} does not need an explicit frame state, because at any time during execution of this method, we can deoptimize and continue execution in the interpreter at the first bytecode of the method. \begin{lstlisting}[label=lst:escape1, caption=Example method that needs no frame state., captionpos=b] void getPoint() { Point p = new Point(); p.x = 1; p.next = new Point(); p.next.x = 2; return p; } \end{lstlisting} The reduction of frame states makes it easier for the compiler to perform memory optimizations like memory access coalescing. We believe that this reduction on frame states is the key to effective vectorization and other compiler optimizations where compilers of compilers of unmanaged languages have advantages. \subsection{Guards} A guard is a node that deoptimizes based on a conditional expression. Guards are not attached to a certain frame state, they can move around freely and will always use the correct frame state when the nodes are scheduled (i.e., the last emitted frame state). The node that is guarded by the deoptimization has a data dependency on the guard and the guard in turn has a data dependency on the condition. A guard must not be moved above any \texttt{If} nodes. Therefore, we use \texttt{Anchor} instructions after a control flow split and a data dependency from the guard to this anchor. The anchor is the most distant instruction that is postdominated by the guarded instruction and the guard can be scheduled anywhere between those two nodes. This ensures maximum flexibility for the guard instruction and guarantees that we only deoptimize if the control flow would have reached the guarded instruction (without taking exceptions into account). To illustrate the strengths of this approach, we show the graph for the Java code snippet shown in \ref{lst:guard1}. The example looks artificial, but in case of method inlining, this is a pattern that is not unlikely to be present in a normal Java program. Figure \ref{fig:guard0} shows the compiler graph for the example method after graph building. The field stores are both represented by a single instruction and the null check that is implicitely incorporated in the field store. \begin{lstlisting}[label=lst:guard1, caption=Example method that demonstrates the strengths of modelling the guards explicitely., captionpos=b] void init(Point p) { if (p != null) { p.x = 0; } p.y = 0; } \end{lstlisting} \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{guard0} \textnode{entry}{Entry} \nodesplit{if}{If} \node{merge}{Merge} \node{return}{Return} \node{cmpnull}{NonNull} \textnode{p}{p} \textnode{const0}{0} \nodebisplit{store1}{FieldStore x} \nodebisplit{store2}{FieldStore y} \nodeframestate{fs1}{FrameState} \nodeframestate{fs2}{FrameState} \datalabel{store1:in1}{p} \datalabel{store2:in1}{p} \datalabel{store1:in2}{const0} \datalabel{store2:in2}{const0} \control{entry}{if} \data{if}{cmpnull} \controllabel{if:succ1}{merge} \controllabel{if:succ2}{store1} \controllabel{store1:succ1}{merge} \controllabel{store1:succ2}{fs1} \control{merge}{store2} \controllabel{store2:succ1}{return} \controllabel{store2:succ2}{fs2} \data{cmpnull}{p} \end{digraphenv} \caption{Initial graph with the two field stores.} \label{fig:guard0} \end{figure} Figure~\ref{fig:guard1} shows the example graph at a later compilation phase when the field store instructions are lowered to memory store instructions and explicitely modelled null check guards. The guards are attached to anchor instructions that delimit their possible schedule. The first guard must not be moved outside the \texttt{if} block; the second guard may be moved before the \texttt{If} instruction, because at this point it is already guaranteed that the second store is executed. \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{guard1} \textnode{entry}{Entry} \node{anchor1}{Anchor} \node{anchor2}{Anchor} \nodesplit{if}{If} \node{merge}{Merge} \node{return}{Return} \node{cmpnull}{NonNull} \textnode{p}{p} \textnode{const0}{0} \nodeguard{guard1}{Guard} \nodeguard{guard2}{Guard} \nodetrisplit{store1}{MemStore 16 (int)} \nodetrisplit{store2}{MemStore 20 (int)} \nodeframestate{fs1}{FrameState} \nodeframestate{fs2}{FrameState} \data{store1:in1}{p} \data{store2:in1}{p} \data{store1:in2}{const0} \data{store2:in2}{const0} \data{store1:in3}{guard1} \data{store2:in3}{guard2} \data{guard1:in1}{anchor2} \data{guard2:in1}{anchor1} \data{guard1:in2}{cmpnull} \data{guard2:in2}{cmpnull} \control{entry}{anchor1} \control{anchor1}{if} \data{if}{cmpnull} \controllabel{if:succ1}{merge} \controllabel{if:succ2}{anchor2} \control{anchor2}{store1} \controllabel{store1:succ1}{merge} \controllabel{store1:succ2}{fs1} \control{merge}{store2} \controllabel{store2:succ1}{return} \controllabel{store2:succ2}{fs2} \data{cmpnull}{p} \end{digraphenv} \caption{A load guarded by a null check guard.} \label{fig:guard1} \end{figure} The first guard can be easily removed, because it is guarded by an \texttt{If} instruction that checks the same condition. Therefore we can remove the guard and the anchor from the graph and this gives us the graph shown in Figure \ref{fig:guard2}. There is another optimization for guard instructions: If two guards that are anchored to the true and false branch of the same \texttt{If} instruction have the same condition, they can be merged, so that the resulting guard is anchored at the most distant node of which the \texttt{If} instruction is a postdominator. \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{guard2} \textnode{entry}{Entry} \node{anchor1}{Anchor} \nodesplit{if}{If} \node{merge}{Merge} \node{return}{Return} \node{cmpnull}{NonNull} \textnode{p}{p} \textnode{const0}{0} \nodeguard{guard2}{Guard} \nodetrisplit{store1}{MemStore 16 (int)} \nodetrisplit{store2}{MemStore 20 (int)} \nodeframestate{fs1}{FrameState} \nodeframestate{fs2}{FrameState} \data{store1:in1}{p} \data{store2:in1}{p} \data{store1:in2}{const0} \data{store2:in2}{const0} \data{store2:in3}{guard2} \data{guard2:in1}{anchor1} \data{guard2:in2}{cmpnull} \control{entry}{anchor1} \control{anchor1}{if} \data{if}{cmpnull} \controllabel{if:succ1}{merge} \controllabel{if:succ2}{store1} \controllabel{store1:succ1}{merge} \controllabel{store1:succ2}{fs1} \control{merge}{store2} \controllabel{store2:succ1}{return} \controllabel{store2:succ2}{fs2} \data{cmpnull}{p} \end{digraphenv} \caption{After removing redundant guards.} \label{fig:guard2} \end{figure} The remaining guard can now be moved above the \texttt{If} condition and be used to eliminate the need for the \texttt{If} node. From this point on, the guard can however no longer be moved below the first memory store. We use a control dependency from the guard to the field store to express this condition. The link between the second store and the guard and the control flow merge instruction is no longer necessary. \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{guard3} \textnode{entry}{Entry} \node{anchor1}{Anchor} \node{return}{Return} \node{cmpnull}{NonNull} \textnode{p}{p} \textnode{const0}{0} \nodeguard{guard2}{Guard} \nodetrisplit{store1}{MemStore 16 (int)} \nodetrisplit{store2}{MemStore 20 (int)} \nodeframestate{fs1}{FrameState} \nodeframestate{fs2}{FrameState} \data{store1:in1}{p} \data{store2:in1}{p} \data{store1:in2}{const0} \data{store2:in2}{const0} \data{store2:in3}{guard2} \data{guard2:in1}{anchor1} \data{guard2:in2}{cmpnull} \control{guard2}{store1} \control{entry}{anchor1} \control{anchor1}{store1} \controllabel{store1:succ2}{fs1} \control{store1}{store2} \controllabel{store2:succ1}{return} \controllabel{store2:succ2}{fs2} \data{cmpnull}{p} \end{digraphenv} \caption{After eliminating an if with a guard.} \label{fig:guard3} \end{figure} At some point during the compilation, guards need to be fixed, which means that appropriate data and control dependencies will be inserted so that they cannot move outside the scope of the associated frame state. This will generate deoptimization-free zones that can be targeted by the most aggressive optimizations. A simple algorithm for this removal of frame states would be to move all guards as far upwards as possible and then the guards are fixed using anchor nodes. In our example, the guard is already fixed, so there is no deoptimization point that uses any of the memory store frame states. Therefore we can delete the frame states from the graph (see Figure \ref{fig:guard4}). \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{guard4} \textnode{entry}{Entry} \node{anchor1}{Anchor} \node{return}{Return} \node{cmpnull}{NonNull} \textnode{p}{p} \textnode{const0}{0} \nodeguard{guard2}{Guard} \nodetrisplit{store1}{MemStore 16 (int)} \nodetrisplit{store2}{MemStore 20 (int)} \data{store1:in1}{p} \data{store2:in1}{p} \data{store1:in2}{const0} \data{store2:in2}{const0} \data{store2:in3}{guard2} \data{guard2:in1}{anchor1} \data{guard2:in2}{cmpnull} \control{guard2}{store1} \control{entry}{anchor1} \control{anchor1}{store1} \control{store1}{store2} \controllabel{store2:succ1}{return} \data{cmpnull}{p} \end{digraphenv} \caption{After removing the frame states.} \label{fig:guard4} \end{figure} Now we can use memory coalescing to combine the two stores without frame state to adjacent locations in the same object. This is only possible if the first store does not have a frame state. Figure \ref{fig:guard5} shows the resulting graph. \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{guard5} \textnode{entry}{Entry} \node{anchor1}{Anchor} \node{return}{Return} \node{cmpnull}{NonNull} \textnode{p}{p} \textnode{const0}{0} \nodeguard{guard2}{Guard} \nodetrisplit{store1}{MemStore 16 (long)} \data{store1:in1}{p} \data{store1:in2}{const0} \data{guard2:in1}{anchor1} \data{guard2:in2}{cmpnull} \control{guard2}{store1} \control{entry}{anchor1} \control{anchor1}{store1} \controllabel{store1:succ1}{return} \data{cmpnull}{p} \end{digraphenv} \caption{After coalescing the two memory stores.} \label{fig:guard5} \end{figure} A memory store that immediately follows a null check guard instruction on the same object, can be combined into a store with an implicit null check (that deoptimizes instead of throwing the exception). Therefore, we can remove the guard again and also the anchor is no longer necessary. Figure~\ref{fig:guard6} shows now that fully optimized graph that is generated for Listing~\ref{lst:guard1}. \begin{figure}[h] \centering \begin{digraphenv}{scale=0.5}{guard6} \textnode{entry}{Entry} \node{return}{Return} \textnode{p}{p} \textnode{const0}{0} \nodetrisplit{store1}{DeoptimizingMemStore 16 (long)} \data{store1:in1}{p} \data{store1:in2}{const0} \control{entry}{store1} \controllabel{store1:succ1}{return} \end{digraphenv} \caption{Fully optimized method.} \label{fig:guard6} \end{figure} \section{Conclusions} \label{sec:conclusions} This document sketched the strategy for the Graph compiler. We already reached M1 (as defined in Section~\ref{sec:mile}) and have the following plans for M2 to M4: \begin{description} \item[M2:] June 30th, 2011 \item[M3:] August 15th, 2011 \item[M4:] September 30th, 2011 \end{description} After we reach M4, we want to create a new project road map that further improves the Graal compiler with respect to its two main goals: Modularity and peak performance. \end{document}