Skip to content
ImagineWorld

Implementing Procedures

node_idnode-book_engineering-a-compiler_chapter-06-implementing-procedures
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titleImplementing Procedures
pillar_membershipF — compiler_trinity
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Procedures play a critical role in the development of software systems. They provide abstractions for control flow and naming. They provide basic information hiding. They are the building block on which systems provide interfaces. They are one of the principal forms of abstraction in Algol-like languages; object-oriented languages rely on procedures to implement their methods or code members.

This chapter takes an in-depth look at the implementation of procedures and procedure calls, from the perspective of a compiler writer. It highlights the implementation similarities and differences between Algol-like languages and object-oriented languages. The Advanced Topics section presents a brief introduction to the algorithms used to manage the runtime heap.

Procedure Calls, Parameter Binding, Linkage Conventions

The procedure is one of the central abstractions in most programming languages. Procedures create a controlled execution environment; each procedure has its own private storage. Procedures help define interfaces between system components; cross-component interactions are usually structured through procedure calls. Finally, procedures are the basic unit of work for most compilers. A typical compiler processes a collection of procedures and emits code for them. The code produced by these separate compilations must link and execute correctly with code compiled at other times.

Procedures play a critical role in separate compilation, which allows software developers to build large software systems. If the compiler needed the entire text of a program for each compilation, large software systems would be untenable. Imagine recompiling a multimillion line application for each editing change made during development! Thus, procedures play as critical a role in system design and engineering as they do in language design and compiler implementation. This chapter focuses on how compilers implement procedures and methods.

To translate a source-language program into executable code, the compiler must map all of the source-language constructs that the program uses into operations and data structures on the target processor. The compiler needs a strategy for each of the abstractions supported by the source language. These strategies include both algorithms and data structures that are embedded into the executable code.

To implement these strategies, the compiler writer must put in place compile-time computations and data structures, mechanisms to pass information from compile time to runtime, and code in the executable to implement the runtime side of the strategy. All these elements combine to create the desired behavior when the application program runs.

This chapter explains the techniques that compiler writers use to implement procedures and procedure calls. Specifically, it examines the implementation of control, of naming, and of the call interface. These abstractions encapsulate many of the features that make programming languages usable and that enable construction of large-scale systems.

This chapter deals with both compile time and runtime issues. The compiler plans the desired runtime behavior. It emits code to implement that behavior-typically, the standard call and return mechanisms. To understand how calls work, the reader should pay careful attention to the interplay between compile-time planning and runtime behavior.

For example, the compiler must plan for the storage needs of each procedure. As it analyzes the procedure’s code, the compiler builds a storage map that includes the type and size of each value computed in the procedure. It assigns each value a runtime location. Using the map, the compiler generates code that will, at runtime, allocate, initialize, and free storage for those values. The code to implement these decisions is spread across the code for the caller and the callee.

Similarly, the compiler determines what actions must be taken at each call site to preserve and protect the environment of the calling procedure; it then emits code to enact those decisions at runtime. Such decisions include saving and restoring registers, evaluating and binding parameters, and maintaining data structures that ensure correct and appropriate access to values in surrounding scopes. Again, the compiler analyzes, plans, and emits code. At runtime, that code creates the desired behavior.

Caller

In a procedure call, the procedure that initiates the call is termed the caller.

Callee

In a procedure call, the procedure that is called is termed the callee.

Procedures are the building blocks of programs. They create a known and controlled execution environment. A procedure executes when it is invoked, or called, by another procedure. That call creates and initializes procedure-local storage. It protects the caller’s environment, establishes the callee’s environment, and creates any linkages between those environments specified by the call and the language. The callee may return a value to its caller, in which case the procedure is termed a function. The interface between procedures lets programmers develop and test parts of a program in isolation; the separation between procedures provides some insulation against problems in other procedures.

Procedures shape the way that programmers develop software and that compilers translate programs. Three critical abstractions that procedures provide allow the construction of nontrivial programs.

  1. The Call Procedure calls provide an orderly transfer of control between procedures. The call mechanism provides a standard way to invoke a procedure and map a set of arguments, or parameters, from the caller’s name space to the callee’s name space. After the callee completes, control returns to the caller, at the point immediately after the call. Most languages allow a procedure to return one or more values to the caller.

Languages and implementations define a standard set of actions required to invoke a procedure, sometimes referred to as a calling sequence. Stan-dardization of calling sequences, in the form of a linkage convention, lets the programmer invoke code written and compiled by other people and other compilers at other times.

  1. Name Space In most languages, a procedure call creates a new and protected name space for the callee(see Section 5.4). The programmer can declare new names, such as variables and labels, inside the procedure without concern for the surrounding context. Those local declarations obscure any previously defined items with the same names. The programmer can use formal parameters in the procedure to map values and variables from the caller’s name space into the callee’s name space. Because the procedure has a known and separate name space, it can function correctly and consistently when called from different contexts.

Executing a call instantiates the callee’s name space. The call must create storage for the objects declared by the callee. This allocation must be both automatic and efficient.

  1. External Interface Procedures form critical interfaces among the parts of large software systems. The linkage convention defines rules that map names to values and locations, that preserve the caller’s runtime

an agreement between the compiler and operating system that defines the actions taken to call a procedure or function

A value or variable passed as a parameter at a call site is an actual parameter of the call.

A name declared as a parameter of some procedure p is a formal parameter of p. environment and create the callee’s environment, and that transfer control between caller and callee.

The linkage convention creates a standard way to invoke code written by other people and in other languages. Uniform calling sequences enable the construction of large software systems by making possible the use of libraries and system calls. Without a linkage convention, both the programmer and the compiler would need to understand the callee’s code at each procedure call.

Thus, the procedure is, in many ways, the fundamental abstraction that underlies Algol-like languages (ALLs). It is an elaborate facade created collaboratively by the compiler, the underlying hardware, and the operating system. Procedures create named variables and map them to virtual addresses; the operating system and the hardware map those virtual addresses to physical addresses. Procedures establish rules for visibility and addressability of names; the hardware loads and stores values from addresses computed by the compiled code. Procedures let us decompose large software systems into components; linkers and loaders knit these components together into an executable; the hardware runs that code by simply advancing its program counter and following branches and jumps.

Implementing the linkage convention requires coordination between the compiler and the surrounding system, as well as between compilations. The compiler must arrange for the generated code to use the interfaces provided by the operating system to handle input and output, to manage memory allocation and deallocation, and to communicate with other processes. The compiler must lay out memory for each procedure and encode that knowledge into the generated code. Since the different components of the program may be compiled at different times, with different compilers, and in isolation from each other, all of these interactions must be standardized and uniformly applied.

This chapter focuses on the procedure as an abstraction and the mechanisms that the compiler uses to establish its control abstraction, name space, and interface to the outside world.

In ALLs, procedures have a simple call/return discipline. A call transfers control from a call site in the caller to the start of the callee; when the callee exits, control returns to the point in the caller immediately after the call. If the callee, in turn, invokes other procedures, they follow the same protocol, with a call and a return. Fig. 6.1 shows the call graph and execution history for the PASCAL program from Fig. 5.9. program Main(input, output); var x,y,z: integer; procedure Fee; var x: integer; begin { Fee } x := 1; y := x * 2 + 1 end; procedure Fie; var y: real; procedure Foe; var z: real; procedure Fum; var y: real; begin { Fum } x := 1.25 * z; Fee; writeln(‘x = ‘,x) end; begin { Foe } z := 1; Fee; Fum end; begin { Fie } Foe; writeln(‘x = ‘,x) end; begin { Main } x := 0; Fie end.

(a) Example PASCAL Program

(b) Call Graph

(c) Execution History

The call graph in panel (b) shows all of the potential calls in the program. Executing Main can produce two distinct calls to Fee: one from Foe and the other from Fum. The execution history shows that both calls actually occur. Each call creates a distinct instance, or activation, of Fee. By the time that Fum is called, the first instance of Fee is no longer active. It was created by the call from Foe (event 3 in the execution history), and destroyed after control returned to Foe (event 4). When Fum calls Fee (event 6), the call creates a new activation of Fee. The return from Fee to Fum ends that activation and makes its state inaccessible.

Activation A call to a procedure activates it; thus, we call an instance of its execution an activation.

Fee, Foe, Fie, and Main are active when the program executes the assignment x:=1 in the first call to Fee. They all lie on a path in the call graph from Main to Fee. Similarly, Fee, Fum, Foe, Fie, and Main are active when the program makes its second call to Fee; they lie on another path from Main to Fee. The call and return mechanism ensures that, at any point during execution, the procedure activations instantiate some rooted path through the call graph.

When the compiler generates code for calls and returns, that code must preserve enough state information to ensure correct operation on a return. When Foe calls Fum, the code must record Foe’s state, including the address in Foe to which Fum should return control-its return address. Unless Fum diverges, control will return to Foe and continue execution in Foe. The call mechanism preserves enough state to allow that to happen.

A computation that does not terminate normally is said to diverge.

Return address

When p calls q, the address in p where execution should continue after q’s return is called its return address.

The call and return behavior of ALLs can be modeled with a first-in, first-out stack. Thus, the runtime implementations of many programming languages use a stack to hold the state of each active procedure. When Fie calls Foe, it pushes the new state for Foe onto the stack; Foe executes from that state. When Foe returns, it pops that state off the stack and exposes the state for Fie, as it was when the call was made.

The stack mechanism handles recursion. In effect, it unrolls the cyclic path through the call graph and creates a distinct activation and state for each call to a procedure. As long as the recursion terminates, this path will be finite and the stack will correctly capture the program’s behavior.

To make this concrete, consider the following recursive factorial computation, written in SCHEME:

(define(fact k)\text{(define(fact k)} (cond\text{(cond} [(<= k 1) 1][\text{(<= k 1) 1]} [else(*(fact(sub1 k)) k)][\text{else}(\text{*}(\text{fact}(\text{sub1}\text{ k}))\text{ k})]

A call to(fact 5) generates a series of recursive calls:(fact 5) calls(fact 4) calls(fact 3) calls(fact 2) calls(fact 1). At that point, the cond statement executes the clause for(<= k 1), ending the recursion. The recursion unwinds in the reverse order. The call to(fact 1) returns the value 1 to(fact 2). It, in turn, returns the value 2 to(fact 3), which returns 6 to(fact 4). Finally,(fact 4) returns 24 to(fact 5), which multiplies 24 times 5 to return the answer 120. The recursive program exhibits last-in, first-out behavior, so the stack mechanism correctly tracks all of the return addresses.

Procedure Calls in Object-Oriented Languages

Section titled “Procedure Calls in Object-Oriented Languages”

From the perspective of procedure calls, object-oriented languages (OOLs) are similar to ALLs. The primary differences between procedure calls in an OOL and an ALL lie in the mechanism used to name the callee and in the mechanisms used to locate the callee at runtime.

In an OOL, the call is made relative to an object. The compiler knows the names of the receiver and the method. From those facts, it must determine the receiver’s class and resolve the method name to the intended implementation. If the compiler can resolve that name-to-implementation binding at compile time, it can emit code that looks much like a standard call in an ALL. If, however, it cannot resolve that binding until runtime, then the compiler must emit code that uses runtime data structures to resolve it.

To support runtime name resolution, the compiler must emit code that builds runtime data structures to instantiate a model of the inheritance hierarchy. Fig. 5.17 showed a simple example.

Following the lambda calculus, some programming languages allow a program to encapsulate a procedure and its runtime context into an object called a closure. When the closure is invoked, the procedure executes in the encapsulated runtime context. A simple stack is inadequate to implement this functionality. Instead, the control information must be saved in a more general structure that can represent the procedure and its context. Similar problems arise if the language allows references to local variables that outlast a procedure’s activation.

In AlgoL-like languages, procedures are invoked with a call and they terminate in a return. The compiler must arrange for the call to record and preserve the caller’s state and for the return to find and restore the caller’s state. Using a stack to hold the state for procedure activations captures the last-in, first-out behavior of the call/return mechanism.

OOLs and languages that support closure build on this basic infrastructure to produce more complex control flow. OOLs use data-centric naming schemes to map names to method implementations. Closures break the relationship between the lifetime of a scope and the call that creates it; these schemes require more complex implementations.

The overall goal is to resolve a compile-time name into a runtime virtual address.

  1. Many programming languages include a direct transfer of control, a so-called goto. Compare and contrast a procedure call and a goto.
  2. Many languages make use of libraries of precompiled code. What facts does the compiler need about the library code so that it can ensure correct behavior? How does your favorite language provide it to the compiler?

To support the name spaces that occur in source-language programs, the compiler must be able to map a given reference into its runtime virtual address. The mechanism has two parts: a compile-time capability to resolve the name to a specific runtime entity and a runtime method to locate and access that entity.

The description of these mechanisms is spread over several chapters in the text. Section 5.4 describes the compile-time mechanisms used to resolve a source-language name to a specific runtime entity. Section 5.6 discusses how the compiler determines where in the computer’s memory each entity that needs storage will reside. This section explores the runtime data-structures that the compiler must put in place to facilitate addressability and to store values. Finally, Section 7.3 enumerates how the compiler uses these mechanisms to emit code that can compute a runtime virtual address.

The runtime support for name resolution and translation occurs, primarily, in two places. The data structures are created, populated, and dismantled as part of the implementation of procedure calls. Section 6.3.1 describes the mechanisms commonly used to support the nested lexical scopes that occur in Algol-like languages (ALLs). Section 6.3.2 discusses the additional runtime structures required to support object-oriented languages (OOLs). The remainder of the implementation occurs when the compiler emits code for individual references, following the plans laid out in Section 7.3.

6.3.1 Runtime Support for Algol-Like Languages

Section titled “6.3.1 Runtime Support for Algol-Like Languages”

To implement the twin abstractions of procedure calls and lexically scoped name spaces, the compiler and runtime system must establish a set of run-time data structures. The key structure involved in both control and naming is the activation record (AR), a private block of memory associated with a single procedure activation. Each procedure call gives rise to a new AR.

Activation record a region of storage set aside to hold control information and data storage associated with a single instance of a single procedure

■ FIGURE 6.2 Typical Activation Records.

■ The compiler must emit code so that the caller stores the return address for the callee. The return address goes in the callee’s AR.

■ The compiler must map the actual parameters at the call site into the formal parameters by which they are accessible in the callee. This parameter information goes into the callee’s AR.

■ The compiler must create storage space for local variables declared in the callee. For the values whose lifetimes match the procedure’s invocation, that storage goes into the callee’s AR.

■ The compiler must provide the callee with other information needed to connect it to the calling context and allow it to interact with other procedures. That data goes into the callee’s AR.

Each call creates a new AR. If multiple instances of a procedure are active, each has its own AR. Thus, recursion gives rise to multiple ARs, each of which holds the local state for a different activation of the procedure.

Fig. 6.2 shows how the contents of an AR might be laid out. The activation record pointer (ARP) points to a fixed spot in the AR. The various fields in the AR are found at positive and negative offsets from the ARP. The ARs shown in Fig. 6.2 have a number of fields.

■ The parameter area holds actual parameters from the call site, in an order determined by their order of appearance at the call site.

■ The register save area contains enough space to hold the values from registers that the procedure must preserve across procedure calls.

Activation record pointer

The compiler ensures that a pointer to the AR, the activation record pointer, is in a designated register.

We denote that register rarp.

The surrounding lexical scope may be a procedure other than the caller.

■ The return-value slot provides space to communicate data from the callee back to the caller, if needed. ■ The return-address slot holds the runtime address to which control should return when the callee terminates. ■ The addressability slot holds information that lets the callee access local variables in surrounding lexical scopes. ■ The slot at the callee’s ARP preserves the caller’s ARP so that the callee can restore the caller’s environment when it returns. ■ The local data area holds variables declared in the callee’s local scope that the callee cannot keep in registers, along with other values that the compiler needs to store.

For the sake of efficiency, some of the information shown in the ARs of Fig. 6.2 may be kept in dedicated registers.

Local Storage

The AR for an activation of procedure q holds both local data and control information for that instance of q. Each time the code calls q, that call generates a new AR. Accesses to fields in an AR occur through the ARP. Thus, the ARP acts as a handle to the activation’s context and state. At runtime, the code accesses the AR frequently enough that most compilers dedicate a physical register to hold the ARP of the active procedure. In ILOC, we refer to this dedicated register as rarp.

The ARP points to a designated position in the AR. The central part of the AR has a static layout; all the fields have known fixed lengths. Thus, the compiled code can access those items at fixed offsets from the ARP. The two ends of the AR are reserved for storage areas whose sizes depend on specific details of the corresponding procedure; one typically holds the parameters while the other holds the local data.

Reserving Space for Local Data

When the compiler performs storage assignment, it assigns space in the local data area to automatic local variables that cannot reside in registers (see Section 5.6.3). As it assigns space to such variables, it should record the current lexical level and the value’s offset from the ARP in the symbol table. This pair, a lexical level and offset, is the key to accessing the value at runtime. This pair becomes its static coordinate (see Section 7.3.1).

The input program may contain one or more variables for which the size is not known at compile time. For example, the code might compute the size of an array or read its size from external media. In such cases, the compiler can create space in the local data area for a pointer to either the actual data or a dope vector for the actual data(see Section 7.3.2).

The compiler can then arrange to allocate the space needed for the data elsewhere. It might put the data in the heap; if the ARs are on a stack, it might place the data at the top of the stack. In either scenario, the compiler can arrange to store a pointer to the storage in the space that it created in the AR, or in the appropriate slot of the dope vector. The static coordinate then leads to the slot in the AR; the code for the array access then begins with that pointer.

If the source language lets the programmer specify initial values for variables, the compiler must ensure that the initialization occurs. For a statically allocated variable, the data can be inserted directly into the appropriate locations in the static data area.

Variables stored in the AR must be initialized at runtime. Because a procedure may be invoked multiple times, the compiler must emit operations to perform the initializations on every invocation. In effect, these initializa-tions are assignments that execute before the procedure’s first statement, on each invocation.

When p calls q, one of them must save the register values that p needs after the call. It may be necessary to save all the register values; on the other hand,a subset may suffice. On return to p, these saved values must be restored. The lifetime of these saved register values matches the lifetime of the callee. Thus, the compiler can save them in either the callee’s AR or the caller’s AR.

If the caller saves a register before jumping to the callee, it saves the value into its own AR. Similarly, if the callee saves a register before it begins to execute, it saves the value into its own AR. Thus, the AR needs capacity to store a full set of caller-saves and callee-saves registers. Since the caller saves before the call and restores after the call, it can reuse the same space for caller-saves registers at each call.

When procedure p calls procedure q, the code for the call must allocate and initialize an AR for q. Because procedure calls are frequent, the compiler writer should try to keep the cost of this allocation as low as possible. In general, the compiler writer has three choices for AR allocation: stack allocation, heap allocation, and static allocation.

Most assemblers provide a pseudooperation to allocate and initialize static storage.

Caller-saves register

If the caller has responsibility to preserve the value of r1 across a call, we say that r is a caller-saves register.

Callee-saves register

If the callee has responsibility to preserve the value of r1 across its own execution, we say that r1 is a callee-saves register.

Stack Allocation of ARs p calls q calls r

Stack Allocation of Activation Records

In many cases, the contents of an AR are only of interest during a single activation of the procedure. If local variables cannot outlive the procedure that creates them and procedure activations cannot outlive their callers, then calls and returns are balanced and follow a last-in, first-out(LIFO) discipline.A call from p to q eventually returns, and any returns that occur between the call from p to q and the return from q to p must result from calls made(either directly or indirectly) by q.

With these restrictions, the ARs also follow the LIFO ordering and allocation can use a simple stack. PASCAL, C, and JAVA are typically implemented with stack-allocated ARs, as shown in the margin.

Stack allocation of ARs has several advantages. Allocation and deallocation are inexpensive; the code performs arithmetic on the top-of-stack(TOS)pointer. The code can extend the AR at the top of the stack by testing for stack overflow and then adjusting the TOS pointer. This scheme lets a procedure extend its AR to create space for dynamically sized local entities. The drawing in the margin shows this situation. Here, the compiler has left a slot in the local data area for a pointer to A, and later extended the AR to create space for A.

With stack allocation, the task of creating the AR can be split between the caller and the callee. The caller can create those portions of the AR whose size it knows-everything from the parameter area to the caller’s ARP. The callee can then extend its own AR to create space for the local data area.

Extending a Stack-Allocated AR

If the programming language allows a procedure activation to outlive its caller, the stack discipline for allocating ARs breaks down. Similarly, if a procedure can return an object, such as a closure, that includes, explicitly or implicitly, references to its local variables, stack allocation is inappropriate because it will leave behind dangling pointers. In these situations, the compiler can allocate ARs on a runtime heap(see Section 6.6). Implementations of SCHEME and ML typically use heap-allocated ARs.

A good memory allocator can keep the cost of heap allocation low. Most heap implementations do not allow an object to expand after it is allocated. This fact complicates AR allocation because it implies that either:

  1. The caller must know the size of the callee’s local data area. The compiler can compute that size and store it in a global constant pool. At each call, the caller can retrieve the value and include it in the calculation of the local data area’s size.

  2. The callee needs to allocate the local data area separately. This option, while simpler, may require a separate register to hold a pointer to the local data area.

With heap-allocated ARs, variable-size objects can be allocated as separate objects on the heap. If heap objects need explicit deallocation, then the code for procedure return must free the AR and its variable-size extensions.

Heap allocated ARs work well for closures. The closure holds a pointer to the AR for the activation that created it. The chain of caller’s ARP fields will keep the rest of the state live until the closure is invoked. When the closure is discarded, any parts of that state that were live only because of the closure will become dead; an implicit deallocation scheme will recycle them.

If a procedure q calls no other procedures, then q can never have multiple active invocations. We call q a leaf procedure since it terminates a path through a graph of possible procedure calls. The compiler can statically allocate ARs for leaf procedures to avoid the runtime costs of AR allocation. If the calling convention has only caller-saves registers (no callee-saves registers), then q’s AR needs no register save area.

Leaf procedure a procedure that contains no calls

If the language does not allow closures, the compiler can do better than one static AR per leaf procedure. At any point during execution, only one leaf procedure can be active. (To have two such procedures active, the first one would need to call another procedure, so it would not be a leaf.) Thus, the compiler can allocate a single static AR for use by all of the leaf procedures. The static AR must be large enough to accommodate any of the program’s leaf procedures. The static variables declared in any of the leaf procedures can be laid out together in that single AR, which avoids the need for separate static ARs for each leaf procedure.

If the compiler discovers a set of procedures that are always invoked in a fixed sequence, it may be able to combine their ARs. For example, if a call from p to q always results in calls to r and s, the compiler may find it profitable to allocate the ARs for q, r, and s at the same time. Combining ARs can save on the costs of allocation; the benefits will vary directly with allocation costs. In practice, this optimization is limited by separate compilation and the use of function-valued parameters. Both limit the compiler’s ability to determine the calling relationships that actually occur at runtime.

6.3.2 Runtime Support for Object-Oriented Languages

Section titled “6.3.2 Runtime Support for Object-Oriented Languages”

Just as Algol-like languages need runtime structures such as ARs to support their lexical name spaces, so too do object-oriented languages need runtime structures to support both their lexical hierarchy and their class hierarchy. Some of those structures are identical to the ones found in an ALL. For example, the control information for methods, as well as storage for method-local names, is kept in ARs. Other structures are designed to address specific needs of the OOL. For example, object lifetimes need not match the lifetime of any particular method activation, so their persistent state cannot be stored in some AR. Thus, each object needs its own object record(OR) to hold its state. The ORs of classes instantiate the inheritance hierarchy; they play a critical role in translation and execution.

Each OR begins with a member class that indicates the object’s class, followed by a member code that points to the class’ method vector, as shown in the margin. The remaining class-specific members follow code. To locate an OR, the code keeps an OR pointer(ORP) that refers to a fixed offset in the OR; the drawings will assume it points to the start of the OR.

The amount of runtime support that an OOL needs depends heavily on features of the OOL. To explain the range of possibilities, we will begin with single inheritance and an open class structure, using the example shown in Section 5.4.2. From there, we will explore the implications of a closed class structure for method lookup.

Panels(a) and(b) in Fig. 6.3 repeat the example from Chapter 5. Panel(c)shows the runtime structures that might result from instantiating both a Point and a ColorPoint. All of Point, ColorPoint, aPoint and aColorPoint have their own ORs. The OR for class is off-page.

The OR for aPoint is simple. It contains a pointer to aPoint’s class, a pointer to aPoint’s method vector(from class Point), and space for the data members of a Point.

The OR for aColorPoint is equally simple. It contains a pointer to aColorPoint’s class, a pointer to its method vector(from class ColorPoint),and space for the data members of a ColorPoint. The data members are ordered in a prefix-layout scheme, following the discussion on layout for single-inheritance from Section 5.6.3 on page 255. Thus, the inherited data members,x,y, and z, sit at the same offsets as they would in an instance of Point, and the data members declared in ColorPoint sit below them.

The OR for a class has a similar structure. Each OR of class class contains a class pointer. Their code pointers, which are not shown, would lead to

The figure shows complete method vectors in each class, ordered in a prefix layout.

(a) Class Definitions

Class Point { public int x, y; private int z; public void draw() {…}; public void move() {…}; }

Class ColorPoint extends Point { private Color c; public void draw() {…}; public void setc( Color x ) { this.c = x }; }

(b) Corresponding Scope Tables

Class: Point Superclass: none x | int | public y | int | public z | int | private draw | void() | public move | void() | public

Class: ColorPoint Superclass: Point c | Color | private draw | void() | public setc | void() | public

(c) Object Records for Point, ColorPoint, aPoint, and aColorPoint

■ FIGURE 6.3 Object Layout, Linking, and Inheritance. the method vector in class class. The class ORs show the method vector and superclass pointers. Undoubtedly, the OR’s of classes would contain additional class-specific members.

ORs are allocated explicitly when an object is created and deallocated when the object is no longer reachable. Most ORs are heap allocated, because object lifetimes are not typically correlated to a single activation of some method. If an object’s lifetime is bounded by some method’s activation, then its OR can be stored inside the AR created for that method.

Analysis can reveal cases where a heap-allocated OR may be, instead, placed inside some method’s AR. This transformation can reduce both allocation overhead and the cost of heap management.

How does the compiler generate code to invoke a method such as draw? Methods are always invoked relative to some receiver object, say an instance of aColorPoint. For the invocation to be legal, aColorPoint must be visible at the point of the call so that the compiler can discover how to find aColorPoint with a symbol-table lookup. The compiler first looks in the method’s lexical hierarchy, then in the class hierarchy, and, finally, in the global scope. That lookup provides enough information to let the compiler emit code to obtain aColorPoint’s ORP.

Once the compiler has emitted code to obtain the ORP, it can find and retrieve the code-vector pointer at a fixed offset from the ORP. The pointer to draw is at a fixed offset from the start of the code vector.(As drawn, that offset is zero.) The compiler can use draw’s address in a standard procedure call, with one twist-the call passes aColorPoint’s ORP as draw’s implicit first parameter, which is bound to a language-specified name such as this or self.

Careful construction of the runtime data structures allows this strategy to work. The code pointer in aColorPoint’s OR points to the method vector from ColorPoint rather than the one from Point. Thus, invoking draw relative to aColorPoint calls ColorPoint.draw. Invoking draw relative to aPoint would call Point.draw. Finally, casting aColorPoint to be a Point should cause it to use Point’s method vector and call Point.draw.

The example in Fig. 6.3 shows each class with a complete method vector. Thus, ColorPoint’s method vector has pointers to ColorPoint.draw, Point.move, and ColorPoint.setc. The vector embodies the result of resolving those names through the inheritance hierarchy. This scheme achieves the intended result-an object of class x invokes the implementation of a method that is visible from inside class x.

As an alternative, the compiler can represent only ColorPoint’s local methods in its class method vector. A method name would resolve to a coordinate that told the compiler how far up the superclass chain it must run to find the code pointer. The compiler would emit code to chase up the superclass chain to the correct level and then retrieve the code pointer. Complete method vectors save runtime at the expense of a minor increase in runtime space.

The discussion so far suggests that every method call requires a lookup through the receiver’s OR to locate the method’s implementation. In a language with a closed class structure, the compiler can resolve the method name to a specific implementation at compile time and generate a direct call. In C++, for example, the compiler can resolve any method to a concrete implementation at compile time, unless the method is declared as a virtual method-meaning, essentially, that the programmer wants to locate the implementation relative to the receiver’s class.

With a virtual method, dispatch locates an implementation using the appropriate method vector. The compiler emits code to follow the path from OR to class method vector to code pointer, a process often called dynamic dispatch. If, however, the C++ compiler can prove that some virtual method call has a known invariant receiver class, it can generate a direct call, sometimes called static dispatch.

Languages with open class structures may need to rely on dynamic dispatch. If the class structure can change at runtime, the compiler cannot resolve method names to implementations; instead, it must defer this process to run-time. The techniques used to address this problem range from recomputing method vectors when the class hierarchy changes, to recompiling affected classes with a JIT, to runtime name resolution and a runtime search in the class hierarchy.

■ If the class hierarchy changes infrequently, the implementation may simply rebuild method vectors for the affected classes after each change. In this scheme, the runtime system must traverse the superclass hierarchy to locate method implementations when it builds subclass method vectors. Changes in class structure invalidate any JIT-compiled code for related methods(see Chapter 14).

■ If the class hierarchy changes often, the implementation may keep incomplete method vectors in each class-that is, a class’ method vector only holds pointers to methods that are local to that class. In this scheme,

The process of calling a method is often called dispatch, a term derived from the message-passing model of OOLs such as SMALLTALK.

METHOD CACHES To support an open class hierarchy, the compiler may need to produce a search key for each method name and maintain a runtime-searchable map of {class, key} pairs to implementations. In such a scheme, method dispatch includes a search, by key, through tables in the class hierarchy.

To improve method lookup in this situation, the runtime system can implement a method cache—a software analog of a processor’s data cache. Each method cache entry consists of a key, a class, and a code pointer. A dynamic dispatch begins with a lookup in the method cache; if it finds the {class, key} pair then it returns the code pointer. If the lookup fails, the dispatch searches up the superclass chain from the receiver’s class. When it finds the method, it caches that result and returns the code pointer.

Of course, creating the new entry may force eviction of some other cache entry. Standard cache replacement policies, such as least recently used or round robin, can select the method to evict. Larger caches retain more information, but require more memory and may take longer to search.

To capture type locality at individual calls, some systems use an inline method cache, a single-entry cache located at each call site. The cache stores the receiver’s class and the code pointer from the last execution of that site. If the current receiver’s class matches the cached class, the call uses the cached code pointer. If the current receiver’s class does not match the cached class, a full lookup is performed; that lookup records its result in the cache.

A change to the class hierarchy must invalidate the affected entries in the method caches. The implementation could clear the method cache and any inline caches; they will refill as the code executes. An alternative solution that works well with inline caches is to generate a new tag for each affected class. The old tags will not match. New lookups will find the new methods. The outdated entries will eventually be evicted.

Keys might be kept in a table local to the class; alternatively, the method vector could consist of {key, address} pairs.

a call to a superclass method triggers a runtime search in the class hierarchy for the first method of that name.

In either case, the language runtime will need lookup tables of method names—either source-level names or search keys derived from those names. Conceptually, each class needs a small dictionary. Runtime name resolution looks up the method name in the hierarchy, in a manner analogous to the chain of symbol tables described in Section 4.5.1.

OOL implementations use two general strategies to reduce the cost of dynamic dispatch. They analyze the code to prove that a given call site always uses a receiver of the same known class, in which case they rewrite the call as a static dispatch. For calls where the receiver’s class either varies or is unknown, the implementation can cache search results to speed up subsequent calls. In such a scheme, the dispatch search looks in a method cache before it searches the class hierarchy. If the search finds the receiver’s class and the method name in the cache, the call uses the cached method pointer.

Algol-like languages typically use lexical scoping, in which name spaces are properly nested and new instances of a name obscure older ones. Each call creates an activation record for the callee, which includes the callee’s local data area. Object-oriented languages add an inheritance-based hierarchy to the name space, based on the class definitions. This dual-hierarchy name space leads to more complex interactions among names and to more complex implementations.

Both styles of naming require runtime structures to reflect and implement the naming hierarchy. In an ALL, activation records capture the structure of the name space, provide the necessary storage for most values, and preserve the state necessary for correct execution. In an OOL, activation records for methods still capture the lexically scoped part of the name space and the execution state. However, the implementation also needs a hierarchy of object records to capture the inheritance-based name space.

  1. In C, set jmp and long jmp provide a mechanism for interprocedural transfer of control. set jmp builds a structure to encapsulate the runtime environment; invoking long jmp on that environment restores the environment and lets execution continue as if the most recent set jmp had just returned. What information must set jmp preserve? How does the implementation of set jmp change between stack-allocated and heap-allocated ARs?
  2. Consider the example from Fig. 6.3. If the programmer casts aColorPoint to class Point, what actions must the generated code take to enforce that cast and to produce the correct behavior? (Recall that the effect of a cast is local, so that the code should not permanently change the receiver’s OR.

The central notion underlying the concept of a procedure is abstraction. The programmer abstracts common operations relative to a small set of names, or formal parameters, and encapsulates those operations in a procedure. To use the procedure, the programmer invokes it with an appropriate binding of values, or actual parameters, to those formal parameters. The callee executes, using the formal parameter names to access the values passed as actual parameters. If the programmer desires, the procedure can return a result.

Parameter binding maps the actual parameters at a call site to the callee’s formal parameters. It lets the programmer write a procedure without knowledge of the contexts in which it may be called. It lets the programmer invoke the procedure from many distinct contexts without exposing details of the procedure’s internal operation to each of its callers. Thus, parameter binding plays a critical role in our ability to write abstract, modular code.

Most modern programming languages use one of two conventions for mapping actual parameters to formal parameters: call-by-value binding and call-by-reference binding. These techniques differ in their behavior. The distinction between them may be best explained by understanding their implementations.

Call by Value

Consider the following C code—a procedure fee and several call sites that invoke fee:

int fee(int x, int y) { c = fee (2,3); x = 2 * x; a = 2; y = x + y; b = 3; return y; c = fee(a,b); } a = 2; b = 3; c = fee(a,a);

Call by value

a convention where the caller evaluates the actual parameters and passes their values to the callee

Any modification to a call-by-value parameter in the callee is not visible in the caller.

With call-by-value parameter passing, as in C, the caller copies the value of an actual parameter into the appropriate location for the corresponding formal parameter—either a register or a parameter slot in the callee’s AR. Only one name refers to that value—the name of the formal parameter. Its value is an initial condition, determined by evaluating the actual parameter at the time of the call. If the callee changes its value, that change is visible inside the callee, but not in the caller.

The three invocations produce the following results when invoked using call-by-value parameter binding:

Call by a b Return Value in out in out Value fee (2,3)-7 fee(a,b) 2 2 3 3 7 fee(a,a) 2 2 3 3 6

With call-by-value, the binding is simple and intuitive.

One variation on call-by-value binding is call-by-value-result binding. In this scheme, the values of formal parameters are copied back into the corresponding actual parameters as part of the return from the callee. The programming language ADA includes value-result parameters. Some FORTRAN 77 implementations used value-result binding.

With a call-by-reference parameter, the caller passes an address rather than a value. If the actual parameter resides in memory, the caller passes its memory address. If the actual parameter is an expression, the caller evaluates the expression, stores its value into the caller’s local data area, and passes the address of that location. Values kept in registers and constants should be handled in the same way as expressions. Inside the callee, each reference to a formal parameter needs an extra level of indirection.

Call by reference differs from call by value in two critical ways. First, if the caller passes a variable x as a call-by-reference actual parameter bound to y in the callee, then any change to y is also a change to x. Second, if the callee can access x directly, then it has two names inside the callee, which can lead to counterintuitive behavior. When the callee has two names for one storage location, we say that the names are aliases.

Consider the earlier example, rewritten in PL/I, which uses call-by-reference parameter binding.

fee: procedure(x,y)c=fee (2,3);returns fixed binary;a=2;declare x,y fixed binary;b=3;x=2*x;c=fee(a,b);y=x+y;a=2;return y;b=3;end fee;c=fee(a,a);

With call-by-reference parameter binding, the example produces different results. The first call is straightforward. The second call redefines both a

a convention where the compiler passes an address for the actual parameter to the callee

If the actual parameter is a variable, then changing the formal’s value also changes the actual’s value. 290 Chapter 0 Implementation Procedures

Alias When two names can refer to the same location, they are said to be aliases. In the example, the call fee(a,a) creates an alias between x and y inside fee.

and b; those changes would be visible in the caller. The third call causes x and y to refer to the same location, and thus, the same value. This alias changes fee’s behavior. The first assignment sets both a and b to the value 4. The second assignment then sets both a and b to the value 8, and fee returns 8. A call to fee (2,2), with literal constants, would instead return 6.

Call by Reference in a out b Return Value fee (2,3) - - - 7 fee(a,b) 2 4 3 7 7 fee(a,a) 2 8 3 3 8

Space for Parameters The size of the representation for a parameter has an impact on the cost of procedure calls. Scalar values, such as variables and pointers, are stored in registers or in the parameter area of the callee’s AR. With call-by-value parameters, the actual value is stored; with call-by-reference parameters, the address of the parameter is stored. In either case, the cost per parameter is small—typically a single store operation.

Large values, such as arrays, records, or structures, pose a problem for call by value. If the language requires that large values be copied, the overhead of copying them into the callee’s parameter area will add significant cost to the procedure call. (In this case, the programmer may want to model call by reference and pass a pointer to the entity rather than the entity itself.) Some languages allow the implementation to pass such entities by reference. Other languages include provisions that let the programmer specify that passing a particular parameter by reference is safe and acceptable; for example, adding the const attribute to a parameter in a C function prototype assures the compiler that the parameter is not modified by a call to the function.

With call-by-value parameters, some linkage conventions designate the register reserved for the first parameter as the register to hold the return value. To return a value from a function, the compiler must set aside space for the returned value. Because the return value, by definition, is used after the callee terminates, it needs storage outside the callee’s AR. If the compiler writer can ensure that the return value is of small fixed size, then it can store the value either in the caller’s AR or in a designated register. All of our pictures of the AR have included a slot for a returned value. To use this slot, the caller allocates space for the returned value in its own AR

ALGOL introduced call-by-name parameter binding. In call-by-name binding,a reference to a formal parameter behaves as if the actual parameter had been textually substituted in its place, with appropriate renaming. This simple rule can lead to complex behavior. Consider the following short example in ALGOL-60:

begin comment Simple array example; procedure zero(Arr, i, j, u1, u2); integer Arr, i, j, u1, u2; begin; for i := 1 step 1 until u1 do for j := 1 step 1 until u2 do Arr := 0; end; integer array Work[1:100,1:200]; integer p, q, x, y; x := 100; y := 200; zero(Work[p,q], p, q, x, y); end

The call to zero assigns zero to every element of the array Work. To see this, rewrite zero with the text of the actual parameters.

While call-by-name binding was easy to define, it was difficult to implement and to understand. In general, the compiler must produce, for each formal parameter, a function that evaluates the actual parameter to return a pointer. These functions are called thunks. Generating competent thunks was complex; evaluating a thunk for each parameter access was expensive. In the end, these disadvantages overcame any advantages that call-by-name parameter binding offered.

The programming language R uses call-by-name to create lazy parameters.A call creates and passes thunks, or promises. The code evaluates the thunk when the parameter is first referenced and stores its result for later references.

and stores a pointer to that space in the return-value slot of its own AR.The callee can load the pointer from the caller’s return-value slot (using the copy of the caller’s ARP that it has in the callee’s AR). With that pointer, the callee can access the space in the caller’s AR set aside for the returned value. As long as both caller and callee agree about the size and type of the returned value, this approach works. If the caller cannot know the size of the returned value, the callee may need to allocate space for it, presumably on the heap. In this case, the callee allocates the space, stores the returned value there, and stores the pointer in the return-value slot of the caller’s AR. On return, the caller can access the return value using the pointer that it finds in its return-value slot. The heap space must be reclaimed, explicitly by the caller or implicitly through collection.

If the return value is small—the size of the return-value slot or less—then the compiler can eliminate the indirection. Instead, the callee can store the value directly into the return value slot of the caller’s AR. The caller can then use the value directly from its AR. This improvement requires, of course, that the compiler handle the value in the same way in both the caller and the callee. Fortunately, type signatures for procedures can ensure that both compiles have the requisite information.

6.4.3 Establishing Addressability for Nonlocal Variables

Section titled “6.4.3 Establishing Addressability for Nonlocal Variables”

As part of the linkage convention, the compiler must ensure that each procedure can generate an address for each variable that it needs to reference. In general, the address calculation consists of two portions: finding the base address of the appropriate data area for the scope that contains the value, and finding the correct offset within that data area. The problem of finding base addresses divides into three cases: data areas with static base addresses, data areas whose addresses cannot be known until runtime, and heap-allocated objects.

Compilers typically arrange for global data areas and static data areas to have static base addresses. To generate an address for a variable in one of these areas, the compiler emits code to compute the data area’s base address into a register and to add the variable’s offset to that base address. These computations are so common that most ISAs include address modes to represent them and to ensure that they execute efficiently. For example, ILOC has a “register + immediate” mode (loadAI) and a “register + register” mode (loadAO).

To generate the runtime address of a static base address, the compiler attaches a symbolic, assembly-level label to the data area. Depending on the target machine’s instruction set, that label might be used in a load immediate operation or it might be used to initialize a slot in the constant pool, in which case it can be moved into a register with a standard load operation. The compiler constructs the label for a base address by mangling the name. Typically, it adds a prefix, a suffix, or both to the original name, using characters that are legal in the assembly code but not in the source language. For example, mangling the global variable name fee might produce the label &fee.; the label is then attached to an assembly-language pseudooperation that reserves space for fee. To move the address into a register, the compiler might emit an operation such as loadI &fee. => r1. Subsequent operations can then use r1 to access the memory location for fee. The label becomes a relocatable symbol for the assembler and the loader, which convert it into a runtime virtual address.

Global variables may be labeled individually or in larger groups. In FORTRAN, for example, the language collects global variables into common blocks. A typical FORTRAN compiler establishes one label for each common block. It assigns an offset to each variable in each common block and generates load and store operations relative to the common block’s label. If the data area is larger than the offset allowed in a “register + offset” operation, it may be advantageous to have different labels for different parts of the data area.

Similarly, the compiler may combine all the static variables in a single scope into one data area. This reduces the likelihood of an unexpected naming conflict; such conflicts are discovered during linking or loading and can be confusing to the programmer. To avoid such conflicts, the compiler can base the label on a globally visible name associated with the scope. This strategy decreases the number of base addresses in use at any time, which may reduce demand for registers. Using too many registers to hold base addresses may adversely affect overall runtime performance.

Accessing a local variable of the current procedure is straightforward. While its virtual address is unknowable at compile time, its base address is simply the address of the current AR, recorded in the ARP. Further, the compiler knows the variable’s offset in the local data area of that AR. (The compiler assigned that offset during storage assignment and carried it in the variable’s static coordinate.) Thus, the compiler can emit code that adds the variable’s offset to the ARP to produce its virtual address. Almost all processors provide an address mode to support this kind of base + offset memory operation. In ILOC those operations are loadAI, loadAO, storeAI, and storeAO.

In some cases, a value is not stored at a constant offset from the ARP. The value might reside in a register, in which case loads and stores are not Name mangling the process of constructing a unique string from a source-language name If the value of &fee. is too long for an immediate load operation, the compiler may need to store the address in a known location and load it from there. needed. If the variable has an unpredictable or changing size, the compiler will store it in an area reserved for variable-size objects, either at the end of the local data area or in the heap. In this case, the compiler can reserve space in the AR for a pointer to the variable’s actual location, access the pointer through an ARP + offset operation, and then use the pointer to access the variable.

To access a local variable of some enclosing lexical scope, the compiler must arrange for the construction of runtime data structures that support the task of finding the local data areas of such scopes. It must also emit code that uses those structures to find the needed virtual address.

For example, assume that procedure fee, at lexical level m, references variable x defined at lexical level n in procedure fie, n < m. The parser can construct the static coordinate for x, ⟨n, o⟩, where o is x’s offset in the AR for fie. To convert ⟨n, o⟩ into a runtime address, the compiler emits code that uses n to find the ARP of the most-recently created level n procedure, and then adds o to that ARP to compute x’s runtime virtual address.

Of course, this plan relies on the availability of runtime data structures that can find the level n ARP. The compiler must emit code to build and maintain those structures. The two most common methods are called access links and a global display. The following subsections explore each of them.

The intuition behind access links is simple. The compiler ensures that each AR contains a pointer, called an access link or a static link, to the AR of its immediate surrounding scope. The access links form a chain that includes all the lexical ancestors of the current procedure, as shown in Fig. 6.4. Thus, any local variable of another procedure that is visible to the current procedure is stored in an AR on the chain of access links that begins in the current procedure.

To access a value ⟨n, o⟩ from a level m procedure, the compiler emits code to walk the chain of links and find the level n ARP. Next, it emits a load that uses the level n ARP and o. To make this concrete, consider the program represented by Fig. 6.4. Assume that m is 2 and that the access link is stored at an offset of -4 from the ARP. The following table shows a set of three different static coordinates alongside the ILOC code that a compiler might generate for them. Each sequence leaves the result in r₂.

Figure 6.4 shows access links in activation records at lexical levels 2, 1, and 0. Each record contains the standard local-data, caller, addressability, return-address, return-value, register-save, and parameter areas; the access link follows the static nesting chain from the current procedure toward its lexical ancestors.

ARP
|
v
+---------------------------------------------------------------+
| Level 2 | Local Data | Caller's ARP | Addressability | ... |
+---------------------------------------------------------------+
|
v
+---------------------------------------------------------------+
| Level 1 | Local Data | Caller's ARP | Addressability | ... |
+---------------------------------------------------------------+
|
v
+---------------------------------------------------------------+
| Level 0 | Local Data | Caller's ARP | Addressability | ... |
+---------------------------------------------------------------+

Figure 6.4 Using Access Links

CoordinateCode
(2,24)loadAI r_arp, 24 => r2
(1,12)loadAI r_arp, -4 => r1
loadAI r1, 12 => r2
(0,16)loadAI r_arp, -4 => r1
loadAI r1, -4 => r1
loadAI r1, 16 => r2

Since the compiler has the static coordinate for each reference, it can generate code to follow the access-link chain from the current ARP to the ARP for the procedure at the referenced lexical level. For a reference at lexical level q from a procedure at lexical level p, it can generate a sequence of p - q + 1 loads to find this ARP and store that pointer as the callee’s access link.

In this scheme, the compiler allocates a single global array, called the display, to hold the ARP of the most recent activation of a procedure at each lexical level. References to local variables of other procedures become indirect references through the display. To access a variable with static coordinate ⟨n,o⟩\langle n,o\rangle , the compiler first retrieves the level n ARP from the display. Then, it uses that ARP along with the offset o in a base+ offset load or store operation. References to local variables of the current procedure can still use the ARP directly from rarp.

Fig. 6.5 shows the program state from Fig. 6.4 represented with a global display instead of access links. The display has one entry per lexical level in the program. The display, itself, can be statically allocated and assigned a known mangled label. Unused display entries contain an invalid pointer.

Using the same static coordinates as in the discussion of access links, the compiler might emit the following code for a display-based implementation. Assume that the current procedure is at lexical level 2, and that the label&disp_: gives the display’s address.

CoordinateCode
(2,24)loadAI r_grp, 24r₂
(1,12)loadI &dispr₁
loadAI r₁, 4r₁
loadAI r₁, 12r₂
(0,16)loadI &dispr₁
loadAI r₁, 0r₁
loadAI r₁, 16r₂

With a display, the cost of nonlocal access is fixed. With access links, the compiler generates a series of m−n loads; with a display, it uses n×l as an offset into the display, where l is the length of a pointer (4 in the example). Local access is still cheaper than nonlocal access, but with a display, the penalty for nonlocal access is constant.

Of course, the compiler must insert code where needed to maintain the display. Thus, when procedure p at level n calls some procedure q at level n+1,p’s ARP becomes the display entry for level n. (While p is executing, that entry is unused.) The simplest way to maintain the display is to have p update the level n entry when control enters p, to replace that entry with its own ARP, and to restore the original entry on exit from p.

The compiler can avoid some of these display updates. If procedure p does not call procedures that are nested within it, then its own ARP cannot be used in a nonlocal access and p need not update the display. This observation eliminates many of the unneeded updates.

p can save the old level n display entry in the addressability slot of p’s own AR.

To do a complete job of eliminating unneeded updates, the compiler would need to know which nonlocal variables each procedure referenced.

The ability to map values into and out of procedures is part of what makes procedures useful. Two distinct mechanisms are involved: parameter binding and direct access to names in surrounding scopes. For parameters, languages specify different mechanisms that the compiler must implement. For nonlocal accesses, the compiler must plan and maintain runtime structures that point to the appropriate data areas.

The most confusing aspect of this material is the distinction between compile-time actions, such as the parser computing a static distance coordinate, and runtime actions, such as the code tracing up a chain of access links. The compiler directly performs the compile-time actions. For the runtime actions, it emits code to perform those actions at runtime.

subroutine change(n) integer n n=n*2 end

program test call change (2) print*,2*2 end

1.An early FORTRAN implementation had an odd bug. The short program in the margin would print, as its result, the value 16. What did the compiler do that led to this result? What should it have done instead?(FORTRAN uses call-by-reference parameter binding.)

  1. One issue in the implementation of closures is the need to keep the relevant ARs alive once a closure is created. What role can access links or a display play in this process? Is one technique better than the other in this situation?

The procedure linkage is a contract between the compiler, the operating system, and the target machine that clearly divides responsibility for naming, allocation of resources, addressability, and protection. The procedure linkage ensures interoperability of procedures between the user’s code, as translated by the compiler, and code from other sources, including system libraries, application libraries, and code written in other programming languages. Typically, all of the compilers for a given combination of target machine and operating system use the same linkage, to the extent possible.

The linkage convention isolates each procedure from the different environments found at call sites that invoke it. Assume that procedure p has an integer parameter x. Different calls to p might bind x to a local variable stored in the caller’s stack frame, to a global variable, to an element of some static array, or to the result of evaluating an integer expression such as y+2.Because the linkage convention specifies how to evaluate the actual parameter and store its value, as well as how to access x in the callee, the compiler can generate code for the callee that ignores the differences between the runtime environments at the different calls sites. As long as all the procedures obey the linkage convention, the details will mesh to create the seamless transfer of values promised by the source-language specification.

The linkage convention is, of necessity, machine dependent. For example, it depends implicitly on information such as the number of registers available on the target machine and the mechanisms for executing a call and a return.

Fig. 6.6 shows how the pieces of a standard procedure linkage fit together. Each procedure has both a prolog and an epilog sequence. Each call site includes both a precall and a postreturn sequence. ■ FIGURE 6.6 A Standard Procedure Linkage.

The precall sequence begins the process that both preserves the caller’s environment and creates the callee’s environment. It allocates space for the callee’s AR. It evaluates the actual parameters and stores the values or addresses in the designated slot in the callee’s AR. It stores the address of the postreturn sequence as the return address. It stores the caller’s ARP in the callee’s AR. It saves any caller-saves registers that must be preserved into the register-save area of the caller’s AR. It may also perform maintenance on the addressability data structures: the access links or the display.

To activate the callee, the precall sequence writes the callee’s ARP into the register designated to hold the current ARP and jumps to the callee’s prolog code.

The prolog sequence finishes the process that both preserves the caller’s environment and creates the callee’s new environment. It saves any callee-saves registers that the callee will use. It may need to allocate space for the callee’s local data area. It may need to load the base addresses for any static or global data areas that the callee references. It may also perform maintenance on the addressability data structures: the access links or the display. Finally, it performs any initializations of local variables. At that point, it begins to execute the code for the callee’s body.

The epilog sequence starts the process that dismantles the callee’s environment and reestablishes the caller’s environment. If the procedure returns a value, the epilog may store that value into the address specified by the caller.(Alternatively, the code generated for a return statement may perform this task.) The epilog restores any callee-saves registers that the prolog saved.It may also perform maintenance on the addressability data structures: the access links or the display. If the callee’s local data area was allocated separately from its AR, the epilog frees that space. Finally, it loads the return address, restores the caller’s ARP, and jumps to the return address.

The postreturn sequence completes the process that restores the caller’s environment. It frees the callee’s AR. It restores any call-by-reference actual parameters that need to be returned to registers. It restores any caller-saves registers that the precall sequence saved. Finally, it continues execution of the caller at the point after the call.

This framework provides general guidance for building a linkage convention. Many of the tasks can be shifted between caller and callee. In general, moving work into the prolog and epilog code produces more compact code. The precall and postreturn sequences are generated for each call, while the prolog and epilog occur once per procedure. If procedures are called, on average, more than once, then there are fewer prolog and epilog sequences than precall and postreturn sequences.

Many of the values shown in the AR diagrams can be passed to the callee in registers. The return address, the address for the return value, and the caller’s ARP are obvious candidates. Many conventions pass the first k actual parameters in registers-a typical value for k might be 3 or 4. If the call has more than k parameters, the remaining actual parameters can be stored in the callee’s AR.

At some point in the call sequence, any register values that the caller expects to survive across the call must be saved into memory. Either the caller or the callee can perform the actual save; each choice has advantages and disadvantages. If the caller saves the registers, it can avoid saving values that it knows are not live across the call; that knowledge might allow it to save and restore fewer values. Similarly, if the callee saves the registers, it can avoid saving values in registers that it does not use; again, knowledge of register use in the callee might reduce saves and restores at the call.

In general, the compiler can use its knowledge of the procedure being compiled to optimize register save behavior. For any specific division of labor between caller and callee, we can construct programs for which it works

A value is live across a call if its value is created before the call and that value is used after the call. MORE ABOUT TIME In a typical system, the linkage convention is negotiated between compiler writers and operating-system implementors at an early stage of system development. Thus, issues such as the distinction between caller-saves and callee-saves registers are decided at design time. When the compiler runs, it must emit procedure prolog and epilog sequences for each procedure, along with precall and postreturn sequences for each call site. This code executes at runtime. The compiler cannot know the return address that it should store into a callee’s AR. (Neither can it know, in general, the address of that AR.) It can, however, include a mechanism that will generate the return address at link time (using a relocatable assembly language label) or at runtime (using some offset from the program counter) and store it into the appropriate location in the callee’s AR.

Similarly, in a system that uses a display to provide addressability for local variables of other procedures, the compiler cannot know the runtime addresses of the display or the AR. Nonetheless, it emits code to maintain the display. The mechanism that achieves this requires two pieces of information: the lexical nesting level of the current procedure and the address of the global display. The former is known at compile time; the latter can be determined at link time by using a relocatable assembly language label. Thus, the prolog can simply load the current display entry for the procedure’s level (using a 1oadA0 from the display address) and store it into the AR (using a storeA0 relative to the ARP). Finally, it stores the address of the new AR into the display slot for the procedure’s lexical level.

well and programs for which it does not. Most modern systems take a middle ground and designate a portion of the register set for caller-saves treatment and a portion for callee-saves treatment. In practice, this seems to work well. It encourages the compiler to put long-lived values in callee-saves registers, where they will be stored only if the callee actually needs the register. It encourages the compiler to put short-lived values in caller-saves registers, where it may avoid saving them at a call.

Allocating the Activation Record In the general case, both the caller and the callee need access to the callee’s AR. Unfortunately, the caller cannot know, in general, how large the callee’s AR must be (unless the compiler and linker can contrive to have the linker paste the appropriate values into each call site).

With stack-allocated ARs, a middle ground is possible. Since allocation consists of incrementing the stack-top pointer, the caller can begin the creation of the callee’s AR by bumping the stack top and storing values into the appropriate places. When control passes to the callee, it can extend the partially built AR by incrementing the stack top to create space for local data. The postreturn sequence can then reset the stack-top pointer, performing the entire deallocation in one step.

With heap-allocated ARs, it may not be possible to extend the callee’s AR incrementally. In this situation, the compiler writer has three choices.

  1. The compiler can pass the values that it must store in the callee’s AR in registers or in the caller’s own AR. The prolog sequence can then allocate an appropriately sized AR and store the passed values in it. The parameter values might go into the caller’s AR. Access to those parameters could use the copy of the caller’s ARP that is saved in the callee’s AR.

  2. The compiler writer can split the AR into multiple distinct pieces: one to hold the parameter and control information generated by the caller and the others to hold space needed by the callee but of a size unknown to the caller. Because the caller cannot, in general, know how large to make the local data area, it can let the callee allocate its own local data area. The callee might dedicate a register to hold the base address of that local data area.

  3. The compiler could use a scheme where each procedure creates an initialized static constant using a mangled label. The compiler can store procedure fee’s local data area size in a label mangled from “fee.”Any call to fee can load that constant and use it to size the local data area.

Heap-allocated ARs increase the cost of a procedure call. Careful implementation can reduce those costs.

Whether the compiler writer chooses to use access links or a display, either mechanism requires some work in the calling sequence. With a display, the prolog updates the display record for its own level and the epilog restores it. If the procedure never calls a more deeply nested procedure, it can skip this step. With access links, the precall must find the appropriate first access link for the callee. The amount of work varies with the difference in lexical level between caller and callee. As long as the callee is known at compile time, either scheme is reasonably efficient. If the callee is unknown(if it is, for example, a function-valued parameter), the compiler may need to emit special-case code to perform the appropriate steps.

The linkage convention is a social contract between the compiler, the operating system, and the underlying hardware. It governs the transfer of control between procedures, the preservation of the caller’s state, the creation of the callee’s state, and the rules for passing values between them.

Standardized linkages enable the assembly of executable programs from code written by different people and compiled at different times. They ensure that each procedure can operate safely and correctly. The same conventions let applications invoke system calls and library routines. While the details of the linkage convention vary across systems, the basic concepts are similar across most target machines, operating systems, and compilers.

  1. What role does the linkage convention play in the construction of interlanguage programs? What facts might the compiler need to know in order to generate code for an interlanguage call?

  2. If, at a call, the compiler knows that the callee does not contain any procedure calls, what steps might it omit from the calling sequence? Are there fields in the AR that the callee would never need?

The compiler must arrange for the allocation of space to hold both user defined data and runtime support structures. Often, those structures have lifetimes that do not fit well into the first-in first-out discipline of a stack. In such cases, the language implementation allocates space in the runtime heap-a region of memory set aside for such objects and managed by routines in a runtime support library. The compiler must also arrange storage for other objects that have lifetimes unrelated to the flow of control, such as most of the objects in a JAVA program.

We assume a simple interface to the heap, namely, a routine allocate(size) and a routine free(address). The allocate routine takes an integer argument size and returns the address of a block of space in the heap that contains at least size bytes. The free routine takes the address of a block of previously allocated space in the heap and returns it to the pool of free space. The critical issues that arise in designing algorithms for explicitly managing the heap are the efficiency of both allocate and free and the extent to which the pool of free space becomes fragmented into small blocks.

This section sketches the algorithms involved in allocation and reclamation of space in a runtime heap. Section 6.6.1 describes first-fit allocation for the heap and expands on that technique to develop the notion of multipool allocators. Section 6.6.2 examines implicit schemes for storage deallocation and reclamation, which eliminate the need for the code to explicitly free heap-based storage.

Most language implementations include a runtime system that provides support functions for the code generated by the compiler. That support typically includes routines to manage a runtime heap. The heap management support may be language specific, as in a SCHEME interpreter or a JAVA virtual machine, or it may be part of the operating system, as in the POSIX implementations of malloc and free.

Many techniques have been proposed to implement allocate and free. Most of those implementations share common strategies and insights. This section explores a simple strategy, first-fit allocation, that exposes most of the issues, and then shows how a strategy such as first fit is used to implement a modern allocator.

The primary focus of a first-fit allocator is the speed of allocate and free. Speed takes precedence over efficient use of memory. Blocks contain a hidden size field, typically located before the address returned by allocate; see Fig. 6.7(a). The allocator maintains a list of available blocks, called the free list. Blocks on the free list have additional fields, as shown in Fig. 6.7(b).Each free block keeps a pointer to the next block on the free list(set to null in the last block) and a pointer to the block itself in its last word of the block. The allocator initializes the heap to contain a single large block of free memory.

To reduce fragmentation, the allocator can maintain a minimum block size,s. It will then only split a block if both of the resulting blocks have size greater than or equal to s.

A call to allocate(k) causes the following sequence of events: The allocate routine walks the free list until it discovers a block with size greater than or equal to k plus one word for the size field. Assume that it finds an appropriate block, b. It removes b; from the free list. If b;is larger than necessary, allocate creates a new free block from the excess space at the end of b; updates all of the relevant fields in b; and the new block, and puts the new block on the free list. Finally, allocate returns a pointer to the appropriate offset inside b.

If allocate does not find a large enough block, it tries to extend the heap. If it succeeds, it returns a block of appropriate size from this newly allocated portion of the heap. If extending the heap fails, allocate reports failure.

size

(b) Free Block

■ FIGURE 6.7 Blocks in a First-Fit Allocator.

Section titled “■ FIGURE 6.7 Blocks in a First-Fit Allocator.”

To deallocate a block, the program calls free with the address of the block.bj. The simplest implementation of free addsbj to the head of the free list and returns. This approach is fast. Unfortunately, it leads to an allocator that, over time, fragments memory into small blocks.

To overcome this flaw, the allocator can use the pointer at the end of a freed block to coalesce adjacent free blocks. The free routine loads the word preceding bj’s size field, which is the end-of-block pointer for the block that immediately precedes bj in memory. If that word contains a valid pointer, and it points to a matching block header(one whose address plus size field points to the start of bj), then both bj and its predecessor are free. The free routine can combine them by increasing the predecessor’s size field and storing the appropriate pointer at the end of bj. If the predecessor block is allocated, then free addsbj to the start of the free list.

To make this scheme work, allocate and free must maintain the end-of-block pointers. Each time that free processes a block, it must update that pointer with the address of the head of the block. The allocate routine must invalidate either the next pointer or the end-of-block pointer to prevent free from coalescing a freed block with an allocated block in which those fields have not been overwritten.

The free routine can also try to combine bj with its successor in memory, bk. It can use bj’s size field to locate the start of bk. It can use bk’s size field and end-of-block pointer to determine if bk is free. If bk is free, then free can combine the two blocks by removing bk from the free list, adding bj to the free list, and updating bj’s size field and end-of-block pointer appropriately. To make the free-list update efficient, the free list should be a doubly-linked list. The overhead for the doubly-linked list is minimal.

As described, the coalescing scheme depends on the fact that the relationship between the pointers in a free block will not occur in an allocated block. While it is extremely unlikely that the allocator will identify an allocated block as free, it could happen. To ensure against this event, the implementor can require that the end-of-block pointer exists in both allocated and free blocks. If allocate sets the pointer to zero and free sets it to the block’s own address, the allocator should never misidentify an allocated block.

Inside the compiler itself, the compiler writer may find it profitable to use a specialized allocator. Compilers have phase-oriented activity, which lends itself well to an arena-based allocation scheme.

With an arena-based allocator, the program creates an arena-a pool of contiguous memory in the heap-at the beginning of an activity. It uses the arena to hold allocated objects that are related in their use. Calls to allocate objects in the arena are satisfied in a stack-like fashion. An allocation involves incrementing a pointer to the arena’s high-water mark and returning a pointer to the newly allocated block. No call is used to deallocate individual objects; they are freed en masse when the arena that contains them is deallocated.

The arena-based allocator is a compromise between traditional allocators and collecting allocators. With an arena-based allocator, the calls to a11ocate can be made lightweight(as in a multipool allocator). No freeing calls are needed; the program frees the entire arena in a single call when it finishes the activity for which the arena was created.

Many variations on first-fit allocation have been tried. They trade off the cost of allocate, the cost of free, the amount of fragmentation produced by a long series of allocations, and the amount of space wasted by returning blocks larger than requested.

Multipool allocators build on first-fit allocation but simplify it based on observations about the behavior of programs. As memory sizes grew in the early 1980s, it became reasonable to waste some space if doing so led to faster allocation. At the same time, studies of program behavior suggested that real programs allocate memory frequently in a few common sizes and infrequently in large or unusual sizes.

Modern allocators use separate memory pools for several common sizes. Typically, selected sizes are powers of two, starting with a small block size(such as 32 or 64 bytes) and running up to the size of a virtual-memory page(typically 4096 or 8192 bytes). Each pool has only one size of block, so allocate can return the first block on the appropriate free list, and free can simply add the block to the head of the appropriate free list. For requests larger than a page, a separate first-fit allocator is used. Allocators based on these ideas are fast. They work particularly well for heap allocation of ARs. These changes simplify both allocate and free. The allocate routine must check for an empty free list and add a new page of appropriately sized blocks to the free list if it is empty. The free routine inserts the freed block at the head of the free list for its size. A careful implementation could determine the size of a freed block by checking its address against the memory segments allocated for each pool. Alternative schemes include using a size field as before, and, if the allocator places all the storage on a page into a single pool, storing the size of the blocks in a page in a designated word on the page.

Programs written with explicit allocation and deallocation are notoriously difficult to debug. It appears that programmers have difficulty deciding when to free heap-allocated objects. If the allocator can quickly distinguish between an allocated object and a free object, then the heap-management software can provide the programmer with some help in debugging.

For example, to coalesce adjacent free blocks, the allocator needs a pointer from the end of a block back to its head. If an allocated block has that pointer set to an invalid value, then the deallocation routine can check that field and report a runtime error when the program attempts to deallocate a free block or an illegal address—a pointer to anything other than the start of an allocated block.

For a modest additional overhead, heap-management software can provide additional help. By linking together allocated blocks, the allocator can create an environment for memory-allocation debugging tools. A snapshot tool can walk the list of allocated blocks. Tagging blocks by the call site that created them lets the tool expose memory leaks. Timestamping them allows the tool to provide the programmer with detailed information about memory use. Tools of this sort can provide invaluable help in locating blocks that are never deallocated.

Many programming languages support implicit deallocation of heap objects. The runtime system deallocates memory objects automatically when they are no longer in use. To perform implicit deallocation, or garbage collection, the compiler and runtime system must include a mechanism for determining when an object is no longer of interest, or dead, and a mechanism for reclaiming and recycling the dead space.

The work associated with storage reclamation can be performed incrementally for individual statements, or it can be performed as a batch-oriented

Decades of experience suggest that programmers are not effective at freeing all the storage that they allocate. They also tend to free objects to which they retain pointers. Implicit deallocation fixes both problems.

Garbage collection the implicit deallocation of objects on the runtime heap

Dead An object is dead when the running code can no longer reach it. task that runs on demand when the free-space pool is exhausted. Reference counting is a classic technique for incremental reclamation. Mark-sweep collection is a classic approach to performing batch-oriented reclamation.

This technique adds a counter to each heap-allocated object. The counter tracks the number of outstanding pointers, or references, that refer to the object. When the allocator creates the object, it sets the reference count to one. Each assignment to a pointer variable adjusts two reference counts. It decrements the reference count of the pointer’s preassignment object and increments the reference count of the pointer’s postassignment object. When an object’s reference count drops to zero, no pointer exists that can reach the object, so the system may safely free the object.

Freeing an object can, in turn, discard pointers to other objects. The code must then decrement the reference counts of those objects. For example, discarding the last pointer to a tree’s root should free the entire tree. When the root node’s reference count drops to zero, it is freed and its descendants’reference counts are decremented. This, in turn, should free the descendants, decrementing the counts of their children. This process continues until the entire tree has been freed.

The presence of pointers in allocated objects creates several challenges for reference-counting schemes, as follows:

  1. The code needs a way to distinguish a pointer from other data in the object. The system can keep a header field on each object where it stores extra information, such as a bitmap that identifies which words in the object are pointers. It can limit the range of pointers to less than a full word and use the remaining high-order bits to “tag” the pointer. It can keep detailed type information at runtime and use that to identify pointers. Note that batch collectors face this same issue and use the same solutions.

  2. A decrement to one reference count, such as the root of a tree, can create a large amount of work. If external constraints require bounded deallo-cation times, as in real-time systems, the runtime system can adopt a scheme that limits the number of objects freed on each pointer assignment. It can keep a queue of objects to free and limit the number freed on each reference-count adjustment. This approach distributes the cost over a larger set of operations and bounds the work done per assignment.

  3. The program might build a cyclic structure in the heap. The reference counts in a cyclic data structure will not reach zero. When the last

external pointer is discarded, the cycle becomes unreachable; its storage cannot be freed by the reference count mechanism. To ensure that cyclic structures are freed, the programmer must break the cycle before discarding the last pointer to the cycle. Many heap-allocated objects, such as variable-length strings and ARs, cannot be involved in such cycles.

Reference counting incurs additional work on every pointer assignment. The amount of work done for a specific pointer assignment can be bounded; in any well-designed scheme, the total cost can be limited to some constant factor times the number of pointer assignments executed plus the number of objects allocated. Proponents of reference counting argue that these overheads are small enough and that the pattern of reuse in reference-counting systems produces good program locality. Opponents of reference counting argue that real programs do more pointer assignments than allocations, so that garbage collection achieves equivalent functionality with less total work.

Batch collectors consider deallocation only when the free-space pool has been exhausted. When the allocator fails to find needed space, it invokes the batch collector. The collector pauses the program’s execution, examines the pool of allocated memory to discover unused objects, and reclaims their space. When the collector terminates, the free-space pool should be nonempty. The allocator can finish its original task and return a newly allocated object to the caller.(As with reference counting, schemes exist that perform collection incrementally to amortize the cost over longer periods of execution.)

Logically, batch collectors proceed in two phases. The first phase discovers the set of objects that can be reached from pointers stored in program variables and compiler-generated temporaries. The collector conservatively assumes that any object reachable in this manner is live and that the remainder is dead. The second phase deallocates and recycles dead objects. Two commonly used techniques are mark-sweep collectors and copying collectors. They differ in their implementation of the second phase of collection-recycling.

Collecting allocators discover live objects with a marking algorithm. The collector needs a bit for each object in the heap, called a mark bit. Conceptually, think of the mark bits as stored in the objects. Mark bits should be created in the “unmarked” or “clear” state.

If the collector cannot free any space, then it must request additional space from the system. If none is available, allocation fails. Clear all marks Worklist ← { pointer values from activation records & registers }

while (Worklist ≠ ∅) do remove p from the Worklist if (p→object is unmarked) then mark p→object add pointers from p→object to Worklist

■ FIGURE 6.8 A Simple Marking Algorithm.

The initial step of the sweep phase builds a worklist that contains all the pointers stored in registers and in variables accessible to active procedures. The second phase of the algorithm walks forward from these pointers and marks every object that is reachable from this set of visible pointers.

Fig. 6.8 shows a high-level sketch of a simple marking algorithm. It halts because the heap is finite and the marks ensure that each pointer enters the Worklist at most once. The cost of marking is proportional to the number of pointers that it examines.

The marking algorithm can be either precise or conservative. The difference lies in how the algorithm determines that a specific data value is a pointer in the final line of the while loop.

■ In a precise marking phase, the compiler and runtime system know the type and layout of each object. This information can be recorded in object headers, or it can be known implicitly from the type system. Either way, the marking phase only follows real pointers.

■ In a conservative marking phase, the compiler and runtime system may be unsure about the type and layout of some objects. Thus, when an object is marked, the system considers each field that may be a possible pointer. If its value might be a pointer, it is treated as a pointer. Any value that does not represent a word-aligned address might be excluded, as might values that fall outside the known boundaries of the heap.

Conservative collectors have limitations. They fail to reclaim some objects that a precise collector would find. Nonetheless, conservative collectors have been successfully retrofitted into implementations for languages such as C that do not normally support garbage collection.

When the marking algorithm halts, any unmarked object must be unreachable from the program. Thus, the second phase of the collector can treat that object as dead. Some objects marked as live may also be dead. However, the collector lets them survive because it cannot prove them to be dead. As the second phase traverses the heap to collect unused storage, it can clear the mark bits.

Mark-sweep collectors reclaim and recycle objects in a linear pass over the heap. The collector adds each unmarked object to the free list (or one of the free lists) where the allocator will find it and reuse it. With a single free list, the same collection of techniques used to coalesce blocks in the first-fit allocator applies. To compact the heap, the collector can incrementally shuffle live objects downward during the sweep or with a postsweep compaction pass.

Copying collectors divide memory into two pools, an old pool and a new pool. The allocator always operates from the old pool. The simplest copying collectors are called stop and copy collectors. When an allocation fails, a stop and copy collector copies all the live data from the old pool into the new pool and swaps the identities of the old and new pools. The act of copying live data compacts it; after collection, all the free space is in a single contiguous block.

Copying can be done in a separate pass, as in mark sweep, or it can be performed incrementally, as live data is identified. An incremental scheme can mark objects in the old pool as it copies them to avoid copying the same object multiple times.

Generational collectors are an important family of copying collectors. They capitalize on the observation that once an object survives one collection, it is more likely to survive subsequent collections. A generational collector uses two “new” pools that it maintains by copying; these pools are sometimes called nurseries. A generational collector also maintains one or more older or stable pools. When the nursery becomes too crowded, the allocator collects and copies the live data from the nursery into the stable pool. Successive collections of the nursery only examine newly allocated objects. Generational schemes vary in terms of how many stable pools they maintain and how often they collect those stable pools.

Garbage collection frees the programmer from thinking about when to release memory and from tracking down the inevitable storage leaks that result from explicit deallocation. While the individual schemes have strengths and weaknesses, the practical benefits of implicit deallocation outweigh the disadvantages for most applications.

Reference counting distributes the cost of deallocation more evenly across program execution than does batch collection. However, it increases the cost of every assignment that involves a heap-allocated value-even if the program never runs out of free space. By contrast, batch collectors incur no cost until the allocator fails to find needed space. At that point, however, the program incurs the full cost of collection. Furthermore, any allocation can provoke a collection.

Mark-sweep collectors examine the entire heap, while copying collectors only examine the live data. Copying collectors actually move every live object, while mark-sweep collectors leave them in place. The tradeoff between these costs will vary with the application’s behavior and with the actual costs of various memory references.

Reference-counting implementations and conservative batch collectors have problems recognizing cyclic structures because they cannot distinguish between references from within the cycle and those from without. The mark-sweep collectors start from an external set of pointers, so they discover that a dead cyclic structure is unreachable. The copying collectors, starting from the same set of pointers, simply fail to copy the objects involved in the cycle.

Copying collectors compact memory as a natural part of the process. The collector can either update all the stored pointers, or it can require use of an indirection table for each object access. A precise mark-sweep collector can compact memory, too. The collector would move objects from one end of memory into free space at the other end. Again, the collector can either rewrite the existing pointers or mandate use of an indirection table.

In general, a good implementor can make both mark sweep and copying work well enough that they are acceptable for most applications. In applications that cannot tolerate unpredictable overhead, such as real-time controllers, the runtime system must incrementalize the process, as the amortized reference-counting scheme does. Such collectors are called real-time collectors.

The primary rationale for moving beyond assembly language was to provide a more abstract programming model and produce improvements in programmer productivity and program understandability. The compiler must be prepared to translate each abstraction that the source language provides.

PYTHON reference counts objects, but invokes a batch collector when it exhausts the heap. The batch collector can reclaim “lost”cyclic structures. This chapter explored techniques used to implement the abstractions introduced by procedure calls.

Procedural programming was invented early in the history of programming. Some of the first procedures were debugging routines written for early computers. These prewritten routines allowed programmers to understand the runtime state of an errant program. Without such routines, simple tasks, such as examining the contents of a variable, tracing the call stack, or printing a dump of the contents of memory, could only be achieved if the programmer entered a long sequence of machine-language code without error.

The advent of lexical scoping in languages such as ALGOL 60 influenced language design for decades. Most modern programming languages inherit some of ALGOL’s philosophy on naming and addressability. Techniques invented to reduce the runtime cost of lexical scoping, such as access links and displays, are widely used today.

OOLs take the scoping concepts of ALLs and reorient them in data-directed ways. These languages typically support both a lexical scoping hierarchy and an inheritance hierarchy. The compiler for an OOL uses both compile-time and runtime structures invented for lexical scoping to model and to implement the naming discipline imposed by the inheritance hierarchy.

As new programming paradigms emerge, they will introduce new abstractions that require careful thought and implementation. By studying the successful techniques of the past and understanding the constraints and costs involved in real implementations, compiler writers will develop strategies that decrease the runtime penalty for using higher levels of abstraction.

Much of the material in this chapter comes from the accumulated experience of the compiler-construction community. The best way to learn more about the name-space structures of various languages is to consult the language definitions themselves. These documents are a necessary part of a compiler writer’s library.

Procedures appeared in the earliest high-level languages—that is, languages that were more abstract than assembly language. FORTRAN [28] and ALGOL 60 [282] both had procedures with most of the features found in modern languages. Early ALGOL 60 implementations developed many of the key ideas that arise in linkage conventions; for example, Ingerman first described thunks for call-by-name parameter passing in 1961 [213]. Object-oriented languages appeared in the late 1960s with SIMULA-67 [287]

followed by SMALLTALK 72[242]. The various SMALLTALK systems used method caches to reduce the cost dynamic dispatch[137,242].

ALGOL 60 introduced lexical scoping; it persists to the present day. Early ALGOL compilers introduced most of the support mechanisms described in this chapter; they implemented activation records, access links, displays, and parameter-passing techniques. Most of the ideas from Sections 6.3 through 6.5 were present in one or more of these early systems[303]. Optimizations to the linkage convention quickly appeared, such as folding storage for a block-level scope into the activation record for the procedure that contained the block. Murtagh took a systematic approach to coalescing activation records, combining the ARs of procedures that are frequently called together[281]. The IBM 370 linkage convention recognized the difference between leaf procedures and others; they avoided allocating a register save area for leaf routines.

The classic reference on memory allocation schemes is Knuth’s Art of Com-puter Programming[240,§2.5]. Modern multipool allocators appeared in the early 1980s. Reference counting dates to the early 1960s and has been used in many systems[102,136]. Schorr and Waite describe an early marking algorithm[319]. Cohen and, later, Wilson provide broad surveys of the literature on garbage collection[99,362]. Conservative collectors were introduced by Boehm and Weiser[48,50,131]. Copying collectors appeared in response to virtual memory systems[86,154]; they led, somewhat naturally, to the generational collectors in widespread use today[255,349]. Hanson introduced the notion of arena-based allocation[189].

1. Show the call tree and execution history for the following C program: Section 6.2

Section titled “1. Show the call tree and execution history for the following C program: Section 6.2”
int Sub(int i, int j) {
return i - j;
}
int Mul(int i, int j) {
return i * j;
}
int Delta(int a, int b, int c) {
return Sub(Mul(b,b), Mul(Mul(4,a),c));
}
void main() {
int a, b, c, delta;
scanf("%d %d %d", &a, &b, &c);
delta = Delta(a, b, c);
if (delta == 0)
puts("Two equal roots");
else if (delta > 0)
puts("Two different roots");
else
puts("No root");
}

2. Some programming languages allow the programmer to use functions in the initialization of local variables but not in the initialization of global variables.

Section titled “2. Some programming languages allow the programmer to use functions in the initialization of local variables but not in the initialization of global variables.”

a. Is there an implementation rationale to explain this seeming quirk of the language definition? b. What mechanisms would be needed to allow initialization of a global variable with the result of a function call?

3. The compiler writer can optimize the allocation of ARs in several ways.

Section titled “3. The compiler writer can optimize the allocation of ARs in several ways.”

For example, the compiler might: a. Allocate ARs for leaf procedures statically. b. Combine the ARs for procedures that are always called together. (When α is called, it always calls β.)

For each scheme, consider the following questions: a. What kind of calls might benefit from the optimization? b. How often do you expect such calls to occur in real programs? c. What is the impact of the optimization on runtime space utilization?

  1. Consider the following definition for class Dog and class Retriever. Draw the structures that the compiler would need to create to support objects of type Retriever, defined as follows:

class Dog { private int Height; private int Weight; public int Sheds;

public int GetHeight();
public int GetWeight();
public boolean PlaysFetch();

}

class Retriever extends Dog { private boolean Calm; public boolean Disposition(); public boolean PlaysFetch(); }

The PlaysFetch method in Dog simply returns false, while the PlaysFetch method in Retriever returns true. The Disposition method in Retriever consults the boolean Calm.

  1. Consider the definitions of Dog and Retriever from the previous question.

a. If a program casts an object of class Retriever to be an object of class Dog, an upcast, what differences in behavior occur? Operationally, how does this upcast work? b. If a program casts an object of class Dog to be an object of class Retriever, a downcast, what differences in behavior would you expect to occur? What problems might arise from a downcast? c. What do you think is a reasonable way for the language to handle attempted downcasts?

  1. As an alternative to a global method cache, an implementation could maintain an inline cache at each call site—a single-entry cache to record the class and method most recently invoked from that site. Develop pseudocode to use and maintain such an inline method cache. Explain the initialization of the inline method caches and any modifications to the general method lookup routine required to support inline method caches.
  2. Consider the following program written in PASCAL-like pseudocode: Section 6.4

procedure main; var a : array[1…3] of integer; i : int; procedure p2(e : integer); begin e := e + 3; a[i] := 5; i := 2; e := e + 4; end; begin a := [1, 10, 77]; i := 1; p2(a[i]); for i := 1 to 3 do print(a[i]); end.

Simulate its execution under call-by-value, call-by-reference, and call-by-name parameter binding rules. Show the results of the print statements in each case.

  1. The use of call-by-reference parameters can create situations where two distinct parameters refer to the same memory location. Consider the following PASCAL procedure, with parameters passed by reference:

procedure mystery(var x, y : integer); begin x := x + y; y := x - y; x := x - y; end;

If the arithmetic does not produce either underflow or overflow: a. What result does mystery produce when it is called with two distinct variables, a and b? b. What would be the expected result if mystery is invoked with a single variable a passed to both parameters? What is the actual result in this case?

  1. Consider the PASCAL program shown in Fig. 6.9(a). Suppose that the implementation uses ARs as shown in Fig. 6.9(b). (Some fields have been omitted for simplicity.) The implementation stack allocates the ARs, with the stack growing toward the top of the page. The ARP

1 program main(input, output); 2 procedure P1(function g(b: integer): integer); 3 var a: integer; 4 begin 5 a := 3; 6 writeln(g(2)) 7 end; 8 procedure P2; 9 var a: integer; 10 function F1(b: integer): integer; 11 begin 12 F1 := a + b 13 end; 14 procedure P3; 15 var a: integer; 16 begin 17 a := 7; 18 P1(F1) 19 end; 20 begin 21 a := 0; 22 P3 23 end; 24 begin 25 P2 26 end.

(b) Activation Record Structure

(c) Initial Activation Record

(a) Example PASCAL Program

■ FIGURE 6.9 Program for Exercise 9.

is the only pointer to the AR, so access links are previous values of the ARP. Finally, Fig. 6.9(c) shows the initial AR for a computation.

a. For the example program in Fig. 6.9(a), draw the set of its ARs just prior to the return from function F1. Use the line numbers to specify return addresses. Draw directed arcs for access links. Show space for local variables and parameters. Label each AR with its procedure name.

b. Show the same state, assuming that the implementation uses a global display rather than access links.

  1. For each of the following actions, does that action belong in the pre-call, prolog, epilog, or postreturn sequence? Give a short justification for your answer. procedure main integer a, b, c b = a + c; c = f1(a,b); call print(c); end;

procedure f1(integer x, y) integer v; v = x * y; call print(v); call f2(v); return -x; end;

procedure f2(integer q) integer k, r; … k = q / r; end;

■ FIGURE 6.10 Code for Exercise 12.

a. store the caller-saves registers b. restore the callee-saves registers c. store the return value d. store the return address e. use the return address

  1. In the design of a linkage convention, some actions can move between the precall sequence and the prolog, or between the epilog and the postreturn sequence.

a. Why might it be good to move something from the precall sequence to the prolog? from the postreturn sequence to the epilog? b. What actions might you be tempted to move between these sequences?

  1. Assume that the compiler is capable of analyzing the code to determine facts such as “from this point on, variable v is not used again in this procedure” or “variable v has its next use in line 11 of this procedure,” and that the compiler keeps all local variables in registers for the three procedures shown in Fig. 6.10.

a. Variable x in procedure f1 is live across two procedure calls. For the fastest execution of the compiled code, should the compiler keep x in a caller-saves register or a callee-saves register? Justify your answer.

b. Consider variables a and c in procedure main. Should the compiler keep them in caller-saves registers or callee-saves registers, again assuming that the compiler is trying to maximize the speed of the compiled code? Justify your answer.

← node-book_engineering-a-compiler_chapter-05-syntax-driven-translation | node-book_engineering-a-compiler | node-book_engineering-a-compiler_chapter-07-code-shape →