Skip to content
ImagineWorld

Runtime Optimization

node_idnode-book_engineering-a-compiler_chapter-14-runtime-optimization
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num14
chapter_titleRuntime Optimization
pillar_membershipF — compiler_trinity
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Runtime optimization has become an important technique for the implementation of many programming languages. The move from ahead-of-time compilation to runtime optimization lets the language runtime and its compilers capitalize on facts that are not known until runtime. If these facts enable specialization of the code, such as folding an invariant value, avoiding type conversion code, or replacing a virtual function call with a direct call, then the profit from use of runtime information can be substantial.

This chapter explores the major issues that arise in the design and implementation of a runtime optimizer. It describes the workings of a hot-trace optimizer and a method-level optimizer; both are inspired by successful real systems. The chapter lays out some of the tradeoffs that arise in the design and implementation of these systems.

Runtime Compilation, Just-in-Time Compilation, Dynamic Optimization

Many programming languages include features that make it difficult to produce high-quality code at compile time. These features include late binding, dynamic loading of both declarations and code (classes in JAVA), and various kinds of polymorphism. A classic compiler, sometimes called an ahead-of-time compiler (AOT), can generate code for these features. In many cases, however, it does not have sufficient knowledge to optimize the code well. Thus, the AOT compiler must emit the generic code that will work in any situation, rather than the tailored code that it might generate with more precise information.

For some problems, the necessary information might be available at link time, or at class-load time in JAVA. For others, the information may not be known until runtime. In a language where such late-breaking information can have a significant performance impact, the system can defer optimization or translation until it has enough knowledge to produce efficient code.

Runtime optimization code optimization applied at runtime

Compiler writers have applied this strategy, runtime optimization or just-in-time compilation (JIT), in a variety of contexts, ranging from early LISP systems through modern scripting languages. It has been used to build regular-expression search facilities and fast instruction-set emulators. This chapter describes the technical challenges that arise in runtime optimization and runtime translation, and shows how successful systems have addressed some of those problems.

Just-in-time compilers are, undoubtedly, the most heavily used compilers that the computer science community has built. Most web browsers include JITs for the scripting languages used in web sites. Runtime systems for languages such as JAVA routinely include a JIT that compiles the heavily used code. Because these systems compile the code every time it runs, they perform many more compilations than a traditional AOT compiler.

Conceptual Roadmap

Classic AOT compilers make all of their decisions based on the facts that they can derive from the source text of the program. Such compilers can generate highly efficient code for imperative languages with declarations. However, some languages include features that make it impossible for the compiler to know important facts until runtime. Such features include dynamic typing, some kinds of polymorphism, and an open class structure.

Runtime optimization involves a fundamental tradeoff between time spent compiling and code quality. The runtime optimizer examines the program’s state to derive more precise information; it then uses that knowledge to specialize the executable code. Thus, to be effective, the runtime optimizer must derive useful information. It must improve runtime performance enough to compensate for the added costs of optimization and code generation. The compiler writer, therefore, has a strong incentive to use methods that are efficient, effective, and broadly applicable.

A Few Words About Time

Runtime optimization adds a new layer of complexity to our reasoning about time. These techniques intermix compile time with runtime and incur compile-time costs every time a program executes.

At a conceptual level, the distinction between compile time and runtime remains. The runtime optimizer plans runtime behavior and runtime data structures, just as an AOT compiler would. It emits code to create and maintain the runtime environment. Thus, JIT-time activities are distinct from runtime activities. All of the reasoning about time from earlier chapters is relevant, even if the time frame when the activities occur has shifted.

JIT time We refer to the time when the runtime optimizer or the just-in-time compiler is, itself, executing as JIT time. To further complicate matters, some systems that use runtime optimization rely on an interpreter for their default execution mode. These systems interpret code until they discover a segment of code that should be compiled. At that point they compile and optimize the code; they then arrange for subsequent executions to use the compiled code for the segment. Such systems intermix interpretation, JIT compilation, and execution of compiled code.

To implement efficiently features such as late binding of names to types or classes, dynamic loading and linking of code, and polymorphism, compiler writers have turned to runtime optimization. A runtime optimizer can inspect the running program’s state to discover information that was obscured or unavailable before runtime.

By runtime, the system mostly knows what code is included in the executable. Late bound names have been resolved. Data structures have been allocated, so their sizes are known. Objects have been instantiated, with full class information. Using facts from the program’s runtime state, a compiler can specialize the code in ways that are not available to an AOT compiler.

Runtime compilation has a long history. McCarthy’s early LISP systems compiled native code for new functions at runtime. Thompson’s construction, which builds an NFA from a regular expression, was invented to compile an RE into native code inside the search command for the QED editor—one of the first well-known examples of a compiler that executed at runtime. Subsequent systems used these techniques for purposes that ranged from the implementation of dynamic object-oriented languages such as SMALLTALK-80 through code emulation for portability. The rise of the World Wide Web was, in part, predicated on widespread use of JAVA and JAVASCRIPT, both of which rely on runtime compilation for efficiency.

Runtime optimization presents the compiler writer with a novel set of challenges and opportunities. Time spent in the compiler increases the overall running time, so the JIT writer must balance JIT costs against expected improvement. Techniques that shift compilation away from infrequently executed, or cold, code and toward frequently executed, or hot, code can magnify any gain from optimization.

We use the term JIT to cover all runtime optimizers, whether their input is source code, as in McCarthy’s early LISP systems; some high-level notation, as in Thompson’s RE-to-native-code compiler; some intermediate form as in JAVA systems; or even native code, as in Dynamo. The digressions throughout this chapter will introduce some of these systems, to familiarize the reader with the long history and varied applications of these ideas.

A “segment” might be a block, a trace, a method, or multiple procedures.

(a) Full Data Set

(b) Expanded View of Small Data Sets

■ FIGURE 14.1 Scalability of a JAVA Application.

The data was gathered on OpenJDK version 1.8.0_292 running on an Intel ES2640 at 2.4GHz.

The input codes had uniform register pressure of 20 values. The allocator was allotted 15 registers.

These numbers are specific to this single application. Your experience will vary.

JIT compilation can make a significant difference in the execution speed of an application. As a concrete example, Fig. 14.1 shows the running times of a JAVA implementation of the local register allocation algorithm from Section 13.3. Panel(a) shows the running time of the allocator on a series of blocks with 1,000 lines, 2,000 lines, 4,000 lines, and so on up to 128,000 lines of ILOC code. The gray line with square data points shows the running time with the JIT disabled; the black line with triangular data points shows the running time with the JIT enabled. Panel(b) zooms in on the startup behavior-that is, the smaller data sets.

The JIT makes a factor of six difference on the largest data set; it more than compensates for the time spent in the JIT. Panel(a) shows the JIT’s contribution to the code’s performance. Panel(b) shows that VM-code emulation is actually faster on small data sets. Time spent in the JIT slows execution in the early stages of runtime; after roughly one-half second, the speed advantage of the compiled code outweighs the costs incurred by the JIT.

JIT design involves fundamental tradeoffs between the amount of work performed ahead of time, the amount of work performed in the JIT, and the improvement that JIT compilation achieves. As languages, architectures, and runtime techniques have changed, these tradeoffs have shifted. These tradeoffs will continue to shift and evolve as the community’s experience with building and deploying JITs grows. Our techniques and our understanding will almost certainly improve, but the fundamental tradeoff of efficiency against effectiveness will remain. This chapter provides a snapshot of the state of the field at the time of publication. Section 14.2 describes four major issues that play important roles in shaping the structure of a JIT-enabled system. The next two sections present high-level sketches for two JITs that sit at different points in the design space. Section 14.3 describes a hot-trace optimizer while Section 14.4 describes a hot-method optimizer; both designs are modeled after successful systems. The Advanced Topics section explores several other issues that arise in the design and construction of practical JIT-based systems.

Runtime optimization has emerged as a technology that lets the runtime system adapt the executable code more closely to the context in which it executes. In particular, by deferring optimization until the compiler has more complete knowledge about types, constant values, and runtime behavior (e.g., profile information), a JIT compiler can eliminate some of the overhead introduced by language features such as object-orientation, dynamic typing, and late binding.

Success in runtime optimization, however, requires attention to both the efficiency and the effectiveness of the JIT. The fundamental principle of runtime optimization is

A runtime compiler must save more cycles than it uses.

If the runtime compiler fails to meet this constraint, then it actually slows down the application’s execution.

This critical constraint shapes both the JIT and the runtime system with which it interacts. It places a premium on efficiency in the compiler itself. Because compile time now adds to running time, the JIT implementation’s efficiency directly affects the application’s running time. Both the scope and ambition of the JIT matter; both asymptotic complexity and actual runtime overhead matter. Equally important, the scheme that chooses which code segments to optimize has a direct impact on the total cost of running an application.

This constraint also places a premium on the effectiveness of each algorithm that the JIT employs. The compiler writer must focus on techniques that are both widely applicable and routinely profitable. The JIT should apply those techniques to regions where opportunities are likely and where those improvements pay off well. A successful JIT improves the code’s running time often enough that the end users view time spent in the JIT as worthwhile.

REGULAR EXPRESSION SEARCH IN THE QED EDITOR

Section titled “REGULAR EXPRESSION SEARCH IN THE QED EDITOR”

Ken Thompson built a regular-expression (RE) search facility into the QED editor in the late 1960s. This search command was an early JIT compiler, invoked under the user’s direction. When the user entered an RE; the editor invoked the JIT to create native code for the IBM 7094. The editor then invoked the native code to perform the search. After the search, it discarded the code.

The JIT was a compiler. It first parsed the RE to check its syntax. Next, it converted the RE to a postfix notation. Finally, it generated native code to perform the search. The JIT’s code generator used the method now known as Thompson’s construction to build, implicitly, an NFA (see Section 2.4.2). The generated code simulated that NFA. It used search to avoid introducing duplicate terms that would cause exponential growth in the runtime state.

The QED search command added a powerful capability to a text editor that ran on a 0.35 MIP processor with 32 KB of RAM. This early use of JIT technology created a responsive tool that ran in this extremely constrained environment.

This situation differs from that which occurs in an AOT compiler. Compiler writers assume that the code produced by an AOT compiler executes, on average, many times per compilation. Thus, the cost of optimization is a small concern. AOT compilers apply a variety of transformations that range from broadly applicable methods such as value numbering to highly specific ones such as strength reduction. They employ techniques that produce many small improvements and others that produce a few large improvements. An AOT compiler wins by accumulating the improvements from a suite of optimizations, used at every applicable point in the code. The end user is largely insulated from the cost of compilation and optimization.

To recap, the constraints in a JIT mean that the JIT writer must choose transformations well, implement them carefully, and apply them to regions that execute frequently. Fig. 14.1 demonstrates the improvement from JIT compilation with the HotSpot Server Compiler. In that test, HotSpot produced significant improvements for codes that ran for more than one-half of a second. Careful attention to both costs and benefits allows this JIT to play a critical role in JAVA’s runtime performance.

The choice of an execution model has a large impact on the shape of a runtime optimization system. It affects the speed of baseline execution. It affects the amount of compilation that the system must perform and, therefore, the cumulative overhead of optimization. It also affects the complexity of the implementation.

A runtime optimization system can be complex. It takes, as input, code for some virtual machine(VM) code. The VM code might be code for an abstract machine such as the JAVA VM(JVM) or the Smalltalk-80 VM. In other systems, the VM code is native machine code. As output, the runtime optimizer produces the results of program execution.

The runtime system can produce results by executing native code, by interpreting VM code, or by JIT compiling VM code to native code and running it. The relationship between the JIT, the code, and the rest of the runtime system determines the mode of execution. Does the system execute, by default, native code or VM code? Either option has strengths and weaknesses.

native-code execution usually implies JIT compilation before execution, unless the VM code is native code.

VM-code execution usually implies interpretation at some level. The code is compact; it can be more abstract than native code.

Native-code execution is, almost always, faster than VM-code execution. Native code relies on hardware to implement the fetch-decode-execute cycle, while VM emulation implements those functions in software. Lower cost per operation turns into a significant performance advantage for any nontrivial execution.

On the other hand, VM-code systems may have lower startup costs, since the system does not need to compile anything before it starts to execute the application. This leads to faster execution for short-running programs, as shown in Fig. 14.1(b). For procedures that are short or rarely executed,VM-code emulation may cost less than JIT compilation plus native-code execution.

The introduction of a JIT to a VM-code system typically creates a mixed-mode platform that executes both VM code and native code. A mixed-mode system may need to represent critical data structures, such as activation records, in both the format specified for the VM and the format supported by the native ISA. The dual representations may introduce translation between VM-code structures and native-code structures; those translations, in turn, will incur runtime costs.

The difference between these modes is largely transparent to the user.

A VM-code system can defer scanning and parsing a procedure until it is called. The savings in startup time can be substantial.

The Deutsch-Schiffman SMALLTALK-80 system used three formats for an AR.It translated between formats based on whether or not the code accessed the AR as data.

Adaptive Fortran was a runtime optimizer for FORTRAN IV built by Hansen as part of the work for his 1974 dissertation. He used it to explore both the practicality and the profitability of runtime optimization. Adaptive Fortran introduced many ideas that are found in modern systems.

The system used a fast ahead-of-time compiler to produce an IR version of the program; the IR was grouped into basic blocks. At runtime, the IR was interpreted until block execution counts indicated that the block could benefit from optimization. (The AOT compiler produced block-specific, optimization-specific thresholds based on block length, nesting depth, and the cost of the JIT optimization.)

Guided by the execution counts and thresholds, a supervisor invoked a JIT to optimize blocks and their surrounding context. The use of multiple block-specific thresholds led to an effect of progressive optimization—more optimizations were applied to blocks that accounted for a larger share of the running time.

One key optimization, which Hansen called fusion, aggregated together multiple blocks to group loops and loop nests into segments. This strategy allowed Adaptive Fortran to apply loop-based optimizations such as code motion.

The alternative, native-code execution, distributes the costs in a different way. Such a system must compile all VM code to native code, either in an AOT compilation or at runtime. The AOT solution leads to fully general code and, thus, a higher price for nonoptimized native execution. The JIT solution leads to a system that performs more runtime compilation and incurs those costs on each execution.

There is no single best solution to these design questions. Instead, the compiler writer must weigh carefully a variety of tradeoffs and must implement the system with an eye toward both efficiency and effectiveness. Successful systems have been built at several points in this design space.

The runtime system must decide when and where to invoke the JIT. This decision has a strong effect on overall performance because it governs how often the JIT runs and where the JIT focuses its efforts.

Runtime optimizers use JIT compilation in different ways. If the system JIT compiles u de as happens in some native-code systems, then the trigger ma mpile each procedure before its first call.” If, instead, the system only compiles hot code, the trigger may require procedure-level or block-level profile data. Native-code environments and mixed-mode en-vironments may employ different mechanisms to gather that profile data.

In a native-code environment, the compiler writer must choose between (1) a system that works from VM code and compiles that VM code to native code before it executes, or (2) a system that works from AOT-compiled native code and only invokes the JIT on frequently executed, or hot, code. The two approaches lead to distinctly different challenges.

In a mixed-mode environment, the system can begin execution immediately and gather profile data to determine when to JIT compile code for native execution. These systems tend to trigger compilation based on profile data exceeding a preset threshold value above which the code is considered hot. This approach helps the system avoid spending JIT cycles on code that has little or no impact on performance.

Threshold values play a key role in determining overall runtime. Larger threshold values decrease the number of JIT compilations. At the same time, they increase the fraction of runtime spent in the VM-code emulator, which is typically slower than native-code execution. Varying the threshold values changes system behavior.

To obtain accurate profile data, a VM-code environment can instrument the application’s branches and jumps. To limit the overhead of profile collection, these systems often limit the set of points where they collect data. For example, blocks that are the target of a backward branch are good candidates to profile because they are likely to be loop headers. Similarly, the block that starts a procedure’s prolog code is an obvious candidate to profile. The system can obtain call-site specific data by instrumenting precall sequences. All of these metrics, and others, have been used in practical and effective systems.

If the system executes native code, it must compile each procedure before that code can run. The system can trigger compilation at load time, either in batch for the entire executable(Speed Doubler) or as modules are loaded(early versions of the V8 system for JAVASCRIPT). Alternatively, the system can trigger the compiler to translate each procedure the first time it runs. To achieve that effect, the system can link a stub in place of any yet-to-be-compiled procedure; the stub locates the VM code for the callee, JIT compiles and links it, and reexecutes the call.

In this context, a backwar targets an address smaller than counter.

Loop-closing branches are usually ward branches.

SPEED DOUBLER Speed Doubler was a commercial product from Connectix in the 1990s. It used load-time compilation to retarget legacy applications to a new ISA. Apple had recently migrated its Macintosh line of computers from the Motorola MC 68000 to the IBM POWER PC. Support for legacy applications was provided by an emulator built into the MacOS.

Speed Doubler was a load-time JIT that translated MC 68000 applications into native POWER PC code. By eliminating the emulation overhead, it provided a substantial speedup. When installed, it was inserted between the OS loader and the start of application execution. It did a quick translation, then branched to the application’s startup code.

The initial version of Speed Doubler appeared to perform an instruction-by-instruction translation, which provided enough improvement to justify the product’s name. Subsequent versions provided better runtime performance; we presume it was the result of better optimization and code generation.

Speed Doubler used native-code execution with a compile-on-load discipline to provide a simple and transparent mechanism to improve running times. Users perceived that JIT compilation cost significantly less than the speedups that it achieved, so the product was successful.

Decreasing time in the JIT directly reduces elapsed execution time.

Load-time strategies must JIT-compile every procedure, whether or not it ever executes. Any delay from that initial compilation occurs as part of the application’s startup. Compile-on-call shifts the cost of initial compilation later in execution. It avoids compiling code that never runs, but it does compile any code that runs, whether it is hot or cold.

If the system starts from code compiled by an AOT compiler, it can avoid these startup compilations. The AOT compiler can insert the necessary code to gather profile data. It might also annotate the code with information that may help subsequent JIT compilations. A system that uses precompiled native code only needs to trigger the optimizer when it discovers that some code fragment is hot-that is, the code consumes enough runtime to justify the cost of JIT compiling it.

Runtime optimizers operate at different granularities. This decision, made at design time, has a strong impact on overall effectiveness because it determines the kinds of optimizations that the JIT can apply and the code size of the fragments that the JIT optimizes. Two particular optimization scopes have been used widely.

Hot Traces A trace optimizer watches runtime branches and jumps to discover hot traces. Once a trace’s execution count exceeds the preset hot threshold, the system invokes the JIT to construct an optimized native-code implementation of the trace.

Trace optimizers perform local or regional optimization on the hot trace, followed by native-code generation including allocation and scheduling. Because a runtime trace may include calls and returns, this “regional”optimization can make improvements that would be considered interpro-cedural in an AOT compiler.

Hot Methods A method optimizer finds procedures that account for a significant fraction of overall running time by monitoring various counters. These counters include call counts embedded in the prolog code, loop iteration counts collected before backward branches, and call-site specific data gathered in precall sequences. Once a method becomes hot, the system uses a JIT to compile optimized native code for the method.

Because it works on the entire method, the optimizer can perform nonlo-cal optimizations, such as code motion, regional instruction scheduling.dead-code elimination, global redundancy elimination, or strength reduction. Some method optimizers also perform inline substitution. They might pull inline the code for a frequently executed call in the hot method. If most calls to a hot method come from one call site, the optimizer might inline the callee into that caller.

The choice of granularity has a profound impact on both the cost of optimizations and the opportunities that the optimizer discovers.

A trace optimizer might apply LVN to the entire trace to find redundancy, fold constants, and simplify identities. Most method optimizers use a global redundancy algorithm, which is more expensive but should find more opportunities for improvement.

A trace optimizer might use a fast local register allocator like the algorithm from Section 13.3. By contrast, a method optimizer must deal with control flow, so it needs a global register allocator such as the coloring allocator or the linear scan allocator(see Sections 13.4 and 13.5.3).

Again, the tradeoff comes down to the cost of optimization against the total runtime improvement.

A JIT can discover facts that are not known before runtime and use those facts to justify or inform optimization. These facts can include profile information, object types, data structure sizes, loop bounds, constant values or

Trace(revisited)

A trace is an acyclic sequence of blocks. As used in runtime optimization, a trace can cross procedure-call boundaries.

Assume a trace that has one entry but m,5 have premature exits.

Linear scan achieves some of the benefits of global allocation with lower cost than graph coloring.

The Deutsch-Schiffman implementation of Smalltalk-80 used JIT compilation to create a native-code environment on a system with a Motorola MC 68000-series processor. Smalltalk-80 was distributed as an image for the Smalltalk-80 virtual machine.

This system only executed native-code. The method lookup and dispatch mechanism invoked the JIT for any method that did not have a native-code body-a compile-on-call discipline.

The system gained most of its speed improvement from replacing VM emulation with native-code execution. It used a global method cache and was the first system to use inline method caches. The authors were careful about translating between VM structures and native-code structures, particularly activation records. The result was a system that was astonishing in its speed when compared to other contemporary Smalltalk-80 implementations on off-the-shelf hardware.

The system ran in a small-memory environment.(16MB of RAM was considered large at the time.) Because native code was larger than VM code by a factor of two to five, the system managed code space carefully. When the system needed to reclaim code space, it discarded native code rather than paging it to disk. This strategy, sometimes called throw-away code generation, was profitable because of the large performance differences between VM emulation and native-code execution, and between JIT compilation and paging to a remote disk(over 10 MBPS Ethernet).

In the Deutsch-Schiffman system, native code was fast enough to compensate for the JIT costs.

types, and other system-specific facts. To the extent that these facts enable optimization that cannot be done in an AOT compiler, they help to justify runtime compilation.

In practice, runtime optimizers find improvement in a number of different ways. Among those ways are:

Eliminate VM Overhead If the JIT operates in a mixed-mode environment, the act of translation to native code decreases the emulation overhead. The native code replaces software emulation with hardware execution, which is almost always faster.

Some early JITs, such as Thompson’s JIT for regular expressions in the QED editor, performed minimal optimization. Their benefits came, almost entirely, from elimination of VM overhead.

Improve Code Layout A trace optimizer naturally achieves improvements from code layout. As it creates a copy of the hot trace, the JIT places the blocks in sequential execution order, with some of the benefits ascii

global code placement(see Section 8.6.2). In the compiled copy of the hot trace, the JIT can make the on-trace path use the fall-through path at each conditional branch. At the same time, any end-of-block jumps in the trace become jumps to the next operation, so the JIT can simply remove them.

■ Eliminate Redundancy Most JITs perform redundancy elimination. A trace optimizer can apply the LVN or SVN algorithms, which also perform constant propagation and algebraic simplification. Both algorithms have O(1) cost per operation.

A method optimizer can apply DVNT or a data-flow technique such as lazy code motion or a global value-numbering algorithm to achieve similar benefits. The costs of these algorithms vary, as do the specific opportunities that they catch (see Sections 10.6 and 10.3.1).

■ Reduce Call Overhead Inline substitution eliminates call overhead. A runtime optimizer can use profile data to identify call sites that it should inline. A trace optimizer can subsume a call or a return into a trace. A method optimizer can inline call sites into a hot method. It can also use profile data to decide whether or not to inline the hot method into one or more of its callers.

■ Tailor Code to the System Because the results of JIT compilation are ephemeral—they are discarded at the end of the execution—the JIT can optimize the code for the specific processor model on which it will run. The JIT might tailor a compute-bound loop to the available SIMD hardware or the GPU. Its scheduler might benefit from model-specific facts such as the number of functional units and their operation latencies.

■ Capitalize on Runtime Information Programs often contain facts that cannot be known until runtime. Of particular interest are constant, or unchanging, values. For example, loop bounds might be tied to the size of a data structure read from external media—read once and never changed during execution. The JIT can determine those values and use them to improve the code. For example, it might move range-checks out of a loop (see Section 7.3.3).

In languages with late binding, type and class information may be difficult or impossible to discern in an AOT compiler. The JIT can use runtime knowledge about types and classes to tailor the compiled code to the runtime reality. In particular, it might convert a generic method dispatch to a class-specific call.

JIT compilation can impose subtle constraints on optimization. For example, traditional AOT optimization often focuses on loops. Thus, techniques such as unrolling, loop-invariant code motion, and strength reduction have all proven important in the AOT model. Hot-trace optimizers that exclude cyclic paths cannot easily duplicate those effects.

Dynamo, in particular, benefited from linearization of the traces.

We do not know of a JIT that performs model-specific optimization. For machine-dependent problems such as instruction scheduling, the benefits might be significant.

An AOT compiler might identify values that can impact JIT optimization and ‘inclu’ methods that query those values.

The Dynamo system was a native-code, hot-trace optimizer for Hewlett-Packard’s PA-8000 systems. The system’s fundamental premise was that it could efficiently identify and improve frequently executed traces while executing infrequently executed code in emulation.

To find hot traces, Dynamo counted the executions of blocks that were likely start-of-trace candidates. When a block’s count crossed a preset threshold (50), the JIT would build a trace and optimize it. Subsequent executions of the trace ran the compiled code. The system maintained its own software-managed cache of compiled traces.

Dynamo achieved improvements from local and superlocal optimization, from improved code locality, from branch straightening, and from linking traces into larger fragments. Its traces could cross procedure-call boundaries, which allowed Dynamo to optimize interprocedural traces.

Dynamo showed that JIT compilation could be profitable, even in competition with code optimized by an AOT compiler. Subsequent work by others created a Dynamo-like system for the IA-32 ISA, called DynamoRIO.

ILOC includes the tbl pseudooperation to record and preserve this kind of knowledge.

Control-flow optimizations, such as unrolling or cloning, typically require a control-flow graph. It can be difficult to reconstruct a CFG from assembly code. If the code uses a jump-to-register operation(jump in ILOC), it may be difficult or impossible to know the actual target. In an IR version of the code, such branch targets can be recorded and analyzed. Even with jump-to-label operations(jumpI in ILOC), optimization may obfuscate the control-flow to the point where it is difficult or impossible to reconstruct. For example, Fig. 12.17 on page 656 shows a single-cycle, software-pipelined loop that begins with five jump-to-label operations; reconstructing the original loop from the CFG in Fig. 12.17(b) is a difficult problem.

JIT construction is an exercise in engineering. It does not require new the-ories or algorithms. Rather, it requires careful design that focuses on efficiency and effectiveness, and implementation that focuses on minimizing actual costs. The success of a JIT-based system will depend on the cumulative impact of individual design decisions.

The rest of this chapter illustrates the kinds of tradeoffs that occur in a run-time optimizer. It examines two specific use cases: a hot-trace optimizer, in ction 14.5 and a hot-method optimizer, in Section 14.4. The hypothetical optimizer draws heavily from the design of the Dynamo system. The hot-method optimizer takes its inspiration from the original HotSpot Server Compiler and from the Deutsch-Schiffman SMALLTALK-80 system. Finally, Section 14.5 builds on these discussions to examine some of the more nuanced decisions that a JIT designer must make.

In JIT design, compiler writers must answer several critical questions. They must choose an execution model; will the system run unoptimized code in an emulator or as native code? They must choose a granularity for compilation; typical choices are traces and whole procedures (or methods). They must choose the compilation triggers that determine when the system will optimize (and reoptimize) code. Finally, compiler writers must understand what sources of improvement the JIT will target, and they must choose optimizations that help with those particular issues.

Throughout the design and implementation process, the compiler writer must weigh the tradeoffs between spending more time on JIT compilation and the resulting reduction of time spent executing the code. Each of these decisions can have a profound impact on the effectiveness of the overall system and the running time of an application program.

  1. In a system that executes native code by default, how might the system create the profile data that it needs? How might the system provide that data to the JIT?
  2. Eliminating the overhead of VM execution is, potentially, a major source of improvement. In what situations might emulation be more efficient than JIT compilation to native code?

In the classic execution model for compiled code, the processor reads operations and data directly from the address space of the running process. The drawing labeled “Normal Execution” in the margin depicts this situation. (It is a simplified version of Fig. 5.15.) The fetch-decode-execute cycle uses the processor’s hardware.

Conceptually, a native-code hot-trace optimizer sits between the executing process’ address space and the processor. It “monitors” execution until it has “enough” context to determine that some portion of the code is hot and should be optimized. At that point, it optimizes the code and ensures that

Normal Execution

future executions of the optimized sequence run the optimized copy rather than the original code. The margin drawing depicts that situation.

The hot-trace optimizer has a difficult task. It must find hot traces. It must improve those traces enough to overcome the costs of finding and compiling them. For each cycle spent in the JIT, it must recover one or more cycles through optimization. In addition, if the process slows execution of the cold code, the optimized compiled code must also make up that deficit.

This section presents the design of a hot-trace optimizer. The design follows that of the Dynamo system built at Hewlett-Packard Research around the year 2000. It serves as both an introduction to the issues that arise and a concrete example to explore design tradeoffs.

Dynamo executed native code by emulation until it identified a hot trace. The emulator ran all of the cold code, gathered profile information, and identified the hot traces. Thus, emulated execution of the native code was slower than simply running that code on the hardware. The premise behind Dynamo was that improvement from optimizing hot traces could make up for both the emulation overhead and the JIT compilation costs.

These design concepts raise several critical issues. How should the system define a trace? How can it find the traces? How does it decide a trace is hot? Where do optimized traces live? How does emulated cold code link to the hot code and vice versa?

In Dynamo, trace profiling, trace identification, and linking hot and cold code all depend on the notion of a trace-entry block. Each trace starts with an entry block. A trace-entry block meets one of two simple criteria. Either it is the target of a backward branch or jump, or it is the target of an exit from an existing compiled trace.

The first criterion selects blocks that are likely to be loop-header blocks. These blocks can be identified with an address comparison; if the target address is numerically smaller than the current program counter(PC), the target address designates a trace-entry block.

The second criterion selects blocks that may represent alternate paths through a loop. Any side exit from a trace becomes a trace-entry block. The JIT identifies these blocks as it compiles a hot trace.

To identify and profile traces, the trace optimizer finds trace-entry blocks and counts the number of times that they execute. Limiting the number of profiled blocks helps keep overhead low. As the optimizer discovers entry

This section presents the design of a hot-trace optimizer. The design follows that of the Dynamo system built at Hewlett-Packard Research around the year 2000. It serves as both an introduction to the issues that arise and a concrete example to explore design tradeoffs. </category> L1: emulateate code until a taken branch or jump lookup target address in the entry table if address is not in the table then if address < emulated PC then create table entry for address set target address’ counter to 1 else // address is in the entry table if fragment has been compiled then jump to the compiled fragment bump the target address’ counter if counter > hot threshold then build, compile, & execute the trace // if here, block runs in emulation mode set emulator’s PC to target address jump back to L1

(a) High-level Algorithm

(b) Components of the Trace Optimizer

■ FIGURE 14.2 Conceptual Structure of a Hot-Trace Optimizer.

blocks, it enters them into a table-the entry table. The table contains an execution count and a code pointer for each block. It is a critical data structure in the hot-trace optimizer.

Fig. 14.2(a) presents a high-level algorithm for the trace optimizer. The combination of the trace-entry table and the trace cache encapsulates the system’s current state. The algorithm determines how to execute a block based on the presence or absence of that block in the entry table and the values of its execution counter and its code pointer.

Blocks run in emulation until they become part of a compiled hot trace. At that point, further executions of the compiled trace run the block as part of the optimized code. If control enters the block from another off-trace path, the block executes in emulation using the original code.

The critical set of decisions occurs when the emulator encounters a taken branch or a jump.(A jump is always taken.) At that point, the emulator looks for the target address in the trace entry table.

■ If the target address is not in the table and that address is numerically smaller than the current PC, the system classifies the target address as a trace entry block. It creates an entry in the table and initializes the The smaller target address means that this branch or jump is a backward branch.

The compiled trace is stored in the trace cache.

Section 14.3.2 discusses how the compiler can link compiled traces together.

entry’s execution counter to one. It then sets the emulator’s PC to the target address and continues emulation with the target block.

If, instead, the target address already has a table entry and that entry has a valid code pointer, the emulator transfers control to the compiled code fragment. Depending on the emulator’s implementation, discussed below, this transfer may require some brief setup code, similar to the precall sequence in a classic procedure linkage.

Each exit path from the compiled trace either links to another compiled trace or ends with a short stub that sets the emulator’s PC to the address of the next block and jumps directly back to the emulator-to label L1 in Fig. 14.2(a).

If the target address is in the table but has not yet been compiled, the system increments the target address’ execution counter and tests it against the hot threshold. If the counter is less than or equal to the threshold, the system executes the target block by emulation. When the target address’execution counter crosses the threshold, the system builds an IR image of the hot trace, executes and compiles that trace, stores the code into the trace cache, and stores its code pointer into the appropriate slot in the trace entry table.

On exit from the compiled trace, execution continues with the next block. Either the code links directly to another compiled trace or it uses a path-specific exit stub to start emulation with the next block.

The algorithm in Fig. 14.2(a) shows the block-by-block emulation, inter-spersed with execution of optimized traces. The emulator jumps into optimized code; optimized traces exit with code that sets the emulator’s PC and jumps back to the emulator. The rest of this section explores the details in more depth.

Following Dynamo, the trace optimizer executes cold code by emulation. The JIT-writer could implement the emulator as a full-fledged interpreter with a software fetch-decode-execute loop. That approach would require a simulated set of registers and code to transfer register values between simulated registers and physical registers on the transitions between emulated and compiled code. This transitional code might resemble parts of a standard linkage sequence.

As an alternative, the system could “emulate” execution by running the original compiled code for the block and trapping execution on a taken branch or jump. If hardware support for that trap is not available, the system can store the original operation and replace it with an illegal instruction-a trick used in debuggers since the 1960s. When the PC reaches the end of the block, the illegal instruction traps. The trap handler then follows the algorithm from Fig. 14.2(a), using the stored operation to determine the target address. In this approach, individual blocks execute from native code, which may be faster than a software fetch-decode-execute loop.

Building the Trace

When a trace-entry block counter exceeds the hot threshold, the system invokes the optimizer with the address of the entry block. The optimizer must then build a copy of the trace, optimize that copy, and enter the optimized fragment into the trace cache.

While the system knows that the entry block has run more than threshold times, it does not actually know which path or paths those executions took. Dynamo assumes that the current execution will follow the hot path. Thus, the optimizer starts with the entry block and executes the code in emulation until it reaches the end of the trace—a taken backward branch or a transfer to the entry of a compiled trace. Again, comparisons of runtime addresses identify these conditions.

As the optimizer executes the code, it copies each block into a buffer. At each taken branch or jump, it checks for the trace-ending conditions. An taken branch denotes a side exit from the trace, so the optimizer records the target address so that it can link the side exit to the appropriate trace or exit stub. When it reaches the end of the trace, the optimizer has both executed the trace and built a linearized version of the code for the JIT to optimize.

Consider the example shown in Fig. 14.3(a). When the emulator sees B1B_{1} ‘s counter cross the hot-threshold, it invokes the optimizer. The optimizer executes B1B_{1} and copies each of its operations into the buffer. The next branch takes control to B2B_{2} ; the emulator executes B2B_{2} and adds it to the buffer. Next, control goes to B5B_{5} followed by B6B_{6} . The branch at the end of B6B_{6} goes back to B1B_{1} , terminating the trace. At this point, the buffer contains B1,B2,B5B_{1},B_{2},B_{5} , and B6B_{6} , as shown in panel (b).

The drawing assumes that each of the side exits leads to cold code. Thus, the JIT builds a stub to handle each side exit and the end-of-trace exit. The stub labeled Bi∗B_{i}^{*} sets the emulator’s PC to the start of block BiB_{i} and jumps to the emulator. The stub also provides a location where the optimizer can insert any code needed to interface the compiled code with the emulated code. Panel (b) shows stubs for B3,B4B_{3},B_{4} , and B7B_{7} .

The optimizer builds the trace based on the dynamic behavior of the executing code, which can produce complex effects. For example, a trace can

(a) Example CFG (b) Trace Buffer for ⟨B1,B2,B5,B6⟩\langle B_{1},B_{2},B_{5},B_{6}\rangle

Figure 14.3 Building a Trace.

extend through a procedure call and, with a simple callee, through a return. Because call and return are implemented with jumps rather than branches, they will not trigger the criteria for an exit block.

Once the optimizer has constructed a copy of the trace, it makes one or more passes over the trace to analyze and optimize the code. If the initial pass is a backward pass, the optimizer can collect LIVE information and other useful facts. From an optimization perspective, the trace resembles a single path through an extended basic block(see Section 8.5). In the example trace, an operation in B6 can rely on facts derived from any of its predecessors, as they all must execute before control can reach this copy of B6.

The mere act of trace construction should lead to some improvements in the code. The compiler can eliminate any on-trace jumps. For each early exit, the optimizer should make the on-trace path be the fall-through path. This linearization of the code should provide a minor performance improvement by eliminating some branch and jump latencies and by improving instruction-cache locality.

The compiler writer must choose the optimizations that the JIT will apply to the trace. Value numbering is an obvious choice; it eliminates redundancies, folds constants, and simplifies algebraic identities.

If the trace ends with a branch to its entry block, the optimizer can unroll this path through the loop. In a loop with control flow, the result may be a loop that is unrolled along some paths and not along others-a situation that does not arise in a traditional AOT optimizer. Early exits from the trace introduce complications. The same compensation-code issues that arise in regional scheduling apply to code motion across early exits (e.g., at the ends of B1B_{1} and B2B_{2}). If optimization moves an operation across an exit, it may need to insert code into the stub for that exit.

The optimizer can detect some instances of dead or partially dead code. Consider an operation that defines rir_{i}. If rir_{i} is redefined before its next on-trace use, then the original definition can be moved into the stubs for any early exits between the original definition and the redefinition. If it is not redefined but not used in the trace, it can be moved into the stubs for the early exits and into the final block of the trace.

After optimization, the compiler should schedule operations and perform register allocation. Again, the local versions of these transformations can be applied, with compensation code at early exits.

The size of the trace cache can affect performance. Size affects multiple aspects of trace-cache behavior, from memory locality to the costs of lookups and managing replacements. If the cache is too small, the JIT may discard fragments that are still hot, leading to lost performance and subsequent re-compilations. If the cache is too large, it may retain code that has gone cold, hurting locality and raising lookup costs. Undoubtedly, compiler writers need to tune the trace-cache size to the specific system characteristics.

One key to efficient execution is to recognize when other paths through the CFG become hot and to optimize them in a way that works well with the fragments already in the cache.

In the ongoing example, block B1B_{1} became hot and the optimizer built a fragment for ⟨B1,B2,B5,B6⟩\langle B_{1},B_{2},B_{5},B_{6}\rangle, as shown in Fig. 14.4(a). The early exits to B3B_{3} and B4B_{4} then make those blocks into trace-entry blocks. If B3B_{3} becomes hot, the optimizer will build a trace for it. The only trace it can build is ⟨B3,B5,B6⟩\langle B_{3},B_{5},B_{6}\rangle, as shown in panel (b).

If the optimizer maintains a small amount of information about trace entries and exits, it can link the two traces in panel (b) to create the code shown in panel (c). It can rewrite the branch to B1∗B_{1}^{*} as a direct jump to B1B_{1}. Similarly, it can rewrite the branch to B3∗B_{3}^{*} as a direct jump to B3B_{3}. The in-terlinked traces then create fast execution paths for both ⟨B1,B2,B5,B6⟩\langle B_{1},B_{2},B_{5},B_{6}\rangle and ⟨B1,B3,B5,B6⟩\langle B_{1},B_{3},B_{5},B_{6}\rangle, as shown in panel (c). The exits to B4B_{4} and B7B_{7} still run though their respective stubs to the interpreter.

Partially dead An operation is partially dead at point p in the code if it is live on some paths that start at p and dead on others.

(a) Original Trace (b) Trace for (B3,B5,B6) (c) After Trace Linking

Figure 14.4 Adding a Second Trace.

Example CFG ├─ B1 │ ├─ B2 │ │ └─ B3 │ └─ B4 │ └─ B5 │ └─ B6 │ └─ B7 └─ B6

If during optimization of ⟨B1,B2,B5,B6⟩, the JIT moved operations into B3*, then the process of linking would need to either (1) preserve B3* on the path from B1 to B3 or (2) prove that the operations in B3* are dead. With a small amount of context, such as the set of registers defined before use in the fragment, it could recognize dead compensation code in the stub.

Cross-linking in this way also addresses a weakness in the trace-construction heuristic. The trace builder assumed that the (k+1)st execution of B1 took the hot path. Because the system only instruments trace header blocks, B1’s execution count could have accrued from multiple paths between B1 and B6. What happens if the (k+1)st execution takes the least hot of those paths?

With trace linking, the (k+1)st execution will build an optimized fragment. If that execution does not follow the hot path, then one or more of the early exits in the fragment will become hot; the optimizer will compile them and link them into the trace, capturing the hot path or paths. The optimizer will recover gracefully as it builds a linked set of traces.

Intermediate Entries to a Trace

In the example, when B1 became hot, the system built an optimized trace for ⟨B1,B2,B5,B6⟩. When B3 became hot, it optimized ⟨B3,B5,B6⟩.

The algorithm, as explained, builds a single trace for ⟨B1,B2,B5,B6⟩ and ignores the intermediate entry to the trace from the edge (B3,B5). The system then executes the path ⟨B3,B5,B6⟩ by emulation until B3’s counter triggers compilation of that path. This sequence of actions produces two copies of the code for B5 and B6, along with the extra JIT-time to optimize them.

Another way to handle the edge (B3,B5) would be to construct an intermediate entry into the trace ⟨B1,B2,B5,B6⟩. The trace-building algorithm, as explained, ignores these intermediate entry points, which simplifies record-keeping. If the emulator knew that B5 was an intermediate entry point, it could split the trace on entry to B5. It would build an optimized trace for ⟨B1, B2⟩ and another for ⟨B5, B6⟩. It would link the expected-case exit from ⟨B1, B2⟩ to the head of ⟨B5, B6⟩.

To implement trace splitting, the optimizer needs an efficient and effective mechanism to recognize an intermediate trace entry point—to distinguish, in the example, between B4 and B5. The hot-trace optimizer, as described, does not build an explicit representation of the CFG. One option might be for the AOT compiler to annotate the VM code with this information.

Splitting ⟨B1, B2, B5, B6⟩ after B2 may produce less efficient code than compiling the unsplit trace. Splitting the trace avoids compiling ⟨B5, B6⟩ a second time and storing the extra code in the code cache. It requires an extra slot in the entry block table. This tradeoff appears to be unavoidable. The best answer might well depend on the length of the common suffix of the two paths, which may be difficult to discern when compiling the first trace.

A hot-trace optimizer identifies frequently executed traces in the running code, optimizes them, and redirects future execution to the newly optimized code. It assumes that frequent execution in the past predicts frequent execution in the future and focuses the JIT’s effort on such “hot” code. The acyclic nature of the traces leads to the use of local and superlocal optimizations. Those methods are fast and can capture many of the available opportunities.

The use of linked traces and interprocedural traces lets a hot-trace optimizer achieve a kind of partial optimization that an ahead-of-time compiler would not. The intent is to focus the JIT’s effort where it should have maximum effect, and to limit its effort in regions where the expected impact is small.

  1. Once a trace entry block becomes hot, the optimizer chooses the rest of the trace based on the entry-block’s next execution. Contrast this strategy with the trace-discovery algorithm used in trace-scheduling. How might the results of these two approaches differ?

  2. Suppose the trace optimizer fills its trace cache and must evict some trace. What steps would be needed to revert a specific trace so that it executes by VM-code emulation?

Method-level optimization presents a different set of challenges and trade-offs than does trace-level optimization. To explore these issues, we will first consider a hot-method optimizer embedded in a JAVA environment. Our design is inspired by the original HotSpot Server Compiler(hereafter, HotSpot). The design is a mixed-mode environment that runs cold methods as JAVA bytecode and hot methods as native code. We finish this section with a discussion of the differences in a native-code hot-method optimizer.

14.4.1 Hot-Methods in a Mixed-Mode Environment

Section titled “14.4.1 Hot-Methods in a Mixed-Mode Environment”

Fig. 14.5 shows an abstract view of the JAVA virtual machine or JVM. Classes and their associated methods are loaded into the environment by the Class Loader. Once stored in the VM, methods execute on an emulator-the figure’s “Bytecode Engine.” The JVM operates in a mixed-mode environment, with native-code implementations for many of the standard methods in system libraries.

To add a method-level JIT, the compiler writer must add several features to the JVM: the JIT itself, a software-managed cache for native-code method bodies, and appropriate interfaces. Fig. 14.6 shows these modifications.

From an execution standpoint, the presence of a JIT brings several changes. Cold code still executes via VM-code emulation; methods from native libraries still execute from native code. When the system decides that a method is hot, it JIT-compiles the VM code into native code and stores the ■ FIGURE 14.6 Adding a JIT to the JAVA Runtime Environment.

new code in its native-code cache. Subsequent calls to that method run from the native code, unless the system decides to revert the method to VM-code emulation (see the discussion of deoptimization on page 742).

The compiler writer must make several key decisions. The system needs a mechanism to decide which methods it will compile. The system needs a strategy to gather profile information efficiently. The compiler writer must decide whether the native code operates on the VM-code or the native-code versions of the various runtime structures, such as activation records. The compiler writer must design and implement the JIT, which is just an efficient and constrained compiler. Finally, the compiler writer must design and implement a mechanism to revert a method to VM-code emulation when the compiled method proves unsuitable. We will explore these issues in order.

Conceptually, the hot-method optimizer should compile a method when that method consumes a significant fraction of the execution time. Finding a hot method that meets this criterion is harder than finding a hot trace, because the notion of a “significant fraction” of execution time is both imprecise and unknowable until the program terminates.

Thus, hot-method optimizers fall back on counters and thresholds to estimate a method’s activity. This approach relies on the implicit assumption that a method that has consumed significant runtime will continue to consume significant runtime in the future. Our design, following HotSpot, will measure: (1) the number of times the method is called and (2) the number

Iteration can occur with either loops or recursion. The mechanism should catch either case.

Around 2000, Sun Microsystems delivered a pair of JITs for its JAVA environment: one intended for client-side execution and the other for server-side execution. The original HotSpot Server Compiler employed more expensive and extensive techniques than did the client-side JIT. The HotSpot Server compiler was notable in that it used strong global optimization techniques and fit them into the time and space constraints of a JIT. The authors used an IR that explicitly represented both control flow and data flow[92]. The IR, in turn, facilitated redundancy elimination, constant propagation, and code motion. Sparsity in the IR helped make these optimizations fast.

The JIT employed a novel global scheduling algorithm and a full coloring allocator(see Section 13.4). To make the coloring allocator practical, the authors developed a method to trim the interference graph that significantly shrink the graph. The result was a state-of-the-art JIT that employed algorithms once thought to be too expensive for use in a JIT.

of loop iterations that it executes. Neither metric perfectly captures the notion that a method uses a large fraction of the running time. However, any method that does consume a significant fraction of runtime will almost certainly have a large value in one of those two metrics.

Thus, the system should count both calls to a method and loop iterations within a method. Strategically placed profile counters can capture each of these conditions. For call counts, the system can insert a profile counter into each method’s prolog code. For iteration counts, the system can insert a profile counter before each loop-closing branch. To trigger compilation, it can either use separate thresholds for loops and invocations, or it can sum the counters and use a single threshold.

HotSpot counted both calls and iterations and triggered a compilation when the combined count exceeded a preset threshold of 10,000 events. This threshold is much larger than the one used in Dynamo(50). It reflects the more aggressive and expensive compilation in HotSpot.

To capture profile data, compiler writers can instrument either the VM code for the application or the implementation of the VM-code engine.

Instrumented VM Code. The system can insert VM code into the method to increment and test the profile counters. In this design, the profile overhead executes as VM code. Either the AOT compiler or the Class Loader can

The system can “sum” the counters by using a single location for all the counters in a method. insert the instrumentation. Counter for calls can be placed in the method’s prolog code, while counters for a specific call-site can be placed in the appropriate precall sequence.

To profile loop iterations, the transformation can insert a counter into any block that is the target of a backward branch or jump. An AOT strategy might decrease the cost of instrumentation; for example, if the AOT compiler knows the number of iterations, it can increment the profile counter once for the entire loop.

Instrumented Engine. The compiler writer can embed the profile support directly into the implementtaion of the VM-code engine. In this scheme, the emulator’s code for branches, jumps, and the call operation (e.g., the JVM’s invokestatic or invokevirtual) can directly increment and test the appropriate counters, which are stored at preplanned locations. Because the profile code executes as native code, it should be faster than instrumenting the VM code.

The emulator could adopt the address comparison strategy of the trace optimizer to identify loop header blocks. If the target address is numerically smaller than the PC, the targeted block is a potential loop header. Alter-natively, it could rely on the AOT compiler to provide an annotation that identifies loop-header blocks.

When profile data triggers the JIT to compile some method x, the JIT can simply retrieve the VM code for x and compile it. The JIT resembles a full-fledged compiler. It parses the VM code into an IR, applies one or more passes of optimization to the IR, and generates native code-performing instruction selection, scheduling, and register allocation. The JIT writes that native code into the native-code cache (see Fig. 14.6). Finally, it updates the tables or pointers that the system uses to invoke methods so that subsequent calls map to the cached native code.

In a mixed-mode environment, the benefits of JIT compilation should be greater than they are in a native-code environment because the cold code executes more slowly. Thus, a hot-method optimizer in a mixed-mode environment can afford to spend more time per method on optimization and code generation. Hot-method optimizers have applied many of the classic scalar optimizations, such as value numbering, constant propagation, dead-code elimination, and code motion (see Chapters 8 and 10). Compiler writers choose specific techniques for the combination of compile-time efficiency and effectiveness at improving code.

By contrast, an AOT compiler w loop headers using dominators (se tion 9.2.1).

Tree-pattern matching techniques are a good match to the constraints of a JIT (see Section 11.4).

The literature on method-level JITs often mentions global value numbering as one of the key optimizations that these JITs employ. The dutiful student will find no consensus on the meaning of that term. Global value numbering has been used to refer to a variety of distinct and different algorithms.

One approach extends the ideas from local value numbering to a global scope, following the path taken in superlocal and dominator-based value numbering(DVNT). These algorithms are more expensive than DVNT and the cost-benefit tradeoff between DVNT and the global algorithm is not clear.

Another approach uses Hopcroft’s partitioning algorithm to find operations that compute the same value, and then rewrites the code to reflect those facts. The HotSpot Server compiler used this idea, which fit well with its program dependence graph IR.

Finally, the JIT writer could work from the ideas in lazy code motion(LCM).This approach would combine code motion and redundancy elimination. Because LCM implementations solve multiple data-flow analysis problems, the JIT writer would need to pay close attention to the cost of analysis.

Hot-method JITs apply local, regional, and global optimizations. Because the JIT operates at runtime, the compiler writer can arrange for an optimization to access the runtime state of the executing program to obtain runtime values and use them in optimization.

Value Numbering Method-level JITs typically apply some form of value numbering. It might be a regional algorithm, such as DVNT, or it might be one of a number of distinct global algorithms.

Value numbering is attractive to the JIT writer because these techniques achieve multiple effects at a relatively low cost. Typically, these algorithms perform some subset of redundancy elimination, code motion, constant propagation, and algebraic simplification.

Specialization to Runtime Data A JIT can have access to data about the code’s behavior in the current execution, particularly values of variables, type information, and profile data. Runtime type information lets the JIT speculate; given that a value consistently had type t in the past, the JIT assumes that it will have type t in the future.

Such speculation can take the form of a fast-path/slow-path implementation. Fig. 14.6 shows, conceptually, how such a scheme might work. The code assumes that x and y are both 32-bit integers and tests for that case;

Inline method caches can provide site-specific data about receiver types. The idea can be extended to capture type information on parameters, as well. // x ← y + z if actual_type(y) = 32_bit_integer and actual_type(z) = 32_bit_integer then x ← 32_bit_integer_add(y, z) else x ← generic_add(y, actual_type(y), z, actual_type(z));

■ FIGURE 14.6 Code with a Fast Path for the Expected Case.

if the test fails, it invokes the generic addition routine. If the slow path executes too many times, the system might recompile the code with new speculated types (see the discussion of “deoptimization” on page 742).

Inline Substitution The JIT can inline calls, which lets it eliminate method lookup overhead and call overhead. Inlining leads the JIT to tailor the callee’s body to the environment at the call site. The JIT can use data from inline method caches to specialize code based on call-site specific type data. It can also inline call sites in the callee; it should have access to profile data and method cache data for all of those calls.

The JIT can also look back to callers to assess the benefits of inlining a method into one or more of its callers. Again, profile data on the caller and type information from the inline cache may help the JIT make good decisions on when to inline.

Code Generation Instruction selection, scheduling, and register allocation can each further improve the JIT-compiled code. Effective instruction selection makes good use of the ISA’s features, such as address modes. Instruction scheduling takes advantage of instruction-level parallelism and avoids hardware stalls and interlocks. Register allocation tries to minimize expensive spill operations.

The challenge for the JIT writer is to implement these passes efficiently. Tree-pattern matching techniques for selection combine locally optimal code choice with extreme JIT-time efficiency. Both the scheduler and the allocator can capitalize on sparsity to make global algorithms efficient enough for JIT implementation. The HotSpot Server Compiler demonstrated that efficient implementations can make these global techniques not only acceptable but advantageous.

As with any JAVA system, a JIT should also try to eliminate null-pointer checks, or move them to places where they execute less frequently. Escape analysis can discover objects whose lifetimes are guaranteed to be contained within the lifetime of some method. Such objects can be allocated in the method’s AR rather than on the heap, with a corresponding decrease in allocation and collection costs. Final and static methods can be inlined.

If the JIT uses runtime information to optimize the code, it runs the risk that changes in that data may render the compiled code either badly optimized or invalid. The JIT writer must plan for reasonable behavior in the event of a failed type speculation. The system may decide to deoptimize the code.

the JIT generates less optimized code due to changes in runtime information

To “notice,” the system would need to in-Consider Fig. 14.6 again. If the system noticed, at some point, that most executions of this operator executed the generic_add path, it might recompile the code to speculate on another type, to speculate on multiple types, or to not speculate at all. If the change in behavior is due to a phase-shift in program behavior, reoptimization may help.

If, however, the statement has simply stopped showing consistency in the types of x,y, or z, then repeated reoptimization may be the wrong answer. Unless the compiled code executes enough to cover the cost of JIT compilation, the recompilations will slow down execution.

The alternative is to deoptimize the code. Depending on the precise situation and the depth of knowledge that the JIT has about temporal type locality, it might use one of several strategies.

■ If the JIT knows that the actual type is one of a small number, it could generate fast path code for each of those types.

■ If the JIT knows nothing except that the speculated type is often wrong, it might generate unoptimized native code that just calls generic_add or it might inline generic_add at the operation.

■ If the JIT has been called too often on this code due to changing patterns, it might mark the code as not fit for JIT compilation, forcing the code to execute in emulation.

A deoptimization strategy allows the JIT to speculate, but limits the down-side risk of incorrect speculation.

14.4.2 Hot-Methods in a Native-Code Environment

Section titled “14.4.2 Hot-Methods in a Native-Code Environment”

Several issues change when the JIT writer attempts hot-method optimization in a native-code environment. This section builds on insights from the Deutsch-Schiffman SMALLTALK-80 implementation.

The native-code environment must ensure that each method is compiled to native code before it runs. Many schemes will work, including a straight-1wad AOT compilation, load-time compilation of all methods, or JIT on the first invocation, which we will refer to as compile on call. The first two options are easier to implement than the last one. Neither, however, creates the opportunity to use runtime information during that initial compilation.

A compile-on-call system will first generate code for the program’s main routine. At each call site, it inserts a stub that (1) locates the VM code for the method; (2) invokes the JIT to produce native code for the method; and (3) relinks the call site to point to the newly compiled native code. When the execution first calls method m, it incurs a delay for the JIT to compile m and then executes the native-code version of m. If runtime facts are known, the first call to m can capitalize on them.

If the JIT compiler supports multiple levels of optimization, the compiler writer must choose which level to use in these initial compiles. A lower level of optimization should reduce the cost of the initial JIT compiles, at the cost of slower execution. A higher level of optimization might increase the cost of the initial JIT compiles, with the potential benefit of faster execution.

To manage this tradeoff, the system may use a low optimization level in the initial compiles and recompile methods with a higher level of optimization when they become hot. This approach, of course, requires data about execution frequencies and type locality.

In a native-code environment, the system can gather profile information in two ways: instrument the code to collect profile data at specific points in the code, or shift to interrupt-driven techniques that discover where the executable spends its time.

Instrumented Code. The JIT compiler can instrument code as described earlier for a mixed-mode hot-method optimizer. The JIT can insert code into method prologs to count total calls to the method. It can obtain call-site specific counts by adding code to precall sequences. It can insert code to count loop iterations before loop-closing branches.

With instrumented code, JIT invocation proceeds in the same way that it would in the mixed-mode environment. The JIT is invoked when execution counts, typically call counts and loop iterations, pass some preset threshold. For a loop-iteration count, the code to test the threshold and trigger compilation should be inserted, as well.

To capture opportunities for type speculation and type-based code specialization, the JIT can arrange to record the type or class of specific values—typically, parameters passed to the method or values involved at a call in the method. The JIT should have access to that information.

Using an indirect pointer to the code body (a pointer to a pointer) may simplify the implementation.

The system must produce tables to map an address into a specific location in the original code.

Some systems have used a combination of instrumented code and interrupt-driven profile data.

Interrupt-Driven Profiles. Method-invocation counts tell the system how often a method is called. Iteration counts tell the system how often a loop body executes. Neither metric provides insight into what fraction of total running time the instrumented code actually uses.

A native-code environment spends virtually all of its time executing application code. Thus, it can apply another strategy to discover hot code:interrupt-driven profiling. In this approach, the system periodically stops execution with a timer-driven interrupt. It maps the program-counter address at the time of the interrupt back to a specific method, and increments that method’s counter. Comparing the method’s counter against the total number of interrupts provides an approximation to the fraction of execution time spent in that method.

Because an interrupt-driven profile measures something subtly different than instrumented code measures, the JIT writer should expect that an interrupt-driven scheme will optimize different methods than an instrumented code scheme would.

The JIT still needs data, when possible, on runtime types to guide optimization. While some such data might exist in inline method caches at call sites, the system can only generate detailed information if the compiler adds type-profiling code to the executable.

When a compiled method begins execution, it must determine if the preconditions under which it was compiled(e.g., type or class speculation, constant valued parameters, etc.) still hold. The prolog code for a method can test any preconditions that the JIT assumed in its most recent compilation. In a mixed-mode environment, the system could execute the VM code if the precondition check fails; in a native-code environment, it must invoke the JIT to recompile the code in a way that allows execution to proceed.

In a recompilation, the system should attempt to provide efficient execution while avoiding situations where frequent recompilations negate the benefits of JIT compilation. Any one of several deoptimization strategies might make sense.

■ The JIT could simply recompile the code with the current best runtime information. If the change in preconditions was caused by a phase shift in program behavior, the current preconditions might hold for some time.

■ If the JIT supports multiple levels of optimization-especially with regard to type speculation-the system could instruct the JIT to use a lower level of speculation, which would produce more generic and less

This strategy suggests a counter that limits the number of “phase shifts” the JIT will tolerate on a given method. tailored code. This approach tries to avoid the situation where the code for some method oscillates between two or more optimization states.

An aggressive JIT could compile a new version of the code with the current preconditions and insert a stub to choose among the variant code bodies based on preconditions. This approach trades increased code size for the possibility of better performance.

The best strategy will depend on how aggressively the JIT uses runtime information to justify optimizations and on the economics of JIT compilation. If the JIT takes a small fraction of execution time, the JIT writer and the user may be more tolerant of repeated compilations. By contrast, if it takes multiple invocations of a method to compensate for the cost of JIT compilation, then repeated recompilations may be much less attractive than lowering the level of speculation and optimization.

The fundamental tradeoff for the JIT writer is the difference between cycles spent in the JIT and cycles saved by the JIT. In a native-code environment, the marginal improvement from the JIT may be lower, simply because the unoptimized code runs more quickly than it would in a similar mixed-mode environment.

This observation, in turn, should drive some of the decisions about which optimizations to implement and how much recompilation to tolerate. The JIT writer must balance costs, benefits, and policies to create a system that, on balance, improves runtime performance.

A hot-method optimizer finds procedures that either execute frequently or occupy a significant fraction of execution time. It optimizes each procedure in light of the runtime facts that it can discern. Because a method optimizer can encounter control flow, it can benefit from regional and global optimizations, such as global value numbering or code motion; these transformations have higher costs and, potentially, higher payoffs than the local and superlocal techniques available to a trace optimizer.

The tradeoffs involved in a specific design depend on the execution environment, the source-language features that produce inefficiency, and the kinds of information gathered in the runtime environment. The design of a hot-method optimizer requires an understanding of the language, the system, the algorithms, and the behavior of the targeted applications.

  1. In a mixed-mode environment, what kinds of data could the emulator gather to facilitate specialization? How might it identify such opportunities and collect the necessary data?

  2. Interrupt-driven profiles can work well in an environment where the dominant fraction of execution occurs in native code. What are some of the difficulties that the compiler writer might encounter using interrupt-driven profiles in a mixed-mode environment?

The previous sections introduce the major issues that arise in the design of a runtime optimizer. To build such a system, however, the compiler writer must make myriad design decisions, most of which have an impact on the effectiveness of the system. This section explores several major topics that arise in the literature that surrounds JIT compilation. Each of them has a practical impact on system design. Each of them can change the overall efficacy of the system.

AOT compilers typically offer the end user a choice among multiple levels of optimization. This feature allows the user, in theory, to use stronger optimization in places where it matters, while saving on compile time in places where the additional optimization makes little difference.

A JIT-based system might provide multiple levels of optimization for several reasons.

Because the elapsed time for application execution includes the JIT’s execution, the JIT writer may decide to include in the standard compilation only those optimizations that routinely produce improvements.

The system may find that a native-code fragment executes often enough to justify more extensive analysis and optimization, which requires more JIT time and saves more runtime.

If the JIT performs speculation based on runtime information, such as types and classes, the JIT may later need to deoptimize the code, which suggests a lower level of optimization.

For all these reasons, some runtime optimization systems have implemented multiple leve

In practice, we know few developers who consider compile time when selecting an optimization level. If the system discovers a loop with a large iteration count, it might apply loop-specific optimizations, such as unrolling, strength reduction, or code motion. To ensure that those changes have immediate effect, it could perform on-stack replacement (see Section 14.5.2).

If the system finds that one method accounts for a significant fraction of interrupt-based profile points, it might apply deeper analysis and more intense optimization. For example, it might inline calls, perform analyses to disambiguate types and classes, and re-optimize.

In either of these scenarios, a JIT with multiple levels of optimization needs a clear set of policies to govern when and where it uses each level of optimization. One key part of that strategy will be a mechanism to prevent the JIT from trying to change the optimization level too often—driving up the JIT costs without executing the code enough to amortize the costs.

A method-level JIT can encounter a situation in which one of the profile counters crosses its threshold during an execution of a long-running method. For example, consider a method with a triply nested loop that has iteration counts of 100 at each level. With a threshold of 10,000, the counter on the inner loop would trigger compilation after just one percent of the iterations.

The counter shows that the method is hot and should be optimized. If the system waits until the next call to “install” the optimized code, it will run the current code for the rest the current invocation. In the triply nested loop, the code would run 99 percent of the iterations after the counter had crossed the threshold for optimization.

To avoid this missed opportunity, the system could pause the execution, optimize and compile the code, and resume the execution with the improved code. This approach capitalizes on the speed of the compiled code for the majority of the loop iterations. To resume execution with the newly optimized code, however, the system must map the runtime state of the paused execution into the runtime state needed by the newly optimized code.

This approach, optimizing the procedure in a way that the current invocation can continue to execute, is often called on-stack code replacement. The JIT builds code that can, to the extent possible, execute in the current runtime environment. When it cannot preserve the values, it must arrange to map values from the current environment into the new environment.

The JIT can use its detailed knowledge of the old code to create the new environment. It can generate a small stub to transform the current

In effect, the system behaves as if a long-running method has a higher threshold to trigger compilation.

On-stack code replacement A technique where the runtime system pauses execution, JIT compiles the executing procedure, and resumes execution with the newly compiled code environment-values in registers plus the current activation record-into the environment need by the new code.

■ The stub may need to move some values. The storage map of the new code may not match the storage map of the old code.

■ The stub may need to compute some values. Optimizations such as code motion or operator strength reduction may create new values that did not exist in the original code.

■ The stub may be able to discard some values. The state of the original code may contain values that are dead or unused in the new code.

The stub runs once, before the first execution of the new code. At that point, it can be discarded. If the JIT runs in a separate thread, as many do, the system needs some handshaking between the JIT and the running code to determine when it should switch to the new code.

The compiler writer has several ways to reduce the complexity of on-stack replacement.

■ She can limit the number of points in the code where the system can perform replacement. The start of a loop iteration is a natural location to consider. Execution of the next iteration begins after compilation and state mapping.

■ She can simplify the state-mapping problem by limiting the set of optimizations that the JIT uses when compiling for on-stack replacement. In particular, the JIT might avoid techniques that require significant work to map the old environment into the new one.

Techniques that create compensation code or introduce new values can complicate the mapping. Examples include code motion, software pipelining, and inline substitution.

The implementation of on-stack replacement ties in a fundamental way to the interfaces between emulated and compiled codes and their runtime environments. The details will vary from system to system. This strategy has the potential to provide significant improvement in the performance of long-running methods.

To avoid confusion, we will refer to the JIT’s cache as a code cache and to processor caches as hardware caches.

Almost all JIT-based systems build and maintain a code cache-a dedicated, software-managed block of memory that holds JIT-compiled code. The JIT writer must design policies and build mechanisms to manage the code cache. Conceptually, code caches blend the problems and policies of a hardware cache and a software-managed heap.

■ Hardware caches determine an object’s placement by an arithmetic mapping of virtual addresses to physical addresses. In a heap, software searches for a block of free space that will hold the object. Code caches are closer to the heap mod ■ Hardware caches deal with fixed sized blocks. Heaps deal with requests for arbitrarily sized blocks, but often round those requests to some common sizes. Code caches must accommodate blocks of native code of different sizes.

■ Hardware caches use automatic, policy-based eviction schemes, typically informed by the pattern of prior use. Heaps typically run a collection phase to find blocks that are no longer live (see Section 6.6.2). Code caches use policies and mechanisms similar to hardware caches.

Most JIT-based systems have a separate code cache for each process or each thread. Some JIT writers have experimented with a global code cache, to allow the reuse of JIT compiled code across processes. The primary benefit from these designs appears to be a reduction in overall memory use; they may provide better performance for a multitasked environment on a limited memory system. When these systems find cross-process sharing, they also avoid reinvoking the JIT on previously compiled code, which can reduce overall runtimes.

The use of a limited-size code cache suggests that the standard virtual-memory paging mechanism is either too slow or too coarse-grained to provide efficient support for the JIT-compiled code. Use of a limited-size cache also implies that a code-cache eviction will discard the JIT-compiled code; delinking it from the executing program and necessitating either emulation or a recompilation if it is invoked in the future.

When the JIT compiles code, it must write that code into the code cache. If the cache management software cannot find a block of unused memory large enough to hold the code, it must evict another segment from the cache.

Replacement in the code cache differs from replacement in a hardware cache. A set-associative hardware cache determines the set to which the new block maps and evicts one of the set’s blocks. The literature suggests evicting the least recently used (LRU) block; many hardware caches use or approximate LRU replacement.

Code cache management algorithms need to evict enough segments to create room for the newly compiled code. In a hardware cache, eviction involves a single fixed-size line. In a software-managed code cache, allocation occurs at the granularity of the segment of compiled code (a trace, a method, or multiple methods). This complicates both the policy and the implementation of the replacement algorithm.

The cache management software should evict from the code cache one or more segments that have not been used recently. The evicted segments

If virtual memory is fast enough, the system can make the cache large and let the paging algorithms manage the problem.

A direct-mapped hardware cache has a set size of one.

must free enough space to accommodate the new code without wasting “too much” space. Choosing the LRU segment might be a good start, but the potential need to evict multiple segments complicates that decision. If the new code requires eviction of multiple segments, those segments must be adjacent. Thus, implementing an LRU mechanism requires some additional work.

The final constraint on replacement is that the algorithms must be fast; any time spent in the replacement algorithms adds to the application’s running time. Creative engineering is needed to minimize the cost of choosing a block to evict and of maintaining the data structures to support that decision.

Repeated allocation and replacement can fragment the space in a code cache. Collected heaps address fragmentation with compaction; uncollected heaps try to merge adjacent free blocks. Code caches lack the notion of a free command; in general, it is unknowable whether some code fragment will execute in the future, or when it will execute.

If the system executes in a virtual-memory environment, it can avoid some of the complication of managing fragmentation by using more virtual address space than allocated memory. As long as the code cache’s working set remains within the intended cache size, the penalty for using more virtual address space should be minimal.

14.5.4 Managing Changes to the Source Code

Section titled “14.5.4 Managing Changes to the Source Code”

This feature is not new. Both APL in the 1960s and Smalltalk in the 1970s had features to edit source code. Those systems, however, were built on interpreters. This feature is not new. Both APL in the 1960s and Smalltalk in the 1970s had fea-

Some languages and systems allow runtime changes to an application at the source-code level. Interpreted environments handle these changes relatively easily. If the runtime environment includes JIT-compiled code, the system needs a mechanism to recognize when a change invalidates one or more native-code fragments, and to replace or recompile them.

The runtime system needs three mechanisms. It must recognize when change occurs. It must identify the code and data that the change affects. Finally, it must bring the current runtime state into agreement with the new source code.

The system must know when the underlying code has changed. The most common way to capture changes is by restricting the mechanisms for making a change. For example, JAVA code changes require the class loader; in APL, code changes involved use of the quote-quad operator. The interface.at allows the change can alert the system. Identify Scope of Change

The system must understand where the changes occur. If the text of a procedure fee changes, then native code for fee is undoubtedly invalid. The system needs a map from a procedure name to its native-code implementation. The more subtle issues arise when a change in fee affects other procedures or methods.

If, for example, the JIT previously inlined fee into its caller foe, then the change to fee also invalidates the prior compilation of foe. If fee is a good target for inline substitution-say, its code size is smaller than the standard linkage code-then a change to fee might trigger a cascade of recompilation. The map from procedure names to code bodies becomes multivalued.

Interface changes to a method, such as changing the parameters, must invalidate both the changed procedure and all of the procedures that call it. Details in the precall and postreturn sequences are inferred from the interface; if it changes, those sequences likely change, too.

Recompiling Changed Code

At a minimum, the system must ensure that future calls to a method execute the most recent code. In a mixed-mode environment, it may suffice to delete the JIT-compiled code for a changed method and revert to interpreting the VM code. When the method becomes hot again, the system will compile it. In a native-code environment, the system must arrange for the new code to be compiled-either aggressively or at its next call.

To simplify recompilation, the JIT writer might add a level of indirection to each call. The precall sequence then refers to a fixed location for the callee; the JIT stores a pointer to the code body at that location. The extra indirection avoids the need to find all of the callers and update their code pointers. To relink the method, the JIT simply overwrites the one code pointer.

In the case where the changed code invalidates compilations of other procedures, the number of invalidations can rise, but the same basic mechanisms should work.

Changes to Declarations

Runtime changes to the source code introduce a related problem-one that arises in both interpreted and compiled implementations. If the source code can change, then the definitions of data objects can change. Consider, for example, a change that adds a new data member to a class. If that class already has instantiated objects, those objects will lack the new data member. The source language must define how to handle this situation, but in the Similar problems arise with interprocedu-ral optimization in an AOT compiler (see Section 8.7.3).

worst case, the system might need to find and reformat all of the instantiated instances of the class—a potentially expensive proposition.

To simplify finding all of the objects in a class, the system might link them together. Early SMALLTALK systems exhaustively searched memory to find such objects; the limited memory on those systems made that approach feasible.

Just-in-time compilation systems make optimization and code generation decisions at runtime. This approach can provide the JIT compiler with access to more precise information about names, values, and bindings. That knowledge, in turn, can help the JIT specialize the code to the actual runtime environment.

JIT systems operate under strict time constraints. Well-designed and well-built systems can provide consistent improvements. The speedups from the JIT must compensate for the time spent gathering information, making decisions, and compiling code. Thus, JIT writers need a broad perspective on language implementation and a deep knowledge of compilation and optimization techniques.

Despite the long history of runtime optimization, the field remains in flux. For example, one of the most heavily used JITs, Google’s V8 JAVASCRIPT JIT, was originally written as a native-code, compile-on-call system. Experience led to a reimplementation that uses a mixed-mode, hot-method approach. The primary justification for this change given in the literature was to reduce code space and startup time; the hot-method version also avoided parsing unused code. Changes in languages, runtime environments, and experience have driven work in runtime optimization over the last decade. We anticipate that this field will continue to change for years to come.

Runtime compilation has a long history. McCarthy included a runtime compilation facility in his early LISP system so that it could provide efficient execution of code that was constructed at runtime—a direct consequence of LISP’s unified approach to code and data [266].

Thompson used an “edit-time” compilation of regular expressions into naive code for the IBM 7094 to create a powerful textual search tool for his port of editor [345]; Section 2.4.2 describes the underlying construction. Hansen built his Adaptive Fortran system to explore the practicality and profitability of runtime optimization [188]. It supported a subset of FORTRAN IV and a small set of optimizations. He modeled the behavior of his system against widely known FORTRAN compilers of the time. His dissertation includes significant discussion on how to estimate the benefits of an optimization and how to trigger the runtime optimizations.

The Deutsch-Schiffman Smalltalk-80 implementation, built for an early Sun Microsystems workstation, demonstrated the potential of runtime compilation for improving dynamic languages [137]; contemporary implementations that relied on interpreting Smalltalk bytecode ran more slowly.

The HotSpot Server Compiler [288] and Dynamo [32] were widely recognized and influential systems. HotSpot influenced design decisions in JIT-based systems for a decade or more. Dynamo inspired a generation of work on problems that ranged from code-cache management to software dynamic translation.

Most method-level optimizers apply some form of global value numbering. These algorithms range from global extensions of the ideas in local value numbering [59,167] through algorithms that build on Hopcroft’s DFA minimization algorithm [90,312] to implementations of lazy code motion (see the notes for Chapter 10).

The time constraints that arise in JIT compilation have encouraged the use of efficient algorithms. Tree-pattern matching instruction selectors can be hyper-efficient: using five to ten compile-time operations per emitted operation [162,163,297]. Linear scan register allocation avoids the expensive part of a full-fledged coloring allocator: building the interference graph [296]. In an environment where many methods are small and do not require spill code, linear scan works well. The HotSpot Server Compiler used interference graph trimming to reduce the cost of a full-fledged coloring allocator [93].

  1. Consider again the plot in Fig. 14.1 (JAVA scaling with and without the JIT). How might changes in the threshold for JIT compilation affect the behavior of the JIT-enabled curve, particularly at the lower end of the curve, shown in panel (b)?

  2. Write pseudocode for a backward pass over an acyclic trace that discovers dead and partially dead operations. Assume that the JIT has LIVE information at each exit from the trace.

How might the JIT obtain LIVE information for the trace exits?

  1. One consideration in the design of a hot-trace optimizer is how to handle intermediate entries into a trace. The design in Section 14.3 ignores intermediate entries, with the effect that multiple copies of some blocks are made.

As an alternative, the compiler writer could have the trace-building algorithm split the trace at an intermediate entry. This strategy would generate an optimized trace for the portion before the intermediate entry and an optimized trace for the portion after the intermediate entry. It would then directly link the former part to the latter part.

a. How might the trace-building algorithm recognize that a block is an intermediate entry point? b. What kinds of JIT optimizations might have reduced effectiveness as a result of splitting traces around intermediate entry points?

  1. If the trace optimizer has a bounded code cache and it fills that cache, it may need to evict one or more traces.

a. What complications do linked traces introduce? b. What approaches can the code-cache management algorithms take to managing the eviction of linked traces?

  1. When a system with a hot-method optimizer discovers that some method has triggered too many recompilations, it may decide to de-optimize the method.

The JIT could treat individual call sites differently, linking each call site to an appropriately optimized code body for the method.

a. What information should the system gather to enable such call-site specific optimization and deoptimization? b. What additional runtime data structures might the JIT need in order to implement such call-site specific optimization? c. One obvious cost of such a scheme is space in the code cache. How might the compiler writer limit the proliferation of variant code bodies for a single method?

  1. Some hot-method JITs compile code in a separate thread, asynchronously. What advantages might this offer to the end user? What disadvantages might it create?

  2. Deoptimization must deal with the results of inline substitution. Suppose the JIT has inlined fie into fee, and that it later decides that it must deoptimize fee. What strategies can the JIT implement to simplify deoptimization of a method that includes inlined code?

Assume, for the moment, that code-cache space is not an issue. 8. Ahead-of-time (AOT) compilers choose which procedures to inline based on some combination of static analysis and profile data from a prior run on “representative” data. By contrast, a JIT decides to inline a procedure based almost entirely on runtime profile information. a. Suggest three heuristics that a hot-method JIT might use to determine whether or not to inline the callee at a specific call site. b. What kinds of data can the runtime system gather to help in the decision of whether or not to inline a specific call site? c. Contrast your strategies, and the results you expect from them, with the results you expect from an AOT compiler. Appendix ILOC A.1 INTRODUCTION ILOC is a linear assembly code for a simple abstract RISC machine. The ILOC used in this book is a simplified version of the intermediate representation (IR) that was used in the Massively Scalar Compiler Project (MSCP) at Rice University. For example, ILOC as defined here assumes just two base data types, an integer of unspecified length, and a single character. In the MSCP compiler, the IR supported a much broader set of data types. The ILOC abstract machine has an unlimited number of registers. It has register-to-register operations; load and store operations; comparisons; and branches. It supports four memory address modes: direct, address-immediate, address-offset, and immediate. Source operands are read at the start of the cycle in which the operation issues. Result operands are defined at the end of the cycle in which the operation completes. Other than its instruction set, the details of the machine are left unspecified. Most of the examples in this book assume a simple machine, with a single functional unit that executes ILOC operations in their order of appearance. When other configurations are used, we discuss them explicitly. An ILOC program consists of a sequential list of instructions, as follows: IlocProgram → InstructionList InstructionList → Instruction | Instruction InstructionList An instruction consists of one or more operations, with an optional label. Instruction → OperationList | label : OperationList A label is an alphanumeric string, ([A-Z] | [a-z]) ([A-Z] | [a-z] | [0-9])*. A colon follows the label. If the code needs multiple labels at some point, we insert labeled nop instructions at the appropriate location. An OperationList consists of either a single Operation, or a list of Operations surrounded by square brackets and separated by semicolons. 758 ILOC

OperationList→ Operation|[ ListOfOps ]

ListOfOps→ Operation| Operation; ListOfOps

Operation→ NormalOp| ControlFlowOp

An ILOC operation corresponds to a single machine-level operation. An Operation is either a NormalOp that performs computation or data movement, or it is a ControlFlowOp used to change the flow of control in the program.

NormalOps consist of an opcode, a list of comma-separated source operands, and a list of comma-separated result operands. The sources are separated from the results by the symbol=>, pronounced “into.”

NormalOp→ Opcode OperandList→OperandList

OperandList→Operand| Operand, OperandList

Operand→ register| number| label

Unfortunately, as in a real assembly language, the relationship between an opcode and the form of its operands is not systematic. The easiest way to specify the form of the operands for each opcode is in a tabular form. The tables in Section A.6 show the full set of opcodes and their operands for each of the ILOC operations that appear in the book.

Operands may be one of three types: register, number, or label. The type of each operand is determined by the opcode and the position of the operand in the operation. In the examples, we use both numerical(r10) and symbolic(rj) names for registers. Numbers are simple positive integers. Labels are, as defined earlier, alphanumeric strings,([A-Z]|[a-z])([A-Z]|[a-z]|[0-9])*.

While the definition of a label allows r10 and ri as labels, we avoid labels that could have other interpretations.

Arithmetic operations have one result; some of the store operations have two results, as do all of the branches.

As an example, storeAI, the address-immediate store operation, has one source operand(a register) and two result operands(a register and a number). The operation storeAI ri⇒rj,4r_{i}\Rightarrow r_{j},4 adds 4 to the value in rjr_{j} to form an address and stores the value rir_{i} into the memory location at that address. It performs the action: MEMORY(rj+4)←CONTENTS(rj).

ILOC

The ILOC code used in examples throughout the text follows a simple set of naming conventions.

  1. Memory offsets for variables are represented symbolically by prefixing the variable name with the @ character.
  2. The user can assume an unlimited supply of registers. These are named with simple integers, as in r₁₇₇₆, or with symbolic names, as in rᵢ.
  3. The register rᵒᵣₚ is reserved for a pointer to the current activation record. Thus, the operation 1oadAI rᵒᵣₚ, @x ⇒ r₁ loads an integer from offset @x in the current activation record into r₁.

ILOC comments begin with the string // and continue until the end of a line. We assume that these are stripped out by the scanner.

The first major category of operations in ILOC is the set of basic computational operations. ILOC provides these operations in both a three-address, register-to-register format and a two-register format that has an immediate constant as its second source operand.

OpcodeSourcesResultsMeaning
addr₁, r₂r₃r₁ + r₂ ⇒ r₃
subr₁, r₂r₃r₁ - r₂ ⇒ r₃
multr₁, r₂r₃r₁ × r₂ ⇒ r₃
divr₁, r₂r₃r₁ ÷ r₂ ⇒ r₃
lshiftr₁, r₂r₃r₁ ≪ r₂ ⇒ r₃
rshiftr₁, r₂r₃r₁ ≫ r₂ ⇒ r₃

The first four ocodes implement standard arithmetic operations. The latter two opcodes implement logical shift operations.

A real ILOC processor or a full-fledged compiler would need more than one arithmetic data type. This would lead to typed opcodes or to polymorphic opcodes. The MSCP compiler had distinct arithmetic operations for various lengths of integer and floating-point numbers, as well as for pointers.

The next group of opcodes specify register-immediate operations. Each of them takes as input a register and an immediate constant value. The noncom- 760 ILOC mutative operations have two distinct forms to allow the constant as either the first or second value in the operation. For example, rsubI subtracts the value in r1 from the immediate constant c2.

OpcodeSourcesResultsMeaning
addIr1,c2r3r1+c2→r3
subIr1,c2r3r1-c2→r3
rsubIr1,c2r3c2-r1→r3
multIr1,c2r3r1×c2→r3
divIr1,c2r3r1÷c2→r3
rdivIr1,c2r3c2÷r1→r3
lshiftIr1,c2r3r1<<c2→r3
rshiftIr1,c2r3r1>>c2→r3

A register-immediate operation is useful for three distinct reasons.

It lets the compiler or the assembly-level programmer use a small constant directly in the operation. Thus, it decreases demand for registers. It may also eliminate an operation to load the constant into a register.

It “reads” the constant from the instruction stream and, thus, from the instruction cache. Most processors have separate caches and data paths for instructions and for data; thus, the immediate operation uses fewer resources on the data-side of the memory interfaces.

The immediate form of the operation records the value of the constant in a visible and easily accessible way, which ensures that optimization and code generation can see and use the value.

The second major category of operations in ILOC allow the compiler or the assembly-level programmer to specify data movement. We include two specialized operations in this section: a conditional move operation and a representation for a ϕ\phi -function (see Section 4.6.2).

ILOC provides a set of operations to move values between memory and registers: load and store operations. The examples in the book limit themselves to integer and character data; a complete version of ILOC would need load and store operations for a much broader variety of base types. To produce efficient code, a compiler’s back end must make effective use of the address modes provided on load and store operations. ILOC provides a variety of address modes in both the load and store operations.

OpcodeSourcesResultsMeaning
loadr₁r₂MEMORY(r₁) ⇒ r₂
loadAIr₁, c₂r₃MEMORY(r₁+c₂) ⇒ r₃
loadA0r₁, r₂r₃MEMORY(r₁+r₂) ⇒ r₃
cloadr₁r₂character load
cloadAIr₁, c₂r₃character loadAI
cloadA0r₁, r₂r₃character loadA0
loadIc₁r₂c₁ ⇒ r₂

The load operations differ in the address modes that they support:

  • The direct loads, load and cload, use the value in r₁ as an address.
  • The address-immediate loads, loadAI and cloadAI, add the immediate constant and the value in the source register to form the address.
  • The address-offset loads, loadA0 and cloadA0, add the contents of the two source registers to form the address.
  • The immediate load, loadI, moves the constant into the target register.

A complete, ILOC-like IR with multiple base types for values should have an immediate load for each distinct base type.

The store operations support the same address modes as the load operations.

OpcodeSourcesResultsMeaning
storer₁r₂r₁ ⇒ MEMORY(r₂)
storeAIr₁r₂, c₃r₁ ⇒ MEMORY(r₂+c₃)
storeA0r₁r₂, r₃r₁ ⇒ MEMORY(r₂+r₃)
cstorer₁r₂character store
cstoreAIr₁r₂, c₃character storeAI
cstoreA0r₁r₂, r₃character storeA0

ILOC has no store immediate operation. 762 ILOC

To move values directly between registers ILOC includes a set of register-to-register copy operations.

OpcodeSourcesResultsMeaning
i2ir1r2r1⇒r2 for integer values
c2cr1r2r1⇒r2 for character values
c2ir1r2convert character to integer
i2cr1r2convert integer to character

i2i and c2c simply copy a value from one register to another. By contrast,c2i and i2c convert the value to another type as part of the copy operation.

Many ISAs provide a conditional move operation that selects a value from one of two source registers based on a Boolean value in a third register. To enable examples that discuss this kind of operation, ILOC includes four-operand conditional move operations for integers and characters.

Architects include conditional move operations in an ISA to let the compiler avoid branches on particularly simple conditional constructs.

OpcodeSourcesResultsMeaning
c_i2irb,r1,r2r3r1⇒r3, if rb= true
r2⇒r3, otherwise
c_c2crb,r1,r2r3r1⇒r3, if rb= true
r2⇒r3, otherwise

When a compiler builds SSA form, it must represent ϕ\phi -functions. In ILOC,the natural way to write a ϕ\phi -function is as an ILOC operation:

phiri,rj,rk⇒rm\text{phi}\quad\text{r}_{i},\quad\text{r}_{j},\quad\text{r}_{k}\Rightarrow\text{r}_{m}

for the ϕ\phi -function rm←ϕ(ri,rj,rk)r_{m}\leftarrow\phi\left(r_{i},r_{j},r_{k}\right) . Because of the nature of SSA form, the ph1 o c ation may take an arbitrary number of sources. It always defines a single target register. Representing ϕ\phi - functions in this way poses some interesting engineering issues in the implementation of the IR.

Control - flow operations allow the ILOC program to sequence the execution of labeled blocks of operations. ILOC includes jumps, comparisons, and conditional branches. To facilitate the discussion in Section 7.4.2, ILOC also includes a syntax to represent predicated operations.

While control - flow operations still fit the three - address form of most ILOC operations, they vary in the meanings of their various operands. As a visual cue, the operations that involve a transfer of control (or an assignment to the program counter) use a single arrow, →, to separate sources from targets.

ControlFlowOp → jumpI → label | jump → register | Branch register → label, label | Compare register, register ⇒ register

ILOC provides two styles of Branch and Compare operations so that Section 7.4.2 can discuss translation of control - flow constructs for each of them.

ILOC has both jump immediate and jump to register operations. Most examples use an immediate jump because it exposes the destination label.

OpcodeSourcesResultsMeaning
jumpI—l₁l₁ → PC
jump—r₁r₁ → PC

The jump operation is ambiguous because the target address is in a register. The compiler may be unable to deduce the correct set of possible target labels for a jump. This effect complicates CFG construction and can degrade the quality of information that data - flow analysis can derive. For these reasons, we prefer jumpI over jump whenever possible and practical.

Sometimes the compiler must generate a jump rather than a jumpI. For these situations, ILOC includes a pseudooperation that lets the compiler record the set of possible labels for a jump operation. The tbl pseudooperation has two arguments, a register and an immediate label. 764 ILOC tbl r₁, l₂ — r₁ might hold l₂

A tbl operation can occur only after a jump. The sequence

jump → rᵢ

tbl rᵢ, L01

tbl rᵢ, L03

tbl rᵢ, L05

tbl rᵢ, L08

asserts that the jump targets one of L01, L03, L05, or L08, and no other label.

All branches in ILOC have a label for the true path and the false path. ILOC does not have the notion of a “fall-through” path.

ILOC supports two models for branches. The standard ILOC model, shown in Fig. A.1(a), uses a simple conditional branch, cbr, and a set of six Boolean-valued comparison operations. cbr tests the Boolean value produced by a comparison and branches to the appropriate immediate label.

The second branch model, shown in panel (b), has one comparison operation and a set of six conditional branches. It models the situation on an ISA where comparison sets a “condition code” (see Section 7.4.2). This model pushes the choice of relational operator into the branch operation.

In the examples, we designate the target of comp as a condition-code register by writing it as ccᵢ. The comp operation writes a value drawn from the set {LT,LE,EQ,GE,GT,NE,} into ccᵢ. The conditional branch has a variant for each of these six values.

Predication is another feature introduced to let the compiler or assembly programmer avoid a conditional branch. A predicated operation takes a Boolean value that determines whether or not the operation’s result takes effect. In ILOC, a predicated operation is written as follows:

(rp) ? add r₁,r₂ ⇒ r₃

This notation indicates that r₃ receives the sum of the values of r₁ and r₂ if rp contains the value true. If rp does not contain true, then r₃ is unchanged.

In principle, any ILOC operation can be predicated. In practice, predication does not make sense for some operations, such as a phi or a jump.(A predi-ated jump is just a cbr whose false path is the next operation.)

OpcodeSourcesResultsMeaning
cmp_LTr₁, r₂r₃true ⇒ r₃
false ⇒ r₃
cmp_LEr₁, r₂r₃true ⇒ r₃
false ⇒ r₃
cmp_EQr₁, r₂r₃true ⇒ r₃
false ⇒ r₃
cmp_GEr₁, r₂r₃true ⇒ r₃
false ⇒ r₃
cmp_GTr₁, r₂r₃true ⇒ r₃
false ⇒ r₃
cmp_NEr₁, r₂r₃true ⇒ r₃
false ⇒ r₃
cbrr₁l₂, l₃l₂ → PC
l₃ → PC

(a) The Standard Branch Syntax

OpcodeSourcesResultsMeaning
compr₁, r₂cc₃sets cc₃
cbr_LTcc₁l₂, l₃l₂ → PC
l₃ → PC
cbr_LEcc₁l₂, l₃l₂ → PC
l₃ → PC
cbr_EQcc₁l₂, l₃l₂ → PC
l₃ → PC
cbr_GEcc₁l₂, l₃l₂ → PC
l₃ → PC
cbr_GTcc₁l₂, l₃l₂ → PC
l₃ → PC
cbr_NEcc₁l₂, l₃l₂ → PC
l₃ → PC

(b) Branch Syntax to Model an ISA with Condition Codes

The following pages contain summary tables that list all of the ILOC operations and their meanings. They are provided for reference.

OpcodeSourcesResultsMeaning
nopnonenonesingle cycle, side-effect free operation
addr₁, r₂r₃r₁ + r₂ ⇒ r₃
subr₁, r₂r₃r₁ - r₂ ⇒ r₃
multr₁, r₂r₃r₁ × r₂ ⇒ r₃
divr₁, r₂r₃r₁ ÷ r₂ ⇒ r₃
addIr₁, c₂r₃r₁ + c₂ ⇒ r₃
subIr₁, c₂r₃r₁ - c₂ ⇒ r₃
rsubIr₁, c₂r₃c₂ - r₁ ⇒ r₃
multIr₁, c₂r₃r₁ × c₂ ⇒ r₃
divIr₁, c₂r₃r₁ ÷ c₂ ⇒ r₃
rdivIr₁, c₂r₃c₂ ÷ r₁ ⇒ r₃
lshiftr₁, r₂r₃r₁ ≪ r₂ ⇒ r₃
lshiftIr₁, c₂r₃r₁ ≪ c₂ ⇒ r₃
rshiftr₁, r₂r₃r₁ ≫ r₂ ⇒ r₃
rshiftIr₁, c₂r₃r₁ ≫ c₂ ⇒ r₃
andr₁, r₂r₃r₁ ∧ r₂ ⇒ r₃
andIr₁, c₂r₃r₁ ∧ c₂ ⇒ r₃
orr₁, r₂r₃r₁ ∨ r₂ ⇒ r₃
orIr₁, c₂r₃r₁ ∨ c₂ ⇒ r₃
xorr₁, r₂r₃r₁ xor r₂ ⇒ r₃
xorIr₁, c₂r₃r₁ xor c₂ ⇒ r₃
OpcodeSourcesResultsMeaning
loadIc₁r₂c₁ ⇒ r₂
loadr₁r₂MEMORY(r₁) ⇒ r₂
loadAIr₁, c₂r₃MEMORY(r₁+c₂) ⇒ r₃
loadAOr₁, r₂r₃MEMORY(r₁+r₂) ⇒ r₃
cloadr₁r₂character load
cloadAIr₁, c₂r₃character loadAI
cloadAOr₁, r₂r₃character loadAO
storer₁r₂r₁ ⇒ MEMORY(r₂)
storeAIr₁r₂, c₃r₁ ⇒ MEMORY(r₂+c₃)
storeAOr₁r₂, r₃r₁ ⇒ MEMORY(r₂+r₃)
cstorer₁r₂character store
cstoreAIr₁r₂, c₃character storeAI
cstoreAOr₁r₂, r₃character storeAO
i2ir₁r₂r₁ ⇒ r₂ for integers
c2cr₁r₂r₁ ⇒ r₂ for characters
c2ir₁r₂convert character to integer
i2cr₁r₂convert integer to character
phir₁, r₂, r₃r₄φ(r₁, r₂, r₃) ⇒ r₄
with arbitrary number of sources
OpcodeSourcesResultsMeaning
jump—r₁r₁ ⇒ PC
jumpI—l₁l₁ ⇒ PC
tblr₁, l₂—r₁ might hold l₂

The following pages contain summary tables that list all of the ILOC operations and their meanings. They are provided for reference.

OpcodeSourcesResultsMeaning
nopnonenonesingle cycle, side-effect free operation
addr₁, r₂r₃r₁ + r₂ ⇒ r₃
subr₁, r₂r₃r₁ - r₂ ⇒ r₃
multr₁, r₂r₃r₁ × r₂ ⇒ r₃
divr₁, r₂r₃r₁ ÷ r₂ ⇒ r₃
addIr₁, c₂r₃r₁ + c₂ ⇒ r₃
subIr₁, c₂r₃r₁ - c₂ ⇒ r₃
rsubIr₁, c₂r₃c₂ - r₁ ⇒ r₃
multIr₁, c₂r₃r₁ × c₂ ⇒ r₃
divIr₁, c₂r₃r₁ ÷ c₂ ⇒ r₃
rdivIr₁, c₂r₃c₂ ÷ r₁ ⇒ r₃
lshiftr₁, r₂r₃r₁ << r₂ ⇒ r₃
lshiftIr₁, c₂r₃r₁ << c₂ ⇒ r₃
rshiftr₁, r₂r₃r₁ >> r₂ ⇒ r₃
rshiftIr₁, c₂r₃r₁ >> c₂ ⇒ r₃
andr₁, r₂r₃r₁ ∧ r₂ ⇒ r₃
andIr₁, c₂r₃r₁ ∧ c₂ ⇒ r₃
orr₁, r₂r₃r₁ ∨ r₂ ⇒ r₃
orIr₁, c₂r₃r₁ ∨ c₂ ⇒ r₃
xorr₁, r₂r₃r₁ XOR r₂ ⇒ r₃
xorIr₁, c₂r₃r₁ XOR c₂ ⇒ r₃
ILOC 769
OpcodeSourcesResultsMeaning
loadIc_1r_2c_1 => r_2
loadr_1r_2MEMORY(r_1) => r_2
loadAIr_1, c_2r_3MEMORY(r_1 + c_2) => r_3
loadAOr_1, r_2r_3MEMORY(r_1 + r_2) => r_3
cloadr_1r_2character load
cloadAIr_1, c_2r_3character loadAI
cloadAOr_1, r_2r_3character loadAO
storer_1r_2r_1 => MEMORY(r_2)
storeAIr_1r_2, c_3r_1 => MEMORY(r_2 + c_3)
storeAOr_1r_2, r_3r_1 => MEMORY(r_2 + r_3)
cstorer_1r_2character store
cstoreAIr_1r_2, c_3character storeAI
cstoreAOr_1r_2, r_3character storeAO
i2ir_1r_2r_1 => r_2 for integers
c2cr_1r_2r_1 => r_2 for characters
c2ir_1r_2convert character to integer
i2cr_1r_2convert integer to character
phir_1, r_2, r_3r_4phi(r_1, r_2, r_3) => r_4 with arbitrary number of sources

The bottom conditional-move rows are partially obscured in the scan image and should be verified from a cleaner source before being treated as verbatim. 768 ILOC

Standard Conditional Branch Syntax

OpcodeSourcesResultsMeaning
cmp_LTr₁, r₂r₃true ⇒ r₃
false ⇒ r₃
if r₁ < r₂
otherwise
cmp_LEr₁, r₂r₃true ⇒ r₃
false ⇒ r₃
if r₁ ≤ r₂
otherwise
cmp_EQr₁, r₂r₃true ⇒ r₃
false ⇒ r₃
if r₁ = r₂
otherwise
cmp_GEr₁, r₂r₃true ⇒ r₃
false ⇒ r₃
if r₁ ≥ r₂
otherwise
cmp_GTr₁, r₂r₃true ⇒ r₃
false ⇒ r₃
if r₁ > r₂
otherwise
cmp_NEr₁, r₂r₃true ⇒ r₃
false ⇒ r₃
if r₁ ≠ r₂
otherwise
cbrr₁l₂, l₃l₂ → PC
l₃ → PC
if r₁ = true
otherwise

Alternate Conditional Branch Syntax

OpcodeSourcesResultsMeaning
compr₁, r₂cc₃sets cc₃ to one of {LT, LE, EQ, GE, GT, NE}
cbr_LTcc₁l₂, l₃l₂ → PC
l₃ → PC
if cc₃ = LT
otherwise
cbr_LEcc₁l₂, l₃l₂ → PC
l₃ → PC
if cc₃ = LE
otherwise
cbr_EQcc₁l₂, l₃l₂ → PC
l₃ → PC
if cc₃ = EQ
otherwise
cbr_GEcc₁l₂, l₃l₂ → PC
l₃ → PC
if cc₃ = GE
otherwise
cbr_GTcc₁l₂, l₃l₂ → PC
l₃ → PC
if cc₃ = GT
otherwise
cbr_NEcc₁l₂, l₃l₂ → PC
l₃ → PC
if cc₃ = NE
otherwise

A compiler is the sum of its myriad parts. Thus, a successful compiler requires attention to many details. This appendix explores some of the algorithmic and implementation issues that arise in building a compiler. In most cases, these details would distract from the relevant discussion in the body of the text. We have gathered them together into this appendix, where they can be considered as needed.

This appendix focuses on the engineering issues that arise in the design and implementation of the infrastructure to support a compiler. The way that the compiler writer resolves these issues has a large impact on both the speed of the resulting compiler and the ease of extending and maintaining it.

In many applications, it makes sense for the programmer to rely on data-structure implementations from standard libraries. The extraordinary stability of JAVA and the increasing use of PYTHON have made this approach both practical and widespread. However, when a routine executes sufficiently often, the incremental improvement attained from custom-built data structures can be significant. On the scale of a compiler such as GCC or LLVM, the cumulative payoff may well justify the effort of implementing a custom representation for a set, a graph, a map, or another data structure.

As one example of the issues that arise in compilation, consider the size of the compiler’s own data structures. The compiler cannot know the size some of those data structures until it has read the input; thus, the front end must be designed to expand the size of its data structures gracefully in order to accommodate large input files. As a corollary, however, subsequent passes in the compiler should know the approximate sizes needed for most of their internal data structures; the front end can record those sizes for the later passes. If the front end needed 10,000 names in the IR program, the compiler should not begin a later pass with a symbol table sized for 512 names. The header of any external representation of the IR should include a specification of the rough sizes of major data structures.

Similarly, the later passes of a compiler can assume that the IR program presented to them was generated by the compiler. While they should detect all errors, the error messages might be more terse than one would expect in 770 Data Structures

The arrow in ILOC is an example of this principle. It makes the flow of values explicit and eliminates one source of confusion in reading the ILOC code.the front end. A common strategy is to build a validation pass that performs a thorough check on the IR program and can be inserted between other passes for debugging purposes, and to rely on less-strenuous error detection when not debugging the compiler. However, the compiler writers should always remember that they are the people most likely to look at the code between passes. Effort spent to make the external forms of the IR more readable often rewards the very people who invested the time and effort in it.

As a final example, consider the implementation of a sparse graph. This problem arises in optimization and in code generation; both the scheduler’s dependence graph and the register allocator’s interference graph tend to be sparse. The implementor might consider representing a sparse graph with a hash table. While dependence graphs for local scheduling tend to be small(limited by block size), interference graphs can grow large enough to make space efficiency a concern.

The idea is simple. Each edge is a(source, sink) pair. Hashing the pairs provides a quick membership test. Edge-specific storage can be created in the hash-table entry for the edge’s pair. As long as the hash function is well-behaved, this scheme produces a space-efficient representation with good asymptotic time behavior.

However, the compiler writer must take care to use a hash function that works well on the edges. If source and sink are small integers, the hash function may not have that many bits of information to use. From experience[111], hash-based interference graph representations depend heavily on the quality of the hash function.

Many different problems in compilation are formulated in terms that involve sets. They arise at many points in the text, including the subset construction(Chapter 2), the construction of the canonical collection of LR(1) items(Chapter 3), data-flow analysis(Chapters 8 and 9), and worklists such as the ready queue in list scheduling(Chapter 12). In each context, the compiler writer must select an appropriate set representation. In many cases, the efficiency of the algorithm depends on careful selection of a set representation(see, for example, the lDoms-based algorithm in Section 9.5.2).

A fundamental difference between building a compiler and building other kinds of systems software-such as an operating system-is that many problems in compilation can be solved offline. For example, the local register-allocation algorithm in Chapter 13 is better known as Belady’s MIN algorithm for offline page replacement, which has long been used as a standard against which to judge the effectiveness of online page-replacement algorithms. In the operating systems community, the algorithm is of only academic interest because it is an offline algorithm. Since the operating system cannot know what pages will be needed in the future, it cannot use an offline algorithm. In a compiler, the offline algorithm is practical because the compiler can look through the entire block before making any decisions.

The offline nature of compilation allows the compiler writer to use a broad variety of set representations. Many representations for sets have been explored. In particular, offline computation often lets us restrict the members of a set S to a fixed-size universe U(S⊆U). This, in turn, lets us use more efficient set representations than are available in an online situation where the size of U is discovered dynamically.

Common set operations include member, insert, delete, clear, choose-one, cardinality, forall, copy, compare, union, intersect, difference, and complement. A specific application typically uses only a small subset of these operations. The cost of individual set operations depends on the particular representation chosen. In selecting an efficient representation for a particular application, it is important to consider how frequently each type of operation will be used. Other factors to consider include the memory requirements of the set representation and the expected sparsity of S relative to U.

The rest of this section focuses on three set representations that compiler writers often use: ordered linked lists, bit vectors, and sparse sets. The final subsection briefly discusses the role of hashing in set implementation.

In cases in which the size of each set is small, it sometimes makes sense to use a simple linked-list representation. For a set S, this representation consists of a linked list and a pointer to the first element in the list. Each node in the list contains a representation for a single element of S and a pointer to the next element of the list. The final node on the list has its pointer set to a standard value indicating the end of the list. With a linked-list representation, the implementation can impose an order on the elements to create an ordered list. For example, an ordered linked list for the set S={i,j,k},i<j<k might look, conceptually, as follows:

The elements are kept in ascending order. The size of S’s representation is proportional to the number of elements in S, not the size of U. If |S| is much 772 Data Structures

OperationOrdered Linked ListBit VectorSparse Set
memberO(S)
insertO(S)
deleteO(S)
clearO(1)O(U
choose-oneO(1)O(U
cardinalityO(S)
forallO(S)
copyO(S)
compareO(S)
unionO(S)
intersectO(S)
differenceO(S)
complementO(U

■ FIGURE B.1 Asymptotic Time Complexities of Set Operations.

smaller than|U|, the savings from representing just the elements present in S may more than offset the extra cost incurred for a pointer in each element.

The list representation is particularly flexible. Because nothing in the list relies on either the size of U or the size of S, it can be used in situations in which the compiler is discovering U or S or both. Such situations arise in the front end, where the compiler acts before it has seen the entire input, and in places where it translates one name space into another, as in the construction of live ranges in a register allocator.

The table in Fig. B.1 shows the asymptotic complexities of common set operations using this representation. Most of the ordered linked list operations are O(|S|) because it is necessary to walk the linked lists to perform the operations. If deallocation does not require walking the list to free the nodes for individual elements, as in a collected system or an arena-based system, clear takes constant time.

If the size of the universe is unknown but it can can grow reasonably large, the compiler writer can decrease the space overhead from pointers and the allocation overhead by creating nodes that hold multiple set elements. Each node has space for k elements, along with a counter that holds the number of occupied elements. Building a set of n elements then requires ⌈nk⌉\lceil\frac{n}{k}\rceil allocations, ⌈nk⌉+1\lceil\frac{n}{k}\rceil+1 pointers, and ⌈nk⌉+1\lceil\frac{n}{k}\rceil+1 counters, where a set implemented with single-element nodes would take n allocations and n+1 pointers. This scheme does have a cost. Insertion and deletion may need to move more data than they would with single-element nodes. Their asymptotic complexity, however, remains O(|S|). A clever implementation can limit such shuffling to k elements on any insert or delete, at the cost of wasting some space.

The lDoms array used in the fast dominance computation (see Section 9.5.2) is a clever application of the list representation of sets to a special case. In particular, the compiler knows the size of the universe and the number of sets. The compiler also knows that, using ordered sets, the sets have the property that if e∈S1 and e∈S2 then every element after e in S1 is also in S2. Thus, the elements starting with e can be shared. By using an array representation, the element names can be used as pointers, too. Thus, a single array of n elements can represent n sparse sets. It also leads to a fast intersection operator for those sets.

Compiler writers often use bit vectors to represent sets, particularly those used in data-flow analysis (see Sections 8.6.1 and 9.2). For a bounded universe U, a set S⊆U can be represented with a bit vector of length |U|, called the characteristic vector for S. For each i∈U, 0≤i<|U|; if i∈S, the ith element of the characteristic vector equals one. Otherwise, the ith element is zero. For example, the characteristic vector for the set S⊆U, where S={i,j,k}, i<j<k is as follows:

0…010…010…010…0
………………………………………

The bit-vector representation always allocates enough space to represent all elements in U; thus, this representation can be used only in an application where U is known—an offline application.

The table in Fig. B.1 lists the asymptotic complexities of common set operations with this representation. Although many of the operations are O(|U|), they can still be efficient if U is small. A single word holds many elements; the representation gains a constant-factor improvement over representations that need one word per element. Thus, for example, with 64-bit words, any universe of 64 or fewer elements has a single-word representation.

The compactness of the representation carries over into the speed of operations. With single-word sets, many of the set operations become single machine instructions; for example, union becomes a logical-or operation and intersection becomes a logical-and operation. Even if the sets take multiple 774 Data Structures

words to represent, the number of machine instructions required to perform many of the set operations is reduced by a factor of the machine’s word size.

B.2.3 Representing Sparse Sets

For a fixed universe U and a set S U,S is a sparse set if|S| is much smaller than|U|. Some of the sets encountered in compilation are sparse. For example, the LIVEOUT sets used in register allocation are typically sparse. Compiler writers often use bit vectors to represent such sets, due to their efficiency in time and space. With enough sparsity, however, more time-efficient representations are possible, especially in situations in which a large percentage of the operations can be supported in either O(1) or O(|S|)time. By contrast, bit vector sets take either O(1) or O(|U|) time on these operations. If|S| is smaller than|U| by a factor greater than the word size, then bit vectors may be the less efficient choice.

One sparse-set representation that has these properties uses two vectors of length|U| and a scalar to represent the set. The first vector, sparse, holds a sparse representation of the set; the other vector, dense, holds a dense representation of the set. The scalar, next, holds the index of the location in dense where the next new element of the set can be inserted. Of course, next also holds the set’s cardinality.

Neither vector needs to be initialized when a sparse set is created; set membership tests ensure the validity of each entry as it is accessed. The clear operation simply sets next back to zero, its initial value. To add a new element i∈U to S, the code (1) stores i in the next location in dense,(2) stores the value of next in the ith location in sparse, and (3) increments next so that it is the index of the next location where an element can be inserted in dense.

If we began with an empty sparse set S and added elements j, i, and k, in order, where i<j<k, the set would reach the following state:

sparse 0 i j k|U|-1…1…0…2…

dense 0 1 2 3|U|-1 j i k…next 3

Note that the sparse-set representation requires enough space to represent all of U. Thus, it can be used only in offline situations in which the compiler knows the size of U. The sparse set has a concise membership test. The valid entries for an element ii in sparse and dense must point to each other, so element ii is in the set if and only if:

0≤sparse[i]<next0\leq sparse[i] <next and dense[sparse[i]]=idense[sparse[i]] =i

The table in Fig. B.1 lists the asymptotic complexities of common set operations on this representation. Because this scheme includes both a sparse and a dense representation of the set, it achieves some of the advantages of each. Individual elements of the set can be accessed in O(1) time through sparse, while set operations that must traverse the set can use dense to obtain O(|S|) complexity.

Both space and time complexities should be considered when choosing between bit-vector and sparse-set representations. The sparse-set representation requires two vectors of length |U| and a scalar. By contrast, a bit-vector representation requires a single bit-vector of length |U|. As shown in Fig. B.1, the sparse-set representation dominates the bit-vector representation in terms of asymptotic time complexity. However, because of the efficient implementations possible for bit-vector set operations, bit vectors are preferred in situations where S is not sparse. When choosing between the two representations, it is important to consider both the sparsity of the represented set and the relative frequency of the set operations employed.

Mapping textual names, such as source-code names, compiler-generated temporary names, or virtual registers, into the internal names used in a set implementation is a critical aspect of set implementation. One effective way to create this map is with a hash table. Using the external name as the key and the internal name as the value creates an expected-case O(1) map.

A compiler’s IR is its central data structure. The IR, along with associated ancillary data structures, represents the program under translation. The compiler repeatedly traverses those structures, analyzes their contents, and rewrites those contents. Thus, the implementation of the IR plays an important role in the overall efficiency of the compiler.

Chapter 4 presented a broad overview of the kinds of intermediate representations that compilers use. This section focuses on details in the implementation of an IR. Some of the content is common sense; some of it draws on the experience of the authors and their friends in the compiler construction

For a name x, its internal name the position of the bit that .epresents name x in a bit vector set or the index in a sparse set’s dense vector. 776 Data Structures community. Sections B.3.1 and B.3.2 address concerns in the implementation of graphical and linear IRs, respectively.

The compiler writer should pay attention to the overall size of IR programs and to the ease with which the compiler can traverse the IR program. Both concerns affect performance. Using more memory than necessary introduces additional costs-particularly in locality and in garbage collection. In the extreme, it can limit the size of input programs that the compiler can reasonably handle. An IR that is hard to traverse introduces its own inefficiencies.

B.3.1 Graphical Intermediate Representations

Section titled “B.3.1 Graphical Intermediate Representations”

Compilers use a variety of graphical IRs(see Section 4.3). Tailoring a graph’s implementation to the compiler’s specific needs can improve both its usability and its space efficiency. This subsection describes some of the issues that arise in tree and graph implementation.

The obvious representation for a tree, in most languages, is as a collection of nodes connected by pointers. A typical implementation allocates nodes on demand, as it builds the tree. The compiler writer may choose to use multiple sizes of nodes, perhaps with different numbers of children or different data fields. Alternatively, the tree can be built from a single kind of node, allocated to fit the largest possible node.

An alternative representation might use an array of node structures. Links between nodes can be either array indices or pointers(providing the language has an address-of operator). This design forces a one-size-fits-all node, but is otherwise similar to the pointer-based implementation.

Each of these schemes has strengths and weaknesses. The tradeoffs must be evaluated in the context of a given project and its implementation language.

A node and pointer scheme handles arbitrarily large trees in a natural way. An array of node structures scheme requires code to expand the array when the tree grows beyond its initial size.

A node and pointer scheme usually requires an allocation for each node. Arena-based allocation can reduce the cost of deallocation(see the digression on page 312).

The node and pointer scheme has locality that depends entirely on the runtime behavior of the underlying allocator. The array of node structures scheme uses a large block of consecutive memory locations, which keeps successive nodes from interfering with each other in the cache.

The compiler writer should pay attention to the total size of the IR form of a program. Larger IRs often lead to slower compilers; in general, the compiler touches every byte of storage that it allocates. In the extreme, wasting space in the IR can cause locality problems and it can limit the size of the input programs that the compiler can easily handle.

Attention to detail in the IR design can help limit IR size.

  • Represent All Facts Compactly. Names should be converted into small integers in the front end and translated back to strings for debugging or output. Data structures should be laid out to avoid the need for padding (see Section 5.6.5).

  • Represent Only Common Facts in the IR. Relegate facts that are needed in just a few passes or a few operations to ancillary structures. The presence of this extra information can be encoded into another field—for example, in the sign bit of an opcode or node type.

  • Eliminate References to Dead Ancillary Structures. If, in a managed-storage environment, the compiler allocates ancillary structures, it should overwrite any explicit pointers to those structures after they are no longer of use. Retaining such pointers keeps them alive through garbage collection.

To understand IR size, the compiler writer can build an optional reporting capability into the IR abstraction and use it, periodically, to examine IR space efficiency. In our projects, we have often discovered fields that are rarely or never used.

  • The node and pointer scheme may be harder to debug than the array implementation. Programmers typically find array indices more intuitive than memory addresses.

The compiler writer can achieve the easy expansion of a node and pointer scheme while mitigating the allocation cost and locality issues by using a block-contiguous allocation scheme.

A block-contiguous allocator for the tree would use a major allocator and a minor allocator. The minor allocator keeps a free list of available nodes, initialized to an empty list. When the minor allocator is called, it returns a node from the free list, unless that list is empty. The common case can be quite fast. When the free list is empty, it calls the major allocator to obtain a block of memory large enough to hold k nodes. It builds a free list of nodes from that space and then returns one of them to the caller. The tree-building code always calls the minor allocator. 778 Data Structures (a) Node to Represent a For Loop

(b) For Loop Encoded with Binary Nodes

(c) A More Complex Tree

(d) Same Tree Encoded as a Binary Tree

■ FIGURE B.2 Mapping Arbitrary Trees Onto Binary Trees.

A straightforward implementation of abstract syntax trees might support nodes with many different numbers of children. For example, a typical for loop header

for i= 1 to n by 2

might have a node in the with five children, like the one shown in Fig. B.2(a). The node labeled body represents the subtree for the code in the body of the for loop.

For some constructs, no fixed number of children will work. To represent a procedure call, the must either custom allocate nodes based on the number of parameters or use a single child that holds a list of parameters. The same problem arises with a φ-function in an SSA-based IR. Using multiple node sizes complicates any code that traverses the AST; each node needs to indicate how many children it has and the traversal must contain code to visit each of those children. Using a list of parameters adds time and space overhead for allocation, construction, and traversal of the lists. To simplify the implementation of trees, the compiler writer can map the AST’s natural form—an arbitrary tree with variable arity nodes—onto a uniform binary tree in which every node has precisely two children. Un-der this map, a node’s left-child field points to its leftmost child while its right-child field points to the next sibling at the current level in the tree. The right-children form lists of siblings.

Fig. B.2(b) shows the for-loop header from panel (a) encoded as a binary tree. The simplicity of the binary tree has some costs; for example, each leaf node has an explicit null pointer. Notice also that the for node has a pointer to the first statement after the loop; in the original version, that pointer undoubtedly occurs in the parent of the for node. Panels (c) and (d) show a more complex example.

Using binary trees simplifies the implementation in several ways. Uniform nodes simplify memory allocation and work well with either an arena-based allocator or a block-contiguous allocator. Code to traverse the tree is simple and uniform; it avoids the issues that arise with multiple node formats. This simplicity has its cost: additional null pointers in leaf nodes.

Compilers must also represent arbitrary graphs, such as control-flow graphs (CFGs) and dependence graphs. The same implementation issues arise in graphs as in trees. Simple implementations might use heap-allocated nodes with pointers to represent edges. Fig. B.3(a) shows a simple CFG. Clearly, it needs three nodes. The difficulty arises with the edges: how many incoming and outgoing edges does each node need? Each node could maintain a list of outgoing edges; this approach leads to an implementation similar to the one shown in Fig. B.3(b).

In Fig. B.3(b), the rectangles represent nodes, and the ovals represent edges. This representation makes it easy to walk the graph in the direction of the edges. If the compiler needs random access to the nodes, the compiler writer can add an array of node pointers, indexed by the nodes’ integer names. With that addition (not shown), the graph is suitable for solving forward data-flow problems. It provides a fast means for finding all the successors of a node.

This representation does not facilitate traversing edges backward, as occurs in the solution of a backward data-flow problem. A backward traversal needs a fast predecessor operation. The compiler writer could add a list of predecessors to each node, at the cost of additional time and space.

An alternative is to represent the graph as a pair of tables: a node table and an edge table. For a given node, the node table contains the names of the 780 Data Structures (a) Control-Flow Graph

(b) A Graphical Representation

Node Table
NameSucc.Pred.
n0e0
n1e2e0
n2e3e1
Next Succ.Next Pred.
NameSourceSink
e0n0n1e1e3
e1n0n2e2
e2n1n2
e3n2n1

(c) A Tabular Representation

FIGURE B.3 Tabular Representation of a CFG.

Section titled “FIGURE B.3 Tabular Representation of a CFG.”

edges to its first successor and its first predecessor. The edge table has an entry for each edge; that entry contains the names of its source and sink. In addition, each edge has a field that contains the name of the next successor of its source and the next predecessor of its sink. These latter two tables instantiate, for each node, a list of its successors and a list of its predecessors.

Fig. B.3(c) shows the CFG from panel(a) in this tabular format. While the tables are not as obvious to read as the representations in panels(a) or(b),they provide quick access to successors, predecessors, and individual nodes and edges by their names(assuming that names are encoded as small integers).

The tabular representation works well for applications that traverse the graph. When the compiler makes heavy use of other operations, better rep-representations exist. For example, a graph-coloring register allocator has two dominant graph operations: iterating over a node’s neighbors and testing for the presence of an edge between two nodes(see Section 13.4.2). These operations suggest different representations; indeed, most coloring alloca-tors use adjacency lists to iterate over neighbors quickly and a bit matrix to answer the membership question-is the edge(i,j) in the graph? Because interference graphs are both large and sparse, space for the adjacency vectors can become an issue. Some implementations use two passes to build the graph—the first pass computes the size of each adjacency vector and the second pass builds the vectors, each with the minimal required size. Other implementations use a variant of the list representation for sets from Section B.2.1—the graph is built in a single pass, using an unordered list for the adjacency vector, with multiple edges per list node.

Conceptually, a linear intermediate form resembles a table or an array. The various ILOC examples throughout the book, in fact, are laid out as tables. Linear IRs have an implicit order; operations execute in order, until execution hits a branch, jump, or call. This abstract model is easy to visualize and to analyze. In practice, however, compilers use implementations that are more complex than a simple table.

A compiler manipulates a linear IR in a number of ways. It may change the values of the fields in an operation; for example, register allocation changes the register names in operations. A given pass might add, delete, or move operations. The parser adds to the end of the IR; the register allocator inserts spill code between existing operations. Dead code elimination removes operations. Lazy code motion might move operations from the middle of one block to the end of another; the scheduler reorders operations.

An implementation that uses a simple array-like structure may encounter unexpected costs on some of these manipulations. Insertions and deletions may be implemented by shuffling operations to create or reuse space. Expanding the array may entail copying the operations to a new heap object. Attention paid to such costs has a direct effect on the cost of compilation.

The compiler writer may use different implementation strategies in different passes. For the front end, the goal might be to minimize the overhead of adding additional operations onto the end of the IR. A pass that simply performs data-flow analysis might do well with a single preallocated array of structures. The scheduler needs the ability to reorder operations; the register allocator needs to insert and delete them.

As with nodes in a tree, two basic options exist for a linear IR: allocating individual structures or allocating an array of structures. In either case, the structure represents a single IR operation. In the first case, the individual structures are allocated on the heap and linked using pointers (or references). In the latter case, the structures are block allocated in one or more arrays; 782 Data Structures

MITIGATION STRATEGIES FOR AN INDEX-ORDER ARRAY

Section titled “MITIGATION STRATEGIES FOR AN INDEX-ORDER ARRAY”

The simplicity of an IR implementation that uses a single array of structures, traversed in index order, is compelling. If the compiler writer chooses this approach, she can employ strategies to mitigate some of the disadvantages.

Insertion Efficient insertions can be implemented with a detour operator that directs any traversal to an out-of-line code segment. To insert before operation i, the compiler creates a segment with the new operations followed by a copy of operation i, followed by a detour back to operation i+1. It then replaces operation i with a detour to the new code segment.

Deletion Efficient deletions are simple. The compiler can use an ignore operator that directs any traversal to skip to the next operation. To delete the i th operation, the compiler overwrites it with an ignore.

If the compiler uses these mitigation techniques, it will need to allocate additional space in the IR array to hold inserted code segments.

At the end of each pass, when the compiler writes the IR to external media for the next pass, it can linearize the detours inline and remove the ignores. Of course, the compiler could linearize the code in mid-pass if that was desirable.

these can be linked using either array indices(for a single array) or pointers. The advantages and disadvantages are similar to those discussed in the previous subsection.

With linked individual structures, the compiler can easily change the traversal order. An array of structures implementation can use index-order traversals, which saves the space used by pointers; this scheme increases the cost of rearrangement.

With an array of structures, index-order traversal should benefit from spatial locality and from the standard optimizations that improve dense linear-algebra codes, such as redundancy elimination, code motion, and strength reduction(see Chapters 8 and 10).

With individually allocated structures, allocation costs are higher than they would be with an array. In a managed runtime, multiple smaller heap objects might affect the cost of collection.

Linear forms are amenable to multiple implementation strategies. In a pass where the IR size is known and static, the compiler writer can allocate a single array of structures large enough to hold it. If index order traversal suffices, as in a single block, the order can be maintained implicitly by the index. If the order of operations may change, the compiler writer can add Data Structures 78 pointers to each operation to create singly or doubly-linked lists and achieve arbitrary traversal orders.

If the IR size is expected to change, the compiler writer can use an arena-style allocator or a block-contiguous allocator. Such an implementation usually requires pointers to link the operations, as a transparent way to link across separately allocated arrays of structures.

Some operations will not fit into the standard structure for an operation. For example, the number of source operands in an SSA-form ϕ\phi -function depends on the number of incoming edges in the control-flow graph. It might be 2; it might be 32. An implementation that uses pointers to link the individual operations can simply allocate a variant structure and link it into the IR. An implementation as an array of structures can use a detour operator as suggested in the digression on page 782. Of course, the code that manipulates the IR must understand all the variants and handle them.

With the widespread availability of feature libraries in languages such as JAVA and PYTHON, most students will rely on library implementations of hash tables or maps. However, some circumstances will warrant a custom implementation. In a heavily used compiler, such as GCC or LLVM, the savings from a custom implementation may be significant when considered across all the compilations done with the compiler. In other cases, a custom implementation may take advantage of particular known properties of the set of expected keys(e.g., single character strings or pairs of small integers).

This section describes several issues that arise in the implementation of a custom hash table. Section B.4.1 describes two hash functions that, in practice, produce good results. Sections B.4.2 and B.4.3 present two widely used strategies for resolving collisions: open-hashing and open-addressing. Sec-tion B.4.4 discusses storage management issues for hash tables.

Perhaps the most critical decision in hash-table design is the choice of a hash function. A hash function that produces a bad distribution of index values directly increases the average cost of both insertions and lookups. Fortunately, the literature documents several good hash functions, including the multiplicative hash functions described by Knuth and the universal hash functions described by Cormen et al. 784 Data Structures

Symbol-table lookups can, and sometimes do, exhibit worst-case behavior. In the early 1980s, the authors worked on the front-end for a FORTRAN vectorizing compiler, PFC. The author of the first version of PFC’s scanner used an unbalanced binary tree in its symbol table.

Unfortunately, several of the key applications used to test PFC had declaration statements that listed the variables in alphabetical order. Thus, the scanner constructed a tree in which most of the right-subtrees were empty; symbol-table lookups quickly devolved to O(n) time per lookup.

To remedy this situation, a graduate student was assigned to build a hash-based table. To compute the hash, the implementation broke the variable name into four-byte chunks and combined them with exclusive or. It used the resulting number, modulo the table size, as an index into the table.

Unfortunately, the student chose a table size of 2,048, so the mod operation returned the low-order 11 bits of the 32-bit word. The hash function padded short strings with blanks to reach a full word. Thus, any one or two character name produced the same hash key: the bottom 11 bits of “b b”. Since the applications contained many single character variable names, symbol-table lookups again trended toward O(n) time per lookup. Changing the table size to a Mersenne number (2n-1) cured the problem. PFC used the implementation for many years with an initial table size of 2,047.

A multiplicative hash function is deceptively simple. The programmer chooses a single constant C and uses it in the following formula:

h(key)=⌊TableSize⋅((C⋅key) mod 1)⌋h(key)=\lfloor TableSize\cdot((C\cdot key)\bmod 1)\rfloor

where C is the constant, key is the integer being used as a key into the table, and TableSize is, rather obviously, the current size of the hash table. Knuth suggests the following value for C:

0.6180339887≈5−120.6180339887\approx\frac{\sqrt{5}-1}{2}

The effect of the function is to compute C·key, take its fractional part with the mod function, and multiply the result by the size of the table.

To implement a universal hash function, the programmer designs a family of functions that are parameterized by a small set of constants. At execution time, values for the constants are chosen at random-either using random numbers for the constants or selecting a random index into a set of previously tested constants. By varying the hash function across executions of the program, this scheme produces different distributions in different runs of the program. In a compiler, if the input program produced pathological behavior in some particular compilation, it is unlikely to produce the same behavior in subsequent compilations. To implement a universal version of the multiplicative hash function, the compiler writer can randomly generate an appropriate value for C at the start of each compilation.

Open hashing, also called bucket hashing, assumes that the hash function h produces collisions. It relies on h to partition the set of input keys into a fixed number of sets, or buckets. Each bucket contains a linear list of records, one record per name. LookUp(n) walks the linear list stored in the bucket indexed by h(n) to find n. Thus, LookUp requires one evaluation of h(n) and the traversal of a linear list. Evaluating h(n) should be fast; the list traversal will take time proportional to the length of the list. For a table of size S,with N names, the cost per lookup should be roughly O(N÷S). As long as h distributes names fairly uniformly and the ratio of names to buckets,N÷SN\div S , is small, this cost approximates our goal: O(1) time for each access.

Fig. B.4(a) shows a small hash table implemented with this scheme. It assumes that h(a)=h(d)=6 to create a collision. Thus, a and d occupy the same slot in the table. The list structure links them together. Insert should add to the front of the list for efficiency.

The same constants are used throughout single run of the program that uses the function, but the constants run. 786 Data Structures

Open hashing has several advantages. Because it creates a new node in one of the linked lists for every inserted name, it can handle an arbitrarily large number of names without running out of space. An excessive number of entries in one bucket does not affect the cost of access in other buckets. Because the concrete representation for the set of buckets is usually an array of pointers, the overhead for increasing S is small—one pointer for each added bucket. This fact makes it less expensive to keep N ÷ S small.

The primary drawbacks for open hashing relate directly to these advantages. Both can be managed.

  1. Open hashing can be allocation intensive. Each insertion allocates a new record. When implemented on a system with heavyweight memory allocation, the cost may be noticeable. Again, lighter-weight mechanisms such as an arena-based allocator or a block-contiguous allocator can reduce the allocation costs.

  2. If any set gets large, LookUp degrades to linear search. With a good hash function, this occurs only when N is much larger than S. The implementation should detect this problem and enlarge the array of buckets. Typically, this involves allocating a new array of buckets and reinserting each entry from the old table into the new table.

A well-implemented open hash table provides efficient access with low overhead in both space and time.

To improve the behavior of the linear search performed in a single bucket, the compiler can dynamically reorder the chain. Rivest and others [310,329] describe two effective strategies: move a node up the chain by one position on each lookup, or move it to the front of the list on each lookup. More complex schemes to organize each bucket can be used as well. However, the compiler writer should assess the total amount of time lost in traversing a bucket before investing much effort in this problem.

Open addressing, also called rehashing, handles collisions by computing an alternative index for the names whose normal slot, at h(n), is already occupied. In this scheme, LookUp(n) computes h(n) and examines that slot. If the slot is empty, LookUp fails. If LookUp finds n, it succeeds. If it finds a name other than n, it uses a second function g(n) to compute an increment for the search. This leads it to probe the table at (h(n) + g(n)) mod S, then at (h(n) + 2 × g(n)) mod S, then at (h(n) + 3 × g(n)) mod S, and so on, until it either finds n, finds an empty slot, or returns to h(n) a second time. (The table is numbered from 0 to S−1, which ensures that mod S will return a valid table index.) If LookUp finds an empty slot, or it returns to h(n) a second time, it fails.

Fig. B.4(b) shows a small hash table implemented with this scheme. It uses the same data as Fig. B.4(a). As before, h(a) = h(d) = 6, while h(b) = 8 and h(c) = 0. When d was inserted, it produced a collision with a. The secondary hash function g(d) produced 8, so insert placed d at index 4 in the table ((6 + 8) mod 10 = 4). In effect, open addressing builds chains of items similar to those used in open hashing. In open addressing, however, the chains are stored directly in the table. A single table slot can be the starting point for multiple chains, each with a different increment produced by g.

This scheme makes a subtle tradeoff of space against speed. Since each key is stored in the table, S must be larger than N. If h and g produce good distributions, then collisions are infrequent, the rehash chains stay short, and access costs stay low. Because it can recompute g inexpensively, this scheme need not store pointers to form the rehash chains—a savings of N pointers. The compiler can instead devote that space to a larger table, which may reduce the number of collisions. The primary advantage of open addressing is simple: lower access costs through shorter rehash chains.

Open addressing has two primary drawbacks. Both arise as N approaches S and the table becomes full.

  1. Because rehash chains thread through the index table, a collision between n and m can interfere with a subsequent insertion of some other name p. If h(n) = h(m) and (h(m) + g(m)) mod S = h(p), then inserting n, followed by m, fills p’s slot in the table. When |S| >> |N|, this problem has a minor impact. As N approaches S, it can become pronounced.

  2. Because S must be at least as large as N, the table must be expanded if N grows too large. (The implementation might also expand S if some chain becomes too long.) With open addressing, expansion is needed for correctness; with open hashing, expansion is a matter of efficiency.

Some implementations use a constant in place of g. While this approach eliminates the cost of computing g(n), it has the downside effect that it creates a single rehash chain for each value of h. Furthermore, it merges rehash chains whenever a secondary index encounters an already occupied table slot. These two disadvantages probably outweigh the cost of computing g(n). A better choice is to use the multiplicative hash function with different constants for h and g, selected at startup from a table of constants.

The table size S plays an important role in open addressing. LookUp must recognize when it reaches a table slot that it has already visited; otherwise, it will not halt on failure. To make this efficient, the implementation should 788 Data Structures

■ FIGURE B.5 Stack Allocation for Records.

Section titled “■ FIGURE B.5 Stack Allocation for Records.”

ensure that it eventually returns to h(n). If S is a prime number, then any choice of 0<g(n)<S generates a series of probes, p1, p2,…,pS, with the properties that p1=pS=h(n), and p;≠h(n), ∀ 1<i<S\forall\,1<i<S . That is, LookUp will examine every slot in the table before it returns to h(n). Since the implementation may need to expand the table, it should include a table of appropriately sized prime numbers. In practice, a small set of primes will suffice, due to the realistic limits on both program size and memory available to the compiler.

Neither open hashing nor open addressing directly addresses the issue of how to allocate space for the information associated with each hash table entry. Assume the compiler uses a structure to hold each symbol’s attributes. With open hashing, the temptation is to put these structures directly into the nodes that implement the chains. With open addressing, the temptation is to store those structures directly in the index table. Both these approaches have drawbacks. A separate stack of structures may achieve better results.

Fig. B.5 depicts this implementation. In an open-hashing implementation, the chain-pointers can be stored in the stack to avoid the need to allocate them individually. In an open-addressing implementation, the rehash chains are still implicit in the index set, preserving the space savings that motivated the idea.

Of course, the compiler writer can link the stack entries together and use either an arena-based allocator or a block-contiguous allocator to handle growth in the stack. When the actual records are stored in a stack, they form a dense table. For heavyweight allocation, this scheme amortizes the cost of a large allocation over many records. In a collected environment, it decreases the number of objects that must be marked and collected. If the compiler writes the table to external media, it can use blocked I/O. Finally, a dense table may provide

[…]more locality when the compiler iterates over the symbols in the table-for example, when the compiler assigns storage locations.

As a final advantage, this scheme simplifies expansion of the index set. The compiler can discard the old index set, allocate a larger set, and then reinsert the records into the new table, working from the stack’s bottom to its top. This process eliminates the need to have both the old and new index sets in memory at the same time. By iterating over the dense table, the compiler does not touch empty table slots.

Most compilers use one or more hashed symbol tables as a central repository for facts about the various names that appear in the source code, in the IR,and in the generated code. During compiler development, the set of fields in the symbol table seems to grow monotonically. Fields are added to support new passes and to transmit information between passes. When the need for a field disappears, it may or may not be removed from the symbol-table definition. As fields are added, symbol table size grows and parts of the compiler with direct access to the symbol table may need to be recompiled.

We encountered this problem in the implementation of the Rn\mathcal{R}^{n} and Para-Scope programming environments. The experimental nature of these systems made additions and deletions of symbol-table fields a common oc-curence. To address the problem, we designed and built a more complex but more flexible symbol table-a two-dimensional hash table. It eliminated most changes to the symbol-table definition and its implementation.

Fig. B.6 shows a conceptual drawing of such a table, populated for the C-like block shown in the margin. The implementation uses two distinct hash index tables, one for the primary key and the other for the field name, used as a secondary key. The implementation uses the secondary key to find the appropriate vector of data for the desired field. It uses the primary key to select the right slot from inside that vector. Of course, the drawing hides some complexity. Both the primary and secondary indices must be implemented as full-fledged hash tables, with provisions for collision using one of the schemes described previously.

While this scheme seems complex, it is not particularly expensive. Each table access requires two hash computations rather than one. The implementation need not allocate storage for a given field until a value is stored in it, which avoids the space overhead of unused fields. It allows individual developers to create and delete symbol-table fields without interfering with other programmers.

As the set of fields stabilizes, the com writer can replace the table with one th has fixed fields. 790 Data Structures

FIGURE B.6 Two-Dimensional Hashed Symbol Table.

Section titled “FIGURE B.6 Two-Dimensional Hashed Symbol Table.”

The implementation provided entry points for setting initial values for a field(by name), for deleting a field(by name), and for reporting statistics on field use. It allowed individual programmers to manage their own symbol-table use in a responsible and independent way, without interfering with their colleagues.

As a final issue, the implementation was abstracted with respect to specific symbol-table instances. That is, the same implementation managed tables in the parser and in other parts of the compiler.

Many of the algorithms in a compiler manipulate sets, maps, tables, and graphs. The underlying implementations directly affect the space and time that those algorithms require and, ultimately, the usability of the compiler itself[63]. Textbooks cover many of the issues that this appendix brings together[5,45,119,207,240].

Our research compilers have used almost all the data structures described in this appendix. We have seen performance problems from data-structure growth in several areas. Abstract syntax trees, as mentioned in the sidebar in Chapter 4, can grow unreasonably large. The technique of mapping an arbitrary tree onto a binary tree simplifies the implementation and seems to keep overhead low [240].

The tabular representation of a graph, with lists of successors and predecessors, has been reinvented many times. It works particularly well for CFGs, for which the compiler iterates over both successors and predecessors. We first used this data structure in the PFC system in 1980.

The sets in data-flow analysis can grow quite large. Because allocation and deallocation are performance issues at that scale, we routinely use Hanson’s arena-based allocator [189] for the bit-vectors.

The size and sparsity of interference graphs makes them another area that merits careful consideration. We use an ordered-list with multiple set elements per node to keep the cost of building the graph low while managing the space overhead [111].

Symbol tables play a central role in the way that compilers store and access information. Much attention has been paid to the organization of these tables. Reorganizing lists [310,329], balanced search trees [45,119] and hashing [240, vol. 3] all play a role in making access to these tables efficient. Knuth [240, vol. 3] and Cormen [119] are standard references for high-quality hash functions.


← node-book_engineering-a-compiler_chapter-13-register-allocation | node-book_engineering-a-compiler