Code Shape
local graph
Chapter 7 — Code Shape
Section titled “Chapter 7 — Code Shape”ABSTRACT
Section titled “ABSTRACT”To translate an application program, the compiler must map each source-language statement into a sequence of one or more operations in the target machine’s instruction set. The compiler must choose among many alternative ways to implement each construct. Those choices have a strong and direct impact on the quality of the code that the compiler eventually produces.
This chapter explores some of the implementation strategies that the compiler can employ for a variety of common programming-language constructs, with an emphasis on how to map the source-level constructs into the target machine’s instruction set. Topics include expression evaluation, access methods for variables and aggregate data structures, control-flow constructs, and procedure calls.
KEYWORDS
Section titled “KEYWORDS”Code Generation, Code Quality, Control Structures, Expression Evaluation
7.1 INTRODUCTION
Section titled “7.1 INTRODUCTION”When the compiler translates application code into executable form, it faces myriad choices about specific details, such as the organization of the computation and the location of data. Such decisions often affect the performance of the resulting code. The compiler’s decisions are guided by information that it derives, progressively, over the course of translation. The compiler must encode that derived knowledge into the IR and its ancillary data structures. It encodes some of that knowledge directly in a transparent way. For example, if x is declared as a 64-bit integer, the compiler records that fact in the relevant symbol table.
Other facts are encoded implicitly. For example, if the compiler discovers that y is a local scalar variable and it decides that y is unambiguous, the compiler might encode that decision by keeping y in a virtual register throughout its lifetime. Encoding information about ambituity in this way makes the fact obvious to the rest of the compiler and eliminates the need to rederive this knowledge in later passes. We refer to this kind of implicit encoding of ambiguity can be difficult to manage. Some situations, such as an address-scalar variable, are obvious. Others, such as a C program that performs arithmetic pointers, can require complex analysis. knowledge into the IR program as code shape. The compiler writer makes an explicit decision to shape the IR in a specific way to encode information and, thus, expose it to later passes.
Conceptual Roadmap
Section titled “Conceptual Roadmap”The translation of source code into target-machine operations is one of the fundamental acts of compilation. The compiler must have a plan for each source-language construct. Many of the issues that arise when generating IR in the compiler’s front end also arise when generating assembly code for a real processor in its back end. The target processor may present a more difficult problem due to finite resources and idiosyncratic features, but the principles are the same.
This chapter focuses on ways to implement a variety of source-language constructs in the compiler’s IR. In many cases, specific implementation details affect the compiler’s ability to analyze and to improve the code. The concept of code shape encapsulates all of the decisions, large and small, that the compiler writer makes about how to represent the computation in both IR and assembly code form. Careful attention to code shape can simplify the analysis and improvement of the code and can allow the compiler to produce better final code.
A Few Words About Time
Section titled “A Few Words About Time”At design time, the compiler writer must choose how the IR form of the program will express specific source-language constructs. Those decisions have a direct impact on the efficiency of the final compiled code. This chapter examines a number of source-language constructs and, when appropriate, explores some of the options available to the compiler writer.
Code-shape decisions, made by the compiler writer at design time, can determine the way that the compiler performs translation. To evaluate these choices, the compiler writer needs to consider the impact that the choices may have on later phases of the compiler and, eventually, on runtime performance. Thus, this chapter focuses on the impact that design-time decisions about the shape of the IR have on compile-time and runtime behavior.
Overview
Section titled “Overview”In general, the compiler writer should focus on shaping the code so that later passes in the compiler can produce high-quality code. In practice, a compiler has multiple choices for how to implement many source-language constructs. These different options use different operations and different approaches. Some of these implementations are faster than others; some use
7.1 Introduction
Section titled “7.1 Introduction”Figure 7.1 shows alternate code shapes for the expression x + y + z.
source code: x + y + z
low-level, three-address code: r1 <- rx + ry r1 <- rx + rz r1 <- ry + rz r2 <- r1 + rz r2 <- r1 + ry r2 <- r1 + rx
corresponding trees: + + + / \ / \ / + z + y + x / \ / \ / x y x z y zSome code sequences might consume less energy or execute faster than others. These differences are matters of code shape.
Code shape has a strong impact on both the behavior of compiled code and the ability of the optimizer to improve it. For example, a compiler might implement a switch statement with a cascaded series of tests or with a binary search over keys. For dense keys, it might build a table of labels and jump through the table, introducing constant overhead per character. For sparse keys, a binary-search form may be better.
All of these are legal implementations of the switch statement. The compiler must choose a strategy from facts such as the number of cases and their relative execution frequencies. Those choices determine code shape.
For x + y + z, the source expression gives many legal computation orders. The figure assumes that each variable is in a register and that the source language does not specify the evaluation order.
binary additions exposes the impact of evaluation order. The three versions on the right show three possible evaluation orders, both as three-address code and as abstract syntax trees. If addition is commutative and associative, as integers are, all three orders are equivalent; the compiler must choose one.
Left associativity would produce the first binary tree. This tree seems “natural” in that left associativity corresponds to the left-to-right reading style of programming languages. Consider what happens if we replace y with the literal constant 2 and z with 3. Of course, x+2+3 is equivalent to x+5. The compiler should detect the computation of 2+3, evaluate it, and fold the result directly into the code. In both(x+y)+z and(x+z)+y, the code never evaluates 2+3. By contrast,(y+z)+x explicitly computes 2+3 and exposes the opportunity to replace the subtree with 5. For each prospective tree, however, there is an assignment of variables and constants to x,y, and z that does not expose the constant expression for optimization.
Again, the compiler cannot choose the best shape for this expression unless it understands the surrounding context. If, for example, the expression x+y was computed recently and the values of neither x nor y have changed, then using the leftmost shape would let the compiler replace the first operation, , with a reference to the previously computed value. Often, the best evaluation order depends on context from the surrounding code.
This chapter explores the code-shape issues that arise in implementing many common source-language constructs. It focuses on the code that should be generated for specific constructs, while largely ignoring the algorithms required to pick specific assembly-language instructions. The issues of instruction selection, register allocation, and instruction scheduling are treated separately, in later chapters.
7.2 ARITHMETIC OPERATORS
Section titled “7.2 ARITHMETIC OPERATORS”Modern processors provide broad support for evaluating expressions. A typical RISC machine has a full complement of three-address operations, including arithmetic operators, shifts, and Boolean operators. The three-address form lets the compiler name the result of any operation and preserve it for later reuse. It also eliminates the major complication of the two-address form: destructive operations.
To generate code for a trivial expression, such as a+b, the compiler first emits code to ensure that the values of a and b are in registers, say and .If a is stored in memory at offset@a in the current AR, the compiler might generate the code sequence shown in the margin to move a into register .
expr(node) { int result, t1, t2; switch(type(node)) { case x, +, +, -: t1 ← expr(LeftChild(node)); t2 ← expr(RightChild(node)); result ← NextRegister(); emit(op(node), t1, t2, result); break; case NAME: entry ← STLookup(node); result ← ValueIntoReg(entry); break; case NUMBER: num ← NumberFromNode(node); result ← NumberIntoReg(num); break; } return result; }
(a) Treewalk Code Generator
(b) Abstract Syntax Tree for a - b x c
(c) Naive Code
Figure 7.2 Simple Treewalk Code Generator for Expressions.
(Assume that rarp holds the current ARP.) Once a and b are both in registers, the compiler can emit an add operation to compute their sum.
By contrast, if a’s value already resides in a register, the code can simply reference its register. If both a and b already reside in registers, say ra and rb, then the compiler can simply emit the add operation.
As we saw in Section 5.3, the compiler can easily emit simple code for expressions in a syntax-driven translation framework. If the compiler initially builds a graphical IR, it can generate a linear form later in compilation using a simple treewalk, along the lines of the one shown in Fig. 7.2(a). It relies on several routines, denoted in the algorithm font, to emit code that instantiates the access method for a name or a number. (For more detail, see Section 7.3.)
Panel (b) shows a simple for a - b x c. Panel (c) shows the code that the treewalk code generator would produce for that AST. The example assumes that a, b, and c reside at known fixed offsets from the ARP—at offsets @a, @b, and @c.
GENERATING LOAD ADDRESS IMMEDIATE
Section titled “GENERATING LOAD ADDRESS IMMEDIATE”A careful reader might notice that the treewalk code generator in Fig. 7.2 generates a two-operation sequence, 1oadI followed by 1oadAO, rather than a single 1oadAI operation:
Throughout the book, the examples assume that it is preferable to generate this two-operation sequence, rather than the single operation. Two distinct factors suggest this course.
-
The longer code sequence gives an explicit name to@a. If@a is reused in other contexts, that name can be reused.
-
The offset@a may not fit in the immediate field of a 1oadAI. That determination is best made in the instruction selector.
The compiler can convert the two-operation sequence into one operation during optimization, if legal and appropriate(e.g., either@a is not reused or it is cheaper to reload@a). The best course, however, may be to defer this choice to instruction selection-in effect, isolating the machine-dependent constant length into a phase of the compiler that is already highly machine dependent.
The simple treewalk code generator uses one template for all of+,-,x, and+. It generates code to (1) ensure that the operands are in registers and (2) perform the operation, leaving the result in a new virtual register.
Most other three-address operations can fit into this framework. Some operations, such as exponentiation or a trigonometric function, require complex multioperation sequences for step (2). These may be expanded inline or implemented with a call to a library routine supplied by the compiler or the operating system.
7.2.1 Function Calls in an Expression
Section titled “7.2.1 Function Calls in an Expression”So far, we have assumed that all the operands in an expression are variables, constants, and temporary values produced by other subexpressions. Function calls also occur as operands in expressions. To evaluate a function call, the compiler simply generates the precall sequence needed to invoke the function, followed by the postreturn sequence, which moves the result into the appropriate location in the caller. The linkage convention limits the callee’s impact on the caller.
The presence of a function call may limit the compiler’s ability to reorder the evaluation of subexpressions. The function may have side effects that modify the values of variables used in the expression. The compiler must respect the implied evaluation order of the source expression, at least with respect to the call. Unless it knows about the call’s possible side effects, the compiler cannot move references across the call. It must assume the worst case-that the function both modifies and uses every variable that it can access. The desire to improve on such worst-case assumptions motivated the development of interprocedural summary analysis(see Section 9.4).
7.2.2 Mixed-Type Expressions
Section titled “7.2.2 Mixed-Type Expressions”Most programming languages allow the code to contain an operation that has operands of different types. These languages carefully define the meaning of such a “mixed-type expression.”(We will focus on source-language base types rather than programmer-defined types.)
A typical language definition allows some mixed-type expressions, such as addition of an integer and a floating-point number, and disallows others, such as multiplication by a character string. In the allowed cases, the compiler may need to insert code that converts one or more of the values involved in the expression to another type.
The compiler writer has two choices with implicit conversions: make them explicit early in translation and expect optimization to reduce their cost, or keep them implicit until late in translation to reduce clutter in the IR.
Inserting explicit conversions is simple; as the compiler translates an expression, it applies the conversion rules of the source language. Most of these rules can be expressed in an operator-specific table that gives result type as a function of the operand types. A simple conversion table for+ appears in the margin. The compiler looks up the result type and emits code to convert operands, as necessary, to the result type. It then emits code to perform the operation in the result type.
C and C++ provide base types for many widths of integer, each with a distinct range of numbers that it can represent. Both languages apply an implicit “widening” rule that converts operands to the narrowest type that can represent both operands. Thus, to add an 8-bit integer and a 64-bit integer,C converts the 8-bit integer to 64-bit form before performing the addition.
If the language does not allow compile-time determination of types, then checking and conversion must be done at runtime. The situation may require the addition of an explicit type field to the runtime representation of the value and a case analysis at runtime to check types, convert operands, and
The digression on page 248 summarizes the rules from the C++ standard.
For explicit conversions, the IR needs a way to represent them: appropriate nodes in a graphical IR or operators in a linear IR.
Runtime type fields are often called tags.
COMMUTATIVITY, ASSOCIATIVITY, AND NUMBER SYSTEMS
Section titled “COMMUTATIVITY, ASSOCIATIVITY, AND NUMBER SYSTEMS”The compiler can often take advantage of the algebraic properties of operations. Addition, multiplication, and Booleans(and, or, xor) are all commutative and associative. Thus, the compiler should recognize that for any given a and b, a+b and b+a compute the same value. Similarly, if the code contains a+b+c and d+a+b, the compiler should recognize that both contain the subexpression a+b. If the compiler evaluates expressions in left-to-right order, it will not see the common subexpression because it will compute the second expression as(d+a)+b.
When possible, the compiler should use commutativity and associativity to improve code quality. Reordering expressions can expose additional opportunities for improvement.
Due to finite precision, floating-point numbers represent a subset of the real numbers, one that does not preserve associativity. Thus, compilers should not reorder floating-point expressions unless the language specifically allows it.
Consider the following example: computing a-b-c, for floating-point a,b, and c. We can assign values such that:
but a-(b+c)≠a. In this case, the result depends on the order of evaluation. Evaluating(a-b)-c produces a value indistinguishable from a, while evaluating a-(b+c) produces a value distinct from a.
This problem arises from the approximate nature of floating-point numbers;the mantissa is small relative to the range of the exponent. To subtract two numbers, the hardware must normalize them; if the difference in exponents is larger than the precision of the mantissa, the smaller number will be truncated to zero. The compiler cannot easily work around this issue, so it should, in general, avoid reordering floating-point computations.
evaluate the operator. Runtime checking incurs costs every time the code executes; compile-time checking incurs that cost once.
Assignment as an Expression
Section titled “Assignment as an Expression”The compiler can treat assignment as an operator that has an unusual evaluation method. The expression on the assignment’s right side evaluates to a concrete value, often called an rvalue. All of the techniques discussed for expression evaluation produce rvalues. The expression on the left side of an assignment evaluates to a location, or lvalue, which might be a memory address or a register. Section 7.3 discusses the computation of lvalues.
Rvalue an expression evaluated to a value, as on the right side of an assignment
Lvalue an exP sion evaluated to a place, as on the due or an assignment
loadI@a⇒r1 loadI@a⇒r1 loadAO rarp,r1⇒r2 loadAO rarp,r1⇒r1 loadI@b⇒r3 loadI@b⇒r2 loadAO rarp,r2⇒r2 loadI@c⇒r5 loadI@c⇒r3 loadAO rarp,r5⇒r6 loadAO rarp,r3⇒r3 mult r4,r6⇒r7 mult r2,r3⇒r2 sub r2,r7⇒r8 sub r1,r2⇒r2
(a) Code from Fig. 7.2(c)(b) Code After Register Allocation
loadI@c⇒r1 loadI@c⇒r1 loadAO rarp,r1⇒r2 loadAO rarp,r1⇒r1 loadI@b⇒r3 loadI@b⇒r2 loadAO rarp,r3⇒r4 loadAO rarp,r2⇒r2 mult r2,r4⇒r5 mult r1,r2⇒r1 loadI@a⇒r6 loadI@a⇒r2 loadAO rarp,r6⇒r7 loadAO rarp,r2⇒r2 sub r7,r5⇒r8 sub r2,r1⇒r1
(c) Evaluate bxc First(d) Code After Register Allocation
■FIGURE 7.3 Rewriting a-bxc to Reduce Demand for Registers.
To generate code for an assignment, the compiler first emits code to evaluate the assignment’s right-hand side to an rvalue. Next, the compiler evaluates the left-hand side to an lvalue, or location. If the rvalue and lvalue have different types, the language may require the compiler to insert code to convert the rvalue to the lvalue’s type. Finally, the compiler emits code to move the rvalue into the specified location.
7.2.3 Reducing Demand for Registers
Section titled “7.2.3 Reducing Demand for Registers”In general, the compiler can keep unambiguous scalar values in registers(see Section 4.6.2). A common code-shape strategy is to assign every value that can reside in a register to a virtual register and, then, to rely on the register allocator to decide which values actually reside in physical registers at each point in the code(see Chapter 13). The compiler can, however, make code-shape choices that reduce the register pressure in the final code.
Expression evaluation provides a clear example. Consider, again, the evaluation of a-bxc, with all of a,b, and c stored at known offsets from the ARP.Fig. 7.3 shows two different evaluation orders for the expression, both before and after register allocation. Panel(a) shows the code from Fig. 7.2(c),which assumed an unlimited set of virtual registers. Panel(b) shows that Evaluation of the lvalue may require code, as with an element of an array. In other cases, such as a scalar value kept in a register, it may not require code.
Register pressure
Section titled “Register pressure”The demand for registers is someun called register pressure.
same code after register allocation; it requires three physical registers in addition to rarp. This result makes sense; the code loads the values of a, b, and c into registers before it performs the multiply and the subtraction. Ei-ther a syntax-driven scheme or a left-to-right treewalk would produce this result.
Changing the evaluation order can lower the register pressure. Panel(c)shows a version of the code that evaluates the multiply operation first. It evaluates bxc before it loads a. After register allocation, this version requires one fewer physical register, as shown in panel(d).
The evaluation order in panel(a) corresponds to a left-to-right treewalk. The evaluation order in panel(c) corresponds to a right-to-left treewalk. Because multiply has higher precedence than subtraction, the left-to-right order loads a’s value into a register, but must preserve it while it evaluates bxc. In this example, the right-to-left order defers the load of a until after the multiply.
Of course, the best order depends on context. At a binary operation, if the compiler needs more registers to evaluate one operand than it does for the other, it should evaluate the more demanding operand first. Doing so will reduce register pressure by one.
This observation is not new. Floyd observed the principle in 1961[160]. Sethi applied it to reducing demand for registers a decade later[321].
To apply this rule, the compiler must examine the expression twice: the first time to compute demand and the second time to choose the order of subexpression evaluation and emit code. This observation applies in many optimization and code generation contexts. To obtain good results often requires that the compiler analyze the code before rewriting it.
SECTION REVIEW
Section titled “SECTION REVIEW”Chapter 5 introduced the translation of expressions, along with a framework to generate either graphical or linear IRs. This section shows how the compiler can apply the same ideas in a traversal of the IR to generate a lower-level representation. It also explores some of the complications that arise in the IR for expressions, such as embedded function calls, type conversions, and assignment.
Building an IR for an expression and traversing it multiple times allows the compiler to analyze the code, derive knowledge about it, and adjust the code in ways that improve the efficiency of the final code. Because a significant portion of actual running time is spent in expression evaluation, efficient code for expressions is critical to the overall speed of the generated program.
REVIEW QUESTIONS
Section titled “REVIEW QUESTIONS”- ILOC includes rsubI, an immediate reverse subtract. It can simplify expression translation. When might it be useful? Why not include the nonimmediate version, rsub, as well?
- Describe two scenarios where multiple traversals of the IR can improve code quality.
7.3 ACCESS METHODS FOR VALUES
Section titled “7.3 ACCESS METHODS FOR VALUES”Section 7.2 implicitly assumes that a single access method works for all identifiers. In practice, different kinds of variables require different access methods. This section begins with an examination of access methods for scalar variables. It then describes the complications introduced by the need to find individual elements within aggregates, such as structures, objects, and arrays.
7.3.1 Access Methods for Scalar Variables
Section titled “7.3.1 Access Methods for Scalar Variables”For scalar variables, the access method must first determine whether the value resides in a register or in memory. Register access is straightforward; the code simply uses the virtual register name. Access in memory requires different strategies depending on the variable’s storage class.
Variables Stored in a Register
Section titled “Variables Stored in a Register”If the compiler can keep a variable’s value in a register in the vicinity of a definition or a use, then it can directly use the register name in operations that reference the value. Access to register-based values is simple and immediate. On most machines, direct access to an enregistered value provides same-cycle access for both uses and definitions. An operation such as add r₁, r₂ ⇒ r₁ can both read and write r₁ in the same cycle. One goal of optimization and the primary goal of register allocation is to keep values in registers in the regions where they are frequently used.
Variables Stored in Memory
Section titled “Variables Stored in Memory”A variable may have its primary location in memory for a number of reasons. The name may be ambiguous because the code has multiple names that might access the same location. The name may have global visibility, so that its ambiguity (or lack thereof) cannot be determined when compiling
one part of the entire application. The name may have a static lifetime, so that its value must be preserved across different procedure invocations.
The IR can represent each variable in a lexically scoped language with its static coordinate: a pair ⟨l,o⟩ where l is the lexical level at which the variable is defined and o is its offset within the level l data area. Global and static variables are typically assigned level zero; for them, the compiler must also record their specific data area.
The general scheme to compute the address of a memory-based variable is to calculate base+offset, where base is the data area’s virtual address and offset is the variable’s distance from base. Different levels in the static coordinate require different strategies to compute base.
Local Variables
Section titled “Local Variables”For local automatic variables, the compiler can allocate storage in the local data area, at one end of the procedure’s AR. To reference the variable, the compiler emits code to add the variable’s known offset to the current ARP, stored in the designated register r_org.
Unambiguous, local, scalar, automatic variables can live in registers. If demand for registers is high, the register allocator may spill some of these values to memory for parts of their lifetimes. When it does, the values’ spill locations are typically placed in the local data area so that the spill and restore code can use r_org as a base address.
Local Variables of Surrounding Scopes
Section titled “Local Variables of Surrounding Scopes”While the global scope surrounds the other lexical scopes, access to it uses a different mechanism.
For local automatic variables declared in lexically surrounding scopes, the compiler must emit code to use the addressability mechanism built and maintained by the linkage convention(see Section 6.4.3).
To find a level l variable using access links, the compiler emits code to find the level l access link, which serves as a base address. With a global display, it would load that base address(the ARP of the level l surrounding scope)directly. It then computes a virtual address as base+offset and uses it in the load or store operation.
Static and Global Variables
Section titled “Static and Global Variables”With global variables, the compiler might generate a unique name-mangled label for each such variable, eliminating the offset and the addition.
For a variable located in a static data area, the base address is marked with an assembly-level label-typically produced by mangling the name associated with the scope. The compiler obtains the textual label name for the reference and arranges to load it into a register as a relocatable assembly-level label.
Properties of the ISA will determine how the compiler obtains the runtime address for the textual label name. We will assume that the label’s value fits into a load immediate operation. If that is not true, then the compiler may need to store the label in a static data area(a constant pool) associated with the procedure and load its value from that location. Of course, the code needs to locate the constant pool. One scheme is to locate the constant pool at a known distance from the start or end of the procedure and access it with a PC-relative address.
For an integer stored at offset 8 in a static data area, the code to compute the address might be:
loadI<label>→rj// get the base address addI rj,8→rj// add the offset
where<label>is the mangled label for the appropriate scope. This sequence can be followed by a load from rj or a store to rj.
Variables Passed as Parameters
Section titled “Variables Passed as Parameters”Formal parameters present a conceptual challenge. Consider an integer function f(x) that takes a single integer parameter, x. Each call site might pass a different variable, or actual parameter, to x. Those actual parameters might have several different storage classes. The code to access x inside f must work independently of the actual parameter’s storage class.
Many linkage conventions designate registers for the first several parameters. For call-by-value parameters, the compiler stores the actual value in the register; the compiler then uses the register name in operations that reference the formal parameter. For call-by reference parameters, the compiler stores the actual parameter’s address in the register; it then emits loads and stores to access the formal parameter’s value.
For parameters passed in memory, the compiler can emit code that uses the ARP as a base address. Each memory-based parameter has a unique offset from the ARP; the compiler can emit code to compute the virtual address of that slot and use that address. Again, for a call-by-value parameter, the AR slot holds the value, while for a call-by-reference parameter, it holds the value’s virtual address.
Variables Stored in the Heap
Section titled “Variables Stored in the Heap”Heap-based variables typically lack both a base address and an offset. The heap allocation process returns a virtual address, which must be preserved to retain access to the entity. That virtual address, in turn, must be stored in either a variable or a field in some other heap-allocated entity.
Note that call-by-reference parameters require one more indirection than do call-by-value parameters. Garbage collection relies on the fact that a heap-allocated entity cannot be accessed if the running program does not have a copy of its address.
If the compiled code contains arbitrary pointer arithmetic or buffer overflows, that assumption may be false.
To access an entity in the heap, the compiler must retrieve the entity’s address, using the appropriate access method. Given that address, it can emit operations to manipulate its memory-based value.
Consider a local automatic variable root that points to a list of heap-allocated structures, each of which has a next pointer. To generate code to traverse the list, the compiler generates code to load the value of root. It uses that value as the address of the start of an instance of the structure. To move down the list, it adds the offset of next within the structure to the address of the current list element and loads the address of the next element.
7.3.2 Access Methods for Aggregates
Section titled “7.3.2 Access Methods for Aggregates”Aggregate objects have more complex access methods than scalar objects because the compiler must emit code to locate specific elements within the aggregate. To access an element of a structure, object, or array, the compiler needs an address for the start of the aggregate object, an offset within the aggregate, and a type.
Structure Elements
The compiler determines how to find the structure’s start address from a symbol table lookup using the search path for the context where the reference occurs. This part of the process is analogous to locating a scalar variable. The compiler uses the storage class to determine how to find the start address. It might be an offset from the current ARP or the ARP of a surrounding scope. It might be an offset from some static or global label. Alternatively, the start address might be stored in some variable that, itself, must be located.
Once the compiler has emitted code to ensure that the start address is in a register, it performs a lookup in the symbol table for the structure’s internal scope to obtain offset and type information. It emits code to add the start address to the offset—to create an effective virtual address for the element. The type information lets the compiler emit the appropriate load operation or operations.
Object Members
To find a given member of a specific object, the compiler must first locate the object’s OR. Because the running code uses the OR pointer (ORP) as the object’s identity, finding the ORP, or start address of the OR, is straightforward. The source-language reference uses a name; that name contains the ORP. The compiler ensures that the ORP is in a register using the techniques described for a scalar variable. To obtain the member’s type and the offset in the OR, the compiler looks up the member name in the symbol table for the object’s internal scope. It then emits code to add the OR address and offset, which creates the member’s starting address. The type information lets the compiler emit the appropriate load operation or operations.
Vectors
Section titled “Vectors”Programming languages typically specify that vectors are one-dimensional arrays of contiguous memory, with a specified lower and upper bound on indices into the vector. A vector V[3:9] has (9 - 3) + 1 elements, as shown in the margin. To access the ith element of V, the compiler needs the starting address of V, which we will designate symbolically as @V, V’s lower and upper bounds, and the offset of element i.
The compiler can compute the offset as (i - low)×w, where low is the declared lower bound of V and w is the length of an element of V. Thus, if low is 3, i is 6, and w is 4, the offset from @V of the ith element is (6 - 3)×4 = 12. If r@V and r_i hold the values of @V and i, respectively, then the following code fragment loads the value of V[i] into rV[i].
subI r_i,3⇒r1// (i - lower bound) multI r_1,4⇒r2// x element length (4) add r@V, r_2⇒r3// address of V[i] load r_3⇒rV[i]// get the value of V[i]
This simple reference introduced three arithmetic operations. The compiler can do better. If the lower bound, low, is known, the compiler can fold the subtraction into @V to create @V0 = @V - low×w, a constant that we will call the false zero of V.
Many memory references take the form of a base address and an offset. Thus, most processors support a two-operand load operation similar to ILOC’s loadA0, or load-address-offset, operation. Using loadA0 folds the addition into the memory operation.
The third arithmetic operation is the multiply. On most processors, an integer multiply takes multiple cycles. If w is a power of two and the index, i, is positive, then the compiler can replace the multiply with a left-shift. Taken together, these would produce the ILOC sequence:
lshiftI r_i,2⇒r2// i × 4 loadA0 r@V[0], r_2⇒rV[i]// get value of V[i]
This code is shorter and, presumably, faster. A good assembly-language programmer might write this code.
V[3:9] Vector Layout
False zero The false zero of a vector V is the address where V[0] would be. In multiple dimensions, it is the location of a zero index in each dimension.
The compiler writer may want to expose details of the address arithmetic to more general optimization, such as redundancy elimination or strength reduction (see Sections 8.4.1 and 10.7.2). Low-level improvements, such as converting the multiply to a shift and folding the add and the load can be performed late in compilation.
Strings
Section titled “Strings”Strings are typically stored as a linear sequence of individual elements. Thus, the address calculation for an element in a string follows the same form as that for an element of a vector. String formats differ in the way that they represent the string’s length. While the discussion focuses on character strings, other types of strings are similar.
An explicit-length representation maintains an integer counter to contain the number of elements in the string, as shown in the margin. The drawing shows the length stored at a negative offset from the pointer to the string. To determine a string’s length, the runtime code simply reads the value in the length field.
An implicit-length representation uses a designated value to denote the end of the string. The best known implicit-length string format is C’s null-terminated character string. As shown in the margin, it stores the null character, designated as “\0,” as the final character in the string. To determine a string’s length, the runtime code must walk the string and count characters up to the null character.
We will defer the implementation of string operations until Section 7.6, after the section on the implementation of loops and other control-flow operations.
Multidimensional Arrays
Section titled “Multidimensional Arrays”To access an element of a multidimensional array, the compiler also uses a base address plus offset scheme. In the multidimensional case, the offset calculation is more complex than for a vector or string. We show the calculation for a two-dimensional array stored in either row-major order or as a set of indirection vectors (see Section 5.6.3). The schemes generalize to higher dimensions. The code for column-major order follows a similar logic and is left as an exercise for the reader.
Row-Major Order. To describe address calculations for multidimensional arrays, we extend the notation from the vector access method. Consider an array A dimensioned as A[1:2,1:4]. Let low₁ refer to the first dimension’s lower bound and low₂ refer to the second dimension’s lower bound. For A,
For a two-dimensional array, let low_1 = 1, high_1 = 2, low_2 = 1, and high_2 = 4. To simplify the exposition, let len_k = high_k - low_k + 1, the size of dimension k.
To access an element A[i,j], the compiler can emit code that computes the offset for the start of row i, computes the offset of element j within that row, and sums the row offset, column offset, and base address. For A[i,j], the address computation is:
@A + (i - low_1) * len_2 * w + (j - low_2) * wHere, @A is the base address of A; (i - low_1) * len_2 is the number of elements before row i; and (j - low_2) is the offset, in elements, of the jth element of a row. The offsets are multiplied by w, the length in bytes of an element.
Substituting actual values, A[2,3] lies at offset:
(2 - 1) * (4 - 1 + 1) * 4 + (3 - 1) * 4 = 24from A[1,1]. The memory layout shows A[1,1], A[1,2], A[1,3], A[1,4], A[2,1], A[2,2], A[2,3], and A[2,4] at byte offsets 0, 4, 8, 12, 16, 20, 24, 28.
Applying the same algebra that creates a false zero in the vector case produces:
@A + (i * len_2 * w) - (low_1 * len_2 * w) + (j * w) - (low_2 * w)Reordering the terms produces:
@A + (i * len_2 * w) + (j * w) - (low_1 * len_2 * w + low_2 * w)The last term is independent of i and j; it can be factored directly into a false zero for A:
@A_0 = @A - (low_1 * len_2 * w + low_2 * w) = @A - 20Now the address calculation for A[i,j] is simply continued on the next page.
The compiler could insert the false zero calculation after the procedure’s prolog code and rely on dead code elimination to remove it if it is not needed-for example, if the only use of the array is as an actual parameter at a call site.
The idea behind the address computation for arrays with two dimensions generalize to arrays of higher dimension. The address polynomial for an array stored in column-major order can be derived from the same ideas that underlie the address polynomial for row-major order. The optimizations that we applied to reduce the cost of address computations apply equally well to the address polynomials for these other kinds of arrays.
Indirection Vectors. The indirection vector representation is conceptually simple. Each level of the array uses a set of vectors, as shown in Fig. 7.4.The innermost level of vectors contains the actual data elements; successive outer levels contain pointers linked so that a series of vector accesses will lead to the desired array element.
For the address of A[2,3], this evaluates to
Since@A0 is just@A-20, this is equivalent to@A-20+44=@A+24, the same location computed by the original address polynomial.
If we assume that i and j are in r; and rj, and that len2 is a constant, this refactored polynomial leads to the following code sequence:
loadI@A0⇒r@A0// adjusted base for A
multI r1,len2⇒r1// i x len2
add r1,rj⇒r2//+j
multI r2,4⇒r3//xw
loadAO r@A0,r3⇒ra// value of A[i,j]
The computation is now two multiplications and two additions(one in the loadAO). The second multI can be rewritten as a shift.
If the compiler does not have access to the array bounds, it must either compute the false zero at runtime or use the full polynomial that includes the lower bounds. The former option can be profitable if the elements of the array are accessed multiple times in a procedure; computing the false zero on entry to the procedure lets the code use the less expensive address computation. The more complex computation makes sense only if the array is accessed infrequently.
FIGURE 7.4 Indirection Vectors in Row-Major Order for B[1:2,1:3,1:4].
Section titled “FIGURE 7.4 Indirection Vectors in Row-Major Order for B[1:2,1:3,1:4].”Consider the three-dimensional array B shown in Fig. 7.4. To access B[i,j,k], the compiler emits code that uses@B0,i, and the length of a pointer to find the start of the indirection vector for the subarray B[i,]. Next, it emits code to use that result, along with j and the length of a pointer, to find the start of the vector for B[i,j,]. Finally, it uses that result, along with k and the length w of an element of B to compute the address of B[i,j,k].
If the values of i,j, and k exist in registers rj, rj, and rk, respectively, and@B0 is the zero-adjusted address of the first dimension, then the compiler might generate the following code to load B[i,j,k]:
loadI@B0→r@B0// false zero of B
multI rj,4→r1// assume pointer is 4 bytes
loadAO r@B0,r1→r2// get@B[i,*]
multI rj,4→r3// pointer is 4 bytes
loadAO r2,r3→r4// get@B[i,j,*]
multI rk,4→r5// assume element length is 4
loadAO r4,r5→rb// value of B[i,j,k]
This code assumes that the pointers in the indirection structure have been adjusted to account for nonzero lower bounds. If not, then the values in rj and rk must be decremented by the corresponding lower bounds. In the example, the multiplies can be replaced with shifts.
Using indirection vectors, the reference requires just two operations per dimension. On machines where memory access was fast relative to arithmetic-for example, most computers prior to 1985-this access method was fast. As the cost of memory accesses has increased relative to the cost of arithmetic, this scheme has lost its advantage in speed.
We use the term array of structure to indicate that all of the array elements have the same structure type.
On cache-based machines, locality is critical to performance. When arrays grow to be much larger than the cache, storage order affects locality. Row-major and column-major storage schemes produce good locality for some array-based operations. The locality properties of an array implemented with indirection vectors are harder for the compiler to predict and, perhaps, to optimize.
Arrays of Structure. Some programming languages allow the compiler to declare an array of structure-multiple copies of a structure or record with array-style indexes that locate specific instances(elements in the array of structure). The access method for an array of structure relies on the address polynomial for an array to find the start of the structure instance. Within the instance, the standard structure access method(base+ appropriate offset)applies.
Accessing Array-Valued Parameters
Section titled “Accessing Array-Valued Parameters”Most languages allow an implementation to pass arrays as call-by-reference parameters to avoid the need to copy each element’s value at a call. The caller and callee must agree on the array’s layout and access method-the form of the address polynomial. The caller must supply the callee with the values that the access method needs.
Dope vector a descriptor for an actual parameter array Dope vectors may also be used for arrays whose bounds are determined at runtime. Some languages require the programmer to supply the needed values. For example, FORTRAN requires that the programmer declare the array using either constants or other formal parameters to specify its dimensions. Other languages have the compiler collect, organize, and pass the necessary information to the callee. The compiler builds a descriptor, called a dope vector, that contains both the array’s base address and the necessary information for each dimension. The dope vector has a known size, so the compiler can allocate space for it in either the caller’s AR or the callee’s AR. The precall sequence passes the dope vector’s address in the appropriate parameter slot.
Fig. 7.5 shows an example from PL/I. The procedure main invokes fee twice. Panels(b) and(c) show the dope vectors for the two call sites. If all the accesses used the false-zero version of the address polynomial, the dope vectors would contain the lengths of each dimension of A rather than the lower and upper bounds.
To access an element of the parameter array, the compiler emits the same address polynomial that it would use for a reference to a local array, except that it pulls values for the base address and dimensions from the dope vector. In this way, activations of the procedure from different call sites can use the same code to access distinct arrays passed from different call sites. The same technique can be used to support dynamically sized and allocated arrays. At program main; begin declare x(1:100,1:10,2:50), y(1:10,1:10,15:35) float; call fee(x); call fee(y); end main; procedure fee(A) declare A(,,*) float; … end fee;
(a) PL/I Code That Passes Whole Arrays
(b) Dope Vector for the First Call Site
(c) Dope Vector for the Second Call Site
■ FIGURE 7.5 Dope Vectors.
allocation time, the compiler can construct a dope vector that subsequent references use.
Note that access through a dope vector costs more than access to a local array with known bounds. At best, the dope vector introduces additional memory references. At worst, it prevents the compiler from using optimizations that need facts from the array’s declaration.
7.3.3 Range Checks
Section titled “7.3.3 Range Checks”Most programming languages assume, either explicitly or implicitly, that a program only accesses locations that are within the defined bounds of data structures. For example, an array reference cannot access an element that is outside its lower and upper bounds. Neither can a string reference access elements that are outside its bounds.
A program that accesses an out-of-bounds element is, by definition, not well formed. Some languages, such as JAVA and ADA, require that out-of-bounds accesses be detected and reported. Other languages leave this issue to the compiler writer’s discretion. Some compilers include code to perform these range checks; others do not. C’s lack of checking is at least partially to blame for buffer-overflow attacks-arguably one of the most widespread computer security problems in history.
The simplest implementation of a range check inserts a test before each reference to an aggregate entity. The test verifies that the computed index into the entity falls within its allocated range. The test throws an exception if the index is outside the valid range.
Range check a test that verifies that an gregate data structure is or allocated bounds
for i←1 to n for j←1 to m if (1b1≤i≤ub, and 1b2≤j≤ub2) then … a[i,j]… else throw exception
Naive Range Checking
if (1b1≤1 and n≤ub, and 1b2≤1 and m≤ub2) then for i←1 to n for j←1 to m … a[i,j]… else throw exception
Range Checks After Optimization
For a heap-allocated object, the compiler could use the allocated size to approximate its total extents. This scheme may overestimate the declared bounds, but would avoid references outside its allocated space.
The example in the margin inserts a test before the array reference in the inner loop. It assumes that a has bounds a[1b1:ub1,1b2:ub2]. A naive range check such as this one can create significant overhead. The additional control-flow affects both optimization and runtime.
The compiler can often improve naive checks by combining them or proving that the accesses are safe. In the marginal example, the checks in the inner loop can be combined and moved out of the two loops. The transformed code performs one check rather than one check per access.
If the loop nest contains multiple references to A, the impact might be even greater. With multiple identical references, the compiler can arrange to check the bounds once. If the loop nest contains multiple references with different index expressions, the compiler must cover all of them. It may be able to combine some of those tests algebraically, further reducing the cost.
If the compiler knows the value of some or all of the names used in the checks, it may be able to move some tests to compile-time. In the example, the compiler knows that the loop indices, i and j, start at one. If it knows the value of 1b1, it can perform the test 1b1≤1 at compile time and eliminate it from runtime. The same strategy applies to each check; if the values are known, move the test to compile time.
To perform range checking, the compiler must know the data structure’s size. If that size is static and known, the compiler can fold it directly into the check. With a dynamically sized data structure, the runtime system must record the size information that the range-check code needs.
SECTION REVIEW
Section titled “SECTION REVIEW”The compiler needs a method to find and access each value that a program computes. The method may be trivial, as for a value kept in a register. It may require several instructions, as for a scalar value stored in the AR of a surrounding lexical scope. It may be complex, as for an element of an array of structures. For each kind of value and each type, the compiler needs a plan so that it can build the right IR construct for the source reference.
This section described common techniques to access most kinds of programming language values. A compiler will use a combination of these techniques, dictated by the implementation of other constructs and by the definition of the source language, itself. In practice, the translation should emit code that exposes enough detail to enable later passes in the optimizer and back end to generate compact and efficient code. REVIEW QUESTIONS
- Consider an array A[0:99,0:89,0:109]. Write down the code to compute the address of A[i,j,k] assuming (a) that A is stored in row-major order and (b) that A is stored using indirection vectors.
- Explain, in terms of storage layout and the code required to access a specific element, the difference between an array of structure and a structure of arrays.
7.4 BOOLEAN AND RELATIONAL OPERATORS
Section titled “7.4 BOOLEAN AND RELATIONAL OPERATORS”Programming languages almost always include features to specify control-flow, such as conditionals and loops. These features, in turn, create the need for Boolean and relational expressions. The language needs a grammar to specify these expressions. The compiler writer needs both a representation for Boolean values and a scheme to translate Boolean operations into the target machine’s ISA.
The grammatical changes are straightforward, as shown in Fig. 7.6. Relational operators have higher precedence than Boolean operators. The productions for RelExpr allow Boolean combinations of relational expressions, but prevent cascading relational operators, as in a < b < c. The Boolean operators have their traditional precedence: → then ∧ then ∨. A relational expression produces a Boolean value.
Representing Boolean values is also straightforward. The compiler writer can assign numerical values to true and false. Typical values include zero for false and nonzero for true. Well chosen values will allow the compiler to use the target machine’s native operations to manipulate them. Most processors provide operations to perform negation, and, or, and exclusive or.
The complication in translating Boolean and relational expressions arises from the different kinds of support provided by processor ISAs. Section 7.4.1 introduces a basic scheme for translating these expressions. Section 7.4.2 examines how variations in the ISA support for Boolean and relational operations can affect translation.
7.4.1 Hardware Support for Relational Expressions
Section titled “7.4.1 Hardware Support for Relational Expressions”Processor ISAs provide several mechanisms to evaluate relational expressions. The operations available on the target ISA largely determine the kinds of code that the compiler can generate to evaluate a relational expression. Since relational expressions typically evaluate to a Boolean value, these relational expressions typically produce Boolean values.
The grammar uses ∨ for or, ∧ for and, and → for not to avoid confusion with ILOC operations.
The programming language may specify values for true and false, such as 1 and 0 or -1 and 0.
Expr→Expr V AndTerm Term→Term Mults Value
| AndTerm | Value |
|---|---|
| AndTerm→AndTerm∧NotTerm | Value→-Factor |
| NotTerm | Factor |
| NotTerm→RelExpr | Factor→(Expr) |
| RelExpr | Num |
| RelExpr→NExpr Rels NExpr | Name |
| NExpr | Rels→< |
| NExpr→NExpr Adds Term | Adds→+ |
| Term | Mults→x÷ |
■FIGURE 7.6 Adding Booleans and Relationals to the Expression Grammar.
if(a<b) then statement₁ else statement₂ If-Then-Else Construct
cmp_LT r_a,r_b→r₁ cbr r₁→L₁,L₂ L₁: statement₁ jumpI→L₃ L₂: statement₂ jumpI→L₃ L₃: nop Implementation Scheme
cmp_LT r_a,r_b→r₁ cmp_GT r_c,r_d→r₂ and r₁,r₂→r₃ cbr r₃→L₁,L₂ L₁: statement₁ jumpI→L₃ L₂: statement₂ jumpI→L₃
effects carry over into both the representation and evaluation of Boolean operations, as well.
Hardware support for relational expressions usually consists of a comparison operation and a set of operations that interpret the result of that comparison. While ISAs differ in how they provide this support, most of them use a similar scheme. Between the comparison operation and the operations that interpret it, the code must be able to distinguish the six basic relations:<,≤,=,≥,>,and≠.
Assume for the moment that, for each of these relations, the ISA includes a comparison operation that writes a Boolean value in a register as its result. For example, cmp_EQ r_a,r_b→r_c sets r_c to true if the values in r_a and r_b are equal and to false otherwise. To interpret this value, a conditional branch operation, cbr r_c→L_T,L_F,transfers control to the code at assembly label LT if r_c contains true and to LF otherwise.
The example in the margin shows how the compiler might implement a simple if-then-else construct using these operations. The code assumes that the values of a and b reside in r_a and r_b. The comparison operation, cmp_LT writes a Boolean value into r₁. The conditional branch, cbr, interprets the value in r₁ to choose between labels L₁ and L₂. After executing the appropriate statement, the code branches to the next statement, at L₃.
The compiler can implement Boolean operations, such as∧,V, and→,in a manner similar to the arithmetic operations. Almost all processors provide direct hardware implementations of these operations, making the translation straightforward.
∧c>d) If the source construct contained a more complex condition, such as(a<b∧c>d), the implementation could perform two comparison operations, combine their results with a hardware and operation, and branch on the result, as shown in the margin at the bottom of the previous page.
Short-Circuit Evaluation
Section titled “Short-Circuit Evaluation”In a Boolean expression, the value of one subexpression may determine the value of an entire expression. The code in the margin shows the ILOC that a compiler might emit for the assignment
assuming all six values are in appropriately named registers. The code eval- uates each of the comparisons, then uses Boolean operations to combine those results. Assuming that cmp_LT, and, and or take one cycle each, the code requires five cycles to evaluate the expression.
The compiler relies on two Boolean identities:
To generate the short-circuit code, the compiler must analyze the expression in light of these two identities and find the set of minimal conditions that determine its value. In many cases, short-circuit evaluation can reduce the cost of evaluating Boolean expressions.
The compiler can refactor the code to use the minimal number of compares needed to determine the expression’s value, as shown in the margin. It first computes x←a<b; if x is true, it branches to the next statement in the source code, at L3. On the other hand, if x is false, the code branches to L1 to evaluate x←c<d.
If c<d evaluates to false, then the x is false and the code branches to L3 to execute the next source-code statement. If c<d is true at this point, then the result of evaluating e<f determines x’s value; the code jumps to L2 to perform that final evaluation.
The length of the path through the refactored code depends on the values of the three comparisons. If a<b, the expression evaluates to true and the code executes just one cmp_LT and one cbr.
If, instead, a≥b, the result relies on the values of c,d,e, and f. If c≥d, control jumps to L3 and the evaluation takes two cmp_LTs and two cbrs. Finally, if c<d, the code uses three cmp_LTs, two cbrs, and a jump.(If the block
Complete Evaluation of
Code Refactored for Short-Circuit Evaluation for L3 immediately follows the block for L2, the jump should optimize away, leaving five operations, as in the original code.)
The actual costs will depend on the individual operation costs. On most machines, an untaken branch is a single cycle; a taken branch might be more. In many cases, the short-circuited code is faster than the code for the complete evaluation.
7.4.2 Variations in Hardware Support
Section titled “7.4.2 Variations in Hardware Support”Computer architects have introduced many variations in support for evaluation of Boolean and relational expressions. The compiler writer must understand the support that the target ISA provides and should capitalize on those features. This section examines three common variations on the support described in the previous section: conditional move operations, predicated execution, and condition codes.
Conditional Move Operations
Section titled “Conditional Move Operations”To avoid some of the branches introduced by relational-expression evaluation, some ISAs include a conditional move operation. Conditional move takes two input values and assigns one of them to its result, based on either a Boolean value or the condition-code. If the conditional move operation takes an explicit Boolean argument, it will need to be a “four-address” operation, much like a floating-point multiply-add operation.
Conditional Move Example
A conditional move provides a simple implementation of some if-then-else constructs, as shown in the margin. The compiler can emit code that eval- uates both additions and only perform the assignment for the selected case-either the then part or the else part.
add r_c,r_d→r_1
add r_e,r_f→r_2
cmp_LT r_a,r_b→r_3
c_i2i r_3,r_1,r_2→r_x
Corresponding ILOC Code Using Conditional Move
If the addition takes fewer cycles than the branch, this strategy saves runtime cycles. If the hardware can perform multiple adds in a single cycle, a good instruction scheduler may avoid paying an extra cycle for the add operation whose result is unused.
Predicated Execution
Section titled “Predicated Execution”Predicated execution is another architectural feature intended to avoid the need for conditional branches. In this scheme, some or all operations can specify a predicate register that determines whether or not the operation takes effect. On some architectures, an operation with a false predicate does not execute; on others, it executes but does not apply its result.(That is, with a false predicate, an add does not assign its value and a branch does not transfer control.)
The final translation:
In ILOC, we designate a predicate as a register name enclosed in parentheses and followed by a question mark. The predicated add operation shown in the margin specifies that rx receives the value (ra+rb) if and only if r1 contains the value true.
For the example used to demonstrate conditional move, a predicated execution scheme emits similar code, as shown in the margin. Again, architects can implement predication in two ways. The processor might evaluate all predicated operations and only assign the value if the predicate is true. Al-ternatively, the processor can test the predicate and only execute operations guarded by true predicates.
Condition Codes
Section titled “Condition Codes”The discussion, so far, has assumed that the ISA’s comparison operation returns a Boolean value. In practice, many processors return more fine-grained information, in the form of a condition code. In these ISAs, an operation such as compare ra, rb sets separate bits in a condition code to indicate whether a<b, a=b, or a>b. The condition code might be stored as a separate register; many architectures have stored it in the processor’s status word. We can think of the condition code as an implicit argument that some operations define or use.
Condition-code schemes require a conditional-branch operator that can test specific bits in the condition code. An ISA that uses condition codes probably has fewer comparison operations and more conditional branch operations than one with Boolean comparisons; the overall difference in complexity of the ISA is negligible.
The complexity appears, however, in code that must produce a concrete Boolean value from a comparison, as shown in the margin. The compiler must emit code that uses a branch to interpret the condition code and embed assignments into the true and false paths. The comp operation writes its results into a condition-code register, cc1; the conditional branch tests that value for the result “less than.” The branch for < writes the value true into the result, r1, while the branch for ≥ writes the value false into r1.
Naive translation of relational expressions into an ISA that uses condition codes can produce awkward code. The code from our earlier if-then-else example appears in the margin. It evaluates a<b to a Boolean value and uses that value to select either the then part or the else part. The code is both awkward and long.
The blocks at L1 and L4 execute if a<b, while the blocks at L2 and L5 execute if a≥b. A human would simplify this code by moving statement1 into the
(r1)? add r, r,→r
cmp_LT r, r,→r
not r,→r
(r1)? add r, r,→r
(r2)? add r, r,→r
ILOC Emitted for Example Using Predicated Execution
comp r, r,→cc1
cbr_LT cc1→L1,L2
L1: loadI true→r1
jumpI→L3
L2: loadI false→r1
jumpI→L3
L3: nop
Deriving a Boolean Value from a Condition Code
if(a<b) then
statement1
else statement2
If-Then-Else Construct
comp ra, rb→cc1
cbr_LT cc1→L1,L2
L1: loadI true→r1
jumpI→L3
L2: loadI false→r1
jumpI→L3
L3: loadI true→r2
comp r1,r2=
cbr cc2→L
L4: statement1
jumpI→L4
L5: statement2
jumpI→L4
L6: nop
Naive Translation
block at L1 and statement2 into the block at L2. A compiler could achieve that result with a combination of constant propagation, code motion, and control-flow simplification(see Chapter 10). The combination of optimizations moves the two statements, empties blocks L4 and L5, removes those blocks, and redirects the jumps to L6.
The resulting code, shown in the margin, represents the value of a<b implicitly as a position in the code. Inside the block at L1, that value is true;inside the block at L2, it is false. The value is neither useful nor accessible in L6 or afterward.
comp r, rb→cc1 cbr_LT cc1→L1,L2 L1: statement1 jumpI→L6 L2: statement2 jumpI→L6 L5: nop Implicit Representation for a<b
The compiler can emit code that represents the comparison’s result implicitly. Compilers that target ISAs with condition codes often switch between explicit and implicit representations for these values. In general, the compiler can use an implicit representation unless the source code assigns the value to a variable. This approach eliminates the bulky and awkward code that naive translation might produce.
SECTION REVIEW
Section titled “SECTION REVIEW”Processor ISAs implement and interpret comparisons in different ways. Translation schemes for Boolean and relational values reflect this diversity. This section showed a basic schema, along with several adaptations for different kinds of ISA support.
The compiler should make reasoned choices about how to map Boolean and relational expressions onto the ISA, choosing between implicit and explicit representations, and making use of features such as conditional moves and predication. Attention to these details can improve the efficiency of the generated code.
REVIEW QUESTIONS
Section titled “REVIEW QUESTIONS”-
Chapter 5 showed how to fit an if-then-else construct into a syntax-driven translation scheme(see page 224). Sketch a syntax-driven translation scheme to generate code for a relational expression, such as a<b, using the grammar from Fig. 7.6.
-
To include short-circuit evaluation into a translation scheme, the compiler must choose an order to evaluate an expression’s subterms. How might the compiler choose an order that reduces the expected time for evaluation?
7.5 CONTROL-FLOW CONSTRUCTS
Section titled “7.5 CONTROL-FLOW CONSTRUCTS”Programming languages provide control-flow constructs that allow the programmer to connect straight-line sequences of code, or basic blocks, in useful ways. Common control-flow constructs include an if-then-else construct, loop constructs, and case statements. For each control-flow construct, the compiler needs a translation scheme.
Section 7.4 described the translation of if-then-else constructs. That scheme created three labels: one for the block that begins the then part.another for the block that begins the else part, and a third for the block that follows the if-then-else construct. The compiler can translate an if-then-else construct by building a representation for each block and connecting the blocks as dictated by the translation schemes for the if-then-else construct. Compilers handle other control-flow constructs in a similar fashion: building representations for the blocks and connecting them with labels, branches, and jumps.
To build a basic block, the compiler aggregates the code for consecutive, unlabeled, unpredicated operations. Any control-flow transfer ends the block. Any labeled statement ends the block, on the assumption that the label may be the target of a branch. Any predicated statement ends the block. In ILOC,every block begins with a labeled statement and ends with a branch or jump. In an IR that supports fall-through branches, the operation that follows a branch starts a block. It may lack an initial label.
To tie the blocks together, the compiler inserts code to implement the control-flow specified by the source program. The margin shows a source-level if-then-else construct, along with ILOC code that follows the discussion in Section 7.4.1. The example abstracts away the details of the blocks that form the then part and the else part.
The code to implement control-flow constructs resides at or near the end of the basic blocks. In general, blocks begin with labeled statements and end with branches or jumps. If the IR models delay slots, the branch or jump may be earlier in the block. In the ILOC examples that follow, blocks begin with a label. Since ILOC branches label both the taken and not-taken(or fall-through) cases, the first operation after a branch is only reachable if it is labeled. If the IR or the target ISA allow PC-relative branches or jumps, then a block may begin with an unlabeled statement that is the target of a PC-relative branch.
While languages use different syntax to express control flow, the set of underlying concepts is small. This section examines the implementation of conditionals, loops, and case statements.
Recall that a basic block is just a maximal-length sequence of straight-line, unpredi-cated code.
if(a<b) then
block1
else block2
If-Then-Else Construct
L0: cmp_LT r, rb r
cbr r1→L1,L2
L1:block1
jumpI→L3
L2:block2
jumpI→L3
L3: nop
Implem=1
BRANCH PREDICTION BY USERS
Section titled “BRANCH PREDICTION BY USERS”One urban compiler legend concerns branch prediction for if-then-else constructs. FORTRAN 66 had an arithmetic if statement that took one of three branches, based on whether the controlling expression evaluated to a negative number, to zero, or to a positive number. One early compiler allowed the user to supply a weight for each label that reflected the relative probability of taking that branch. The compiler then used the weights to order the branches to minimize the total expected delay.
After the compiler had been in the field for a year, the story goes, one of the maintainers discovered that the branch weights were being used in the reverse order, maximizing the expected delay. No one had complained.
This story is usually told as a fable about the value of programmers’ opinions on the behavior of code they have written.(Of course, no one reported the improvement, if any, from using the branch weights in the correct order.)
7.5.1 Conditional Execution
Section titled “7.5.1 Conditional Execution”The previous example showed a scheme to implement if-then-else constructs with a Boolean-valued compare and branches. The discussion in Section 7.4 focused on evaluating the controlling expression. It showed how the underlying instruction set influenced the strategies for handling the controlling expression.
Because the then and else parts can contain arbitrary amounts of code, the compiler writer may employ multiple translation strategies and select between them based on context. If the then and else parts are large, the three-block scheme from Section 7.4 works well. If, however, the then and else parts are small, the compiler should consider the use of either conditional moves or predicated execution to avoid the branches and jumps.
Consider an if-then-else construct where the then and else parts each contain 20 operations. With predication, the code would cause the processor to issue all 40 operations; with a branching strategy, it would issue 20 operations plus the necessary branches and jumps. For a small enough block, predication might be faster. As the block size grows, it will reach a point where the cost of the branches and jumps is less than the cost of issuing unused operations.
The same issue arises with a strategy based on conditional move operations. For small blocks, the use of conditional move operations may produce more efficient code than the three-block strategy.
Predication decreases the density of useful operations in a block. At some point, the multicycle delay of a branch is less than the cost of the cycles spent on useless operations.
The choice between strategies based on branches, predication, and conditional move operations should account for several factors.
-
Expected Frequency of Execution If one part of the if-then-else construct executes significantly more often, the compiler should focus on techniques that improve speed along that path. This bias might take the form of predicting a branch, of executing some operations speculatively, or of reordering the logic.
-
Uneven Amounts of Code If one part of the if-then-else construct contains many more operations than the other, this fact may weigh against the use of predication or conditional moves.
-
Control Flow Inside the Construct If either part of the if-then-else construct contains control flow, such as another if-then-else, a case statement, a loop, or a procedure call, then predication and conditional move implementations may be a poor choice.
To make the best decision, the compiler must consider all these factors, as well as the surrounding context. This observation suggests that, in practice, the compiler may need to (1) build an initial IR that represents the if-then-else in a more abstract way, (2) analyze the code in that form, and (3) choose between branches, predication, and conditional move after it has the context to make a good decision.
7.5.2 Loops and Iteration
Section titled “7.5.2 Loops and Iteration”Most programming languages include one or more loop constructs to perform iteration. The first FORTRAN compiler introduced the do loop to perform iteration. Today, loops are found in many forms. For the most part, they have a similar structure.
Consider the C for loop shown in Fig. 7.7(a) as an example. Panel (b) shows a CFG to illustrate how the compiler might lay out the code for this loop. The loop has three controlling expressions: e1, which provides for initialization; e2, which evaluates to a Boolean and governs execution of the loop; and e3, which executes at the end of each iteration and, potentially, updates the values used in e2. This basic schema applies to several kinds of loops.
If the loop body consists of a single block—that is, it contains no other control flow—then the schema produces a loop that has one initial branch plus one branch per iteration. Some ISAs provide mechanisms to hide branch latency, such as user-specified predictions or branch delay slots. Compilers can often use such features to hide the latency of a loop-closing branch.
If the ISA allows, the compiler should predict loop-closing branches as taken.
for(e1;e2;e3) {loop body}
(a) Code for Loop
(b) Schema for Implementing the Loop
| Step | Purpose |
|---|---|
| 1 | evaluate e1 |
| 2 | if(¬e2) then goto 5 |
| 3 | loop body |
| 4 | evaluate e3 |
| if(e2) then goto 3 | |
| 5 | code after loop |
■ FIGURE 7.7 General Schema for Layout of a for Loop.
For Loops
Section titled “For Loops”To map a for loop into code, the compiler follows the general schema from Fig. 7.7(b). Consider the following example:
loadI 1⇒r_i // Step 1
loadI 100⇒r_1 // Step 2
cmp_GT r_i,r_1⇒r_2
for(i=1;i<=100;i++)
cbr r_2→L2,L1
{loop body}
L1: loop body // Step 3
}
addI r_i,1⇒r_i // Step 4
next statement
cmp_LE r_i,r_1⇒r_3
cbr r_3→L1,L2
L2: next statement // Step 5
Translation of steps 1, 2, and 4 is straightforward. It yields a single basic block for steps 1 and 2, and another block for step 4. Translation of the loop body proceeds statement-by-statement. If the loop body consists of a single basic block, then the compiler can combine the blocks for steps 3 and 4,which may lead to improvements in the code. For example, the instruction scheduler might use operations from the end of step 3 to fill delay slots in the branch from step 4.
FORTRAN’s DO Loop
Section titled “FORTRAN’s DO Loop”In FORTRAN, the iterative loop is a do loop. It has a more restrictive form than C’s for loop. The loop header specifies an index variable, an initial
SINGLE TEST VERSUS DOUBLE TEST LOOPS
Section titled “SINGLE TEST VERSUS DOUBLE TEST LOOPS”The loop schema shown in Fig. 7.7 uses a compare-and-branch sequence both before the loop and at the end of the loop body. An obvious alternative is to adopt a schema that has a single test at the top of the loop and a jump at the bottom-avoiding the second compare operation.
The single-test loop creates a two-block loop body for even the simplest loops. It also lengthens the path through the loop by at least one operation.
The double-test loop should produce a single-block loop body for loops with no internal control flow. Local optimization and instruction scheduling then apply to the entire loop body. With constant lower and upper bounds, the initial check may be eliminated. In short, the double-test loop should optimize more easily than the single-test one.
value, and a final value. The programmer may specify an optional increment value. The following example loop iterates the index i from 1 to 100 by increments of 1.
loadI 1⇒r1// Step 1
loadI 100⇒r1// Step 2
cmp_GT r1,r1⇒r2
do 10 i=1,100,1 cbr r2→L2,L1
loop body
L1: loop body// Step 3
10 continue
addI r1,1⇒r1// Step 4
next statement
cmp_LE r1,r1⇒r3
cbr r3→L1,L2
L2: next statement// Step 5
The comments map the ILOC code back to the schema in Fig. 7.7.
FORTRAN, like many languages, has some interesting quirks. One such peculiarity relates to do loops and their index variables. The number of iterations of a loop is fixed before execution enters the loop. If the program changes the index variable’s value, or passes it to a subroutine that might change its value, that change does not affect the number of iterations that execute. To ensure the correct behavior, the compiler may need to generate a hidden index variable, called a shadow index variable, to control the iteration. For an index variable passed at a call, interprocedural summary analysis can prove that the value is unchanged, allowing the compiler to eliminate this extra overhead(see Section 9.2.4).
Programmers often pass a loop index at a call so that it can appear in the code’s output. In FORTRAN, with call-by-reference parameters, this act can fool the compiler into believing that the index variable will be changed by the call.
While Loops
Section titled “While Loops”A while loop also maps into the standard loop schema. Unlike the C for loop or the FORTRAN do loop, a while loop has no initialization. Thus, the code is even more compact.
\begin{array}{ll}\text{cmp_GE}&\text{r}_{x},\text{r}_{y}\Rightarrow\text{r}_{1}\quad//\,\text{Step 2}\\ \text{cbr}&\text{r}_{1}\rightarrow\text{L}_{2},\text{L}_{1}\\ \text{while}(\text{x}<\text{y})\,\{\end{array}loop body
L1: loop body// Step 3
\text{cmp_LT}\quad\text{r}_{\text{x}},\text{r}_{\text{y}}\Rightarrow\text{r}_{\text{2}}\quad//\,\text{Step 4}next statement
L2: next statement// Step 5
Replicating the test in step 4 creates the opportunity for a simple loop to have a body that consists of a single basic block. The same benefits that accrue to a for loop from this structure also occur for a while loop.
Until Loops
Section titled “Until Loops”An until loop iterates until the controlling expression has the value true. It tests the controlling expression at the end of each iteration of the loop’s body.PASCAL’s repeat until loop behaves in this way.
An until loop always enters the loop and performs at least one iteration. The loop has a particularly simple structure, since it avoids steps 1 and 2 in the schema:
\begin{array}{ll}\text{(}&\text{L}_{1}\text{: loop body}\\ \text{loop body}&\text{cmp_LT}\quad\text{r}_{x},\text{r}_{y}\Rightarrow\text{r}_{2}\quad//\,\text{Step 4}\\ \text{) until}(\text{x}<\text{y})&\text{cbr}\quad\text{r}_{2}\rightarrow\text{L}_{2},\text{L}_{1}\\ \text{next statement}&\text{L}_{2}\text{: next statement}\\ \end{array}\quad//\,\text{Step 5}C does not provide an until loop. Its do construct is similar to an until loop, except that the sense of the condition is reversed. It iterates until the condition evaluates to false, where an until loop iterates until the condition is true.
Expressing Iteration as Tail Recursion
Section titled “Expressing Iteration as Tail Recursion”In Lisp-like languages, programmers often implement iteration using a styl-ized form of recursion. If the last action executed by a function is a call, that call is known as a tail call. For example, to find the last element of a list in SCHEME, the programmer might write the following simple function:
Tail call
A procedure call that occurs as the last action in some procedure is termed a tail call. A self-recursive tail call is termed a tail recursi CONDITION CODES AND COUNTDOWN LOOPS One argument for condition-code ISAs is that they can produce efficient code in some specific, but important, situations. In particular, these ISAs usually have arithmetic operations, such as add and sub, set the condition code to indicates the relationship between the result value and zero. In this case, subsequent control-flow operations can sometimes avoid the need to perform a comparison. With this feature, the compiler can often translate an iterative loop with known bounds into a countdown loop that ends when an index variable reaches zero. (For example, a FORTRAN loop that needs a shadow index variable can be transformed to count down rather than up.) This transformation removes one operation from the loop. For loops that contain few operations, the improvement can be substantial.
The recursive call in the last line is a tail call. Compilers can generate particularly efficient code for tail calls that recur on the caller (see Section 10.4.1). Iteration can be expressed as a tail recursion, as in the following SCHEME code:
Invoking len on a list returns the list’s length. len relies on count, which implements a simple counter using tail calls.
Break Statements Many languages implement a break or exit statement that provides a structured way to exit a loop. A break transfers control to the first statement following the loop. For nested loops, a break typically exits the innermost loop. Some languages, such as ADA and JAVA, allow an optional label on a break statement that specifies the loop that it will exit. A labeled break allows the program to exit multiple loops at once. C also uses break in its switch statement, to transfer control to the statement that follows the switch statement.
The break statement has a simple implementation. Since loops and case statements end with a label for the next statement, the compiler can simply emit an immediate jump to that label. Some languages include a skip or continue statement that jumps to the next iteration of a loop. This construct can be implemented as an immediate jump to the code that reevaluates the controlling expression and tests its value. Alternatively, the compiler can simply insert a copy of the evaluation, test, and branch at the point where the skip occurs.
7.5.3 Case Statements
Section titled “7.5.3 Case Statements”Many programming languages include some form of a case statement. FOR-TRAN has its computed goto. ALGOL-W introduced the case statement in its modern form. BCPL and C have a switch construct. PL/I generalized the switch statement; one version allowed logical expressions as case labels. As the introduction to this chapter hinted, implementing a case statement efficiently is complex.
Consider the implementation of C’s switch statement. The basic strategy is simple:(1) evaluate the controlling expression;(2) branch to the selected case; and (3) execute the code for that case. Steps 1 and 3 are well under-stood; they follow from earlier discussions.
In C, the individual cases usually end with a break statement that exits the switch statement. If a case ends without a break, control falls through to the next case. To make this feature work, the compiler must either (1) preserve the original order of the cases,(2) add an explicit jump at the end of any case that lacks a break, or (3) clone the code for the fall-through case.
To make the case-statement implementation efficient, the compiler must choose a good method to find the desired case. The choice of case is not known until runtime and may, at runtime, change with each execution of the case statement. Thus, the compiler must emit code that will use the value of the controlling expression to locate the corresponding case. No single scheme works well for all instances. Many compilers have the ability to generate several different schemes and choose a specific scheme based on context.
This section examines three common strategies: a linear search, a computed address, and a binary search. Each strategy is appropriate under different circumstances. switch (e1) { case 0: block0; break; case 1: block1; break; case 3: block3; break; default: blockd; break; }
(a) Switch Statement (b) Implementation with Linear Search
■ FIGURE 7.8 Case Statement Implemented with Linear Search.
Linear Search
The simplest way to locate the appropriate case is to treat the case statement as the specification for a nested set of if-then-else statements. For example, the switch statement shown in Fig. 7.8(a) can be translated into the pseudocode shown in panel (b). This scheme preserves the meaning of the switch statement, but makes the cost of reaching individual cases dependent on the order in which they appear.
With a linear search strategy, the compiler should attempt to order the cases by estimated execution frequency. Still, when the number of cases is small—say three or four—this strategy can be efficient.
Direct Address Computation
If the case labels form a compact set, the compiler can do better than linear search. Consider the switch statement shown in Fig. 7.9(a). It has case labels from 0 to 9, plus a default case. In this case, the compiler can build a vector, or jump table, that contains the block labels, and find the desired label by indexing into the table. The jump table is shown in panel (b), while the code to compute the correct case’s label is shown in panel (c). The search code assumes that the jump table begins at @T and that a label occupies @LL bytes.
For a dense label set, this scheme generates compact and efficient code. The cost is small and constant—a brief calculation, a memory reference, and a jump. If a few holes exist in the label set, the compiler can fill those slots with the label for the default case. If no default case exists, the appropriate action depends on the language. In C, for example, the code should branch to the first statement after the switch, so the compiler can place that label in each hole in the table. If the language treats a missing case as an error, the Jump table a vector of labels used to transfer control based on a computed index into the table
switch (e1) { case 0: block0 break; case 1: block1 break; case 2: block2 break; … case 9: block9 break; default: blockd break; }
@T: LB0 LB1 LB2 LB3 LB4 LB5 LB6 LB7 LB8 LB9
t1 ← e1 if (0 > t1 or t1 > 9) then jump to LBd else t2 ← @T + t1 × @LL t3 ← memory(t2) jump to t3
(a) Switch Statement (b) Jump Table (c) Address Computation
■ FIGURE 7.9 Case Statement Implemented with Direct Address Computation.
compiler can fill holes in the jump table with the label of a block that throws a runtime error.
Binary Search
As the number of cases rises, linear search becomes inefficient. Similarly, as the label set becomes more sparse, jump table size becomes a problemfor direct address computation. The classic solutions from efficient searchapply here. If the compiler can impose an order on the case labels, it can usebinary search to obtain a logarithmic search rather than a linear one.
The idea is simple. The compiler builds a compact ordered table of caselabels, along with their corresponding block-address labels. It emits a binarysearch to find the case label or its absence. Finally, it either branches to thecorresponding label or to the default case.
The exact form of the search loop mightvary. For example, the code in panel (c)does not short circuit the case when it findsthe label early. Empirical testing may benecessary to find the best choices.
Fig. 7.10(a) shows a case statement with a sparse set of labels (0, 15, 23, 37,41, 50, 68, 72, 83, and 99) and a default case. The labels could, of course, cover a much larger range. Panel (b) shows the corresponding search table, and panel (c) shows a binary search that the compiler might emit to locatethe desired case and branch to it.
To aid in subsequent analysis, the compiler should record the set of jumptargets in the IR (such as ILOC’s tbl pseudooperation described in Ap-pendix A.5). Otherwise, the labels appear as data rather than code and passesthat analyze control flow, such as the CFG construction, may have difficultyfinding them (see Section 4.6). switch (e1) { case 0: block0 break; case 15: block15 break; case 23: block23 break; … case 99: block99 break; default: blockd break; }
Value Label
0 LB0 15 LB15 23 LB23 37 LB37 41 LB41 50 LB50 68 LB68 72 LB72 83 LB83 99 LB99
t1 ← e1
down ← 0 // lower bound up ← 10 // upper bound + 1
while (down + 1 < up) { middle ← (up + down) ÷ 2 if (Value[middle] ≤ t1) then down ← middle else up ← middle }
if (Value [down] = t1 then jump to Label[down] else jump to LBd
(a) Switch Statement (b) Search Table (c) Code for Binary Search
■ FIGURE 7.10 Case Statement Implemented with Binary Search.
SECTION REVIEW
Section titled “SECTION REVIEW”Programming languages include many features that implement control flow. The compiler needs a schema for each such construct in the source language. In some cases, such as a loop, one approach serves for multiple different constructs. In others, such as an if-then-else or a case statement, the compiler must choose between several implementation schemes.
To make the best choice in these more complex cases, the compiler writer may choose to build a more abstract initial IR and analyze that IR to determine the specific facts that the compiler needs to make an informed decision. Then, with those facts in hand, it can rewrite the construct to implement the chosen scheme.
REVIEW QUESTIONS
Section titled “REVIEW QUESTIONS”- Write ILOC code for the FORTRAN loop shown in the margin. Recall that the loop body must execute 100 iterations, even though the loop modifies the value of 1.
- Many programming languages include an unconditional jump, such as the goto statement in C. How might the compiler manage the label for such a jump in a syntax-driven translation scheme?
FORTRAN 66 lacked support for character strings, a major omission.
7.6 OPERATIONS ON STRINGS
Section titled “7.6 OPERATIONS ON STRINGS”Strings arise in multiple contexts. The most common strings contain characters, as found in most languages since COBOL. Some languages support strings with different element types. Basic string operations, however, have a common structure across many element types.
Support for string operations varies from that in C, where most manipulation takes the form of calls to library routines, to that in PL/I, where the language provides direct mechanisms to assign whole strings, substrings, and individual characters, and to concatenate strings to form new strings. To illustrate the translation issues that strings introduce, this section discusses string-length computation, string assignment, and string concatenation. Other string operations, such as substitution through a translation table, follow the same basic ideas.
String operations can be costly. Older CISC architectures, such as the IBM S/370 and the DEC VAX-11, provide extensive hardware support for character string manipulation. RISC machines rely more heavily on the compiler to code these complex operations using a set of simpler operations. The basic operation, copying bytes from one location to another, arises in many different contexts.
7.6.1 String Length
Section titled “7.6.1 String Length”Programs that manipulate strings often need to know the length of a string. The implementation of a length operation depends on the underlying representation(see Section 5.6.3). For a string with an explicit length field, the compiler can simply emit code to access the length at a fixed offset from the start of the string(usually, a negative offset).
For a null-terminated string, the running program must walk the string and count the elements, as shown in the margin. The pseudocode leaves the number of string elements in the variable len.
The length computation illustrates the tradeoff between the two representations. The explicit-length version uses more space and makes length an O(1) operation. The null-terminated version may use less space; it makes length an O(string length) operation.
7.6.2 String Assignment
Section titled “7.6.2 String Assignment”String assignment breaks into two distinct cases: single-character assignment and multicharacter assignment. Single character assignment can be straightforward. In C, an assignment from the third character of b to the
len←0
while(string[len]≠\0)
len←len+1
Finding the Length of a Null-Terminated String
second character of a can be written as a[1]=b[2];.(Recall that C defaults to zero as the lower bound in a vector or string.) In an ISA with one-byte characters and byte-oriented memory operations(cload and cstore), this assignment might translate into the simple code shown in the margin. Assume that r_{a} and r_{b} hold the base addresses of a and b.
Without hardware-supported, byte-length, memory operations, the code becomes more complex. The compiler must emit code to load the word that contains b[2]. The code must use a mask to clear the rest of the word and then shift the character from b[2] into the position for a[1]. It must load the word that contains a[1] and clear that byte(another and of an appropriate mask), and move the character from b[2] into that position(with an or operation). Finally, it must write the word that holds a[1] back to memory. The complexity of this operation may explain why byte-length loads and stores are common.
For multicharacter assignments, whether an entire string or a subrange, the compiler can wrap a loop around the code for a single-character assignment. With byte-length operations, the code is simple. The loop in the margin assigns all of b to a. It assumes that both strings have zero as a lower bound and that size_of(a) returns a’s allocated length-that is, its capacity. To assign a subrange, the upper and lower bounds change on both strings.
If the ISA lacks byte-oriented operations, multicharacter assignment can create complex situations. In the best case, the source and destination have the same memory alignment. In the worst case, the code must mask and shift each character to build the words in the destination string. These examples only arise in an ISA without byte-oriented memory operations and are left as an exercise for the reader.
To achieve efficient execution for long word-aligned strings, the compiler can generate code that uses whole-word loads and stores. Conceptually, the compiler wants to generate byte-oriented operations until it reaches a word or double-word alignment boundary, then use word or double-word operations as long as possible, and handle any remaining characters with byte-oriented operations. The effect is similar to unrolling the loop(see Section 8.5.2) and combining the operations, with a preloop to reach the alignment boundary and a postloop to handle any trailing characters.
As with single-character assignment, the code becomes more complex if the ISA lacks byte-oriented memory operations. In practice, the compiler’s runtime library might include carefully optimized routines to implement the nontrivial cases(e.g., POSIX memmove).
cloadAI r_{b},2→r_{2}
cstoreAI r_{2}→r_{n},1
Code for a[1]=b[2];
The compiler can emit code that uses Boolean operations with appropriate masks to clear bytes or to move a byte from one word to another.
la←size_of(a)
lb←length(b)
if(la<lb)
then throw an error
i←0
while(i<lb) do
a[i]←b[i]
i←i+1
Whole String Assignment
7.6.3 String Concatenation
Section titled “7.6.3 String Concatenation”Concatenation is simply a shorthand for a sequence of one or more assignments. It comes in two basic forms: appending string b to string a, and creating a new string that contains a followed immediately by b.
If sufficient space is not available, the code should raise a runtime exception or signal an error.
The former case requires a length computation followed by an assignment. The emitted code determines the length of a and then, if space permits, it copies the characters from b into the space that immediately follows the contents of a. The latter case copies each character in a and each character in b. The compiler, in essence, treats the concatenation as a pair of assignments.
In either case, the compiler should ensure that enough space is allocated to hold the result. In practice, either the compiler or the runtime system must know the allocated length of each string. If the compiler knows those lengths, it can perform the check during code generation and avoid the run-time check. In cases where the compiler cannot know the lengths of a and b, it must generate code to compute the lengths at runtime and to perform the appropriate test and branch.
7.6.4 Optimization of String Operations
Section titled “7.6.4 Optimization of String Operations”Because string operations often require O(string length) time, compiler writers should try to optimize them. A classic example of a string optimization problem is to find the length that would result from the concatenation of two strings, a and b. If+ is the concatenation operator, we might write this expression as length(a+b).
The expression length(a+b) has two obvious implementations:(1) construct a+b and compute its length(in C, strlen(strcat(a,b))), and (2) add the lengths of a and b(in C,strlen(a)+strlen(b)). The latter solution, of course, is desired, as it avoids creating a temporary string just to compute the length.
As discussed in Section 7.3.3, string operations may include a range check to avoid reading or writing characters outside of the string’s allocated extent. Range checks can prevent logical errors from corrupting other data; they can also prevent malicious code from either reading or corrupting runtime state. The string assignment example shown earlier carefully placed the range check outside the loop.
Range checks, of course, require basic information about string length. To check a write, the test will need to know the allocated size of the string. To check a read, it may also need to know the current size of the string.(Consider a string allocated to have 1,024 bytes that currently holds the characters “hello world!”. An attempt to read the 128th character should trip a range check.) The same kinds of range-check optimizations that apply to arrays also apply to strings.
SECTION REVIEW
Section titled “SECTION REVIEW”In principle, string operations are similar to vector operations. The details of string representation and the complications introduced by alignment and efficiency can complicate the code that the compiler must generate. Simple loops that copy one character at a time are easy to generate, to understand, and to prove correct. More complex loops that use word or double-word operations can be more efficient; the cost of that efficiency is added code to handle the corner cases. Many compilers handle the complex cases with a call to a string-copy routine in the runtime system.
REVIEW QUESTIONS
Section titled “REVIEW QUESTIONS”- Write ILOC code for the string assignment a ← b using word-length loads and stores. (Use character-length loads and stores in a postloop to clean up the end cases.) Assume that a and b are word aligned and nonoverlapping.
- If the two strings in question 1 are character aligned, what complications arise? Similarly, what complications arise if they may overlap?
7.7 PROCEDURE CALLS
Section titled “7.7 PROCEDURE CALLS”The implementation of procedure calls is, for the most part, straightforward. As shown in Fig. 7.11, and discussed in Section 6.5, a call consists of four distinct sequences: the precall and postreturn sequences in the caller, and the prolog and epilog in the callee. A single procedure can contain multiple call sites, each with its own precall and postreturn sequences. In most languages, a procedure has one entry point, so it has one prolog sequence and one epilog sequence. Many of the details involved in these sequences are described in Section 6.5. This section focuses on issues that affect the compiler’s ability to generate efficient, compact, and consistent code for procedure calls.
As a general rule, moving operations from the precall and postreturn sequences into the prolog and epilog sequences should reduce the overall size of the final code. If the call from p to q shown in Fig. 7.11 is the only call to q in the entire program, then moving an operation from the precall sequence
In languages that allow multiple entry points, such as PL/I, each entry point has its own prolog.
■ FIGURE 7.11 A Standard Procedure Linkage.
Section titled “■ FIGURE 7.11 A Standard Procedure Linkage.”For example, a static function in C can only be invoked by procedures defined in the same file.
If the function’s address is never taken, the compiler can customize its linkage.
in p to the prolog in q(or from the postreturn sequence in p to the epilog in q) has no impact on code size. If, however, other sites call q, then moving an operation from the caller to the callee(at all the call sites), it should reduce the overall code size by replacing multiple copies of an operation with a single one. As the number of call sites that invoke a given procedure rises, the savings grow. In general, this kind of linkage optimization can only be done during the design of the linkage convention, or in circumstances where the compiler knows and compiles each of the callers.
We assume that most user-written procedures are called from several locations; if not, both the programmer and the compiler should consider moving the procedure inline at the point of its only call.
Procedure calls in Algol-like and object-oriented languages are similar. The primary difference between calls in ALLs and OOLs lies in the technique used to locate the code for the callee(see Section 6.3). In addition, a call in an object-oriented language typically includes the receiver’s object record as an implicit parameter.
7.7.1 Evaluating Actual Parameters
Section titled “7.7.1 Evaluating Actual Parameters”When the compiler builds the precall sequence, it must emit code to evaluate the actual parameters to the call. The compiler treats each actual parameter as an expression. For a call-by-value parameter, the precall sequence evaluates the expression and stores its value in a location designated for that parameter-either in a register or in the callee’s AR. For a call-by-reference parameter, the precall sequence evaluates the parameter to an address and stores the address in a location designated for that parameter. If a call-by-erence parameter has no storage location, then the compiler may need to allocate space in the caller’s AR to hold the parameter’s value so that it has an address to pass to the callee.
If the source language specifies an evaluation order for actual parameters, the compiler must implement that order. Otherwise, it should use a consistent order-either left to right or right to left. The evaluation order matters for parameters that might have side effects. For example, a program that used push and pop to manipulate a stack would produce different results for subtract(pop(), pop()) under left-to-right and right-to-left evaluation.
Procedures typically have several implicit arguments, such as the procedure’s ARP, the caller’s ARP, the return address, and any information needed to establish addressability. Object-oriented languages pass the receiver as an implicit parameter. Some of these arguments are passed in registers while others usually reside in memory. Many architectures have an operation like
jsr label1
that transfers control to label1 and places the address of the operation that follows the jsr into a designated register.
Procedures passed as actual parameters may require special treatment. If p calls q, passing procedure r as an argument, p must pass to q more information than r’s starting address. In particular, if the compiled code uses access links to find nonlocal variables, the callee needs r’s lexical level so that a subsequent call to r can find the correct access link for r’s level. The compiler can construct an(address, level) pair and pass it(or its address) in place of the procedure-valued parameter. When the compiler constructs the precall sequence for a procedure-valued parameter, it must emit the extra code to fetch the lexical level and adjust the access link accordingly.
7.7.2 Saving and Restoring Registers
Section titled “7.7.2 Saving and Restoring Registers”Under any calling convention, one or both of the caller and the callee must preserve register values. Often, linkage conventions use a combination of caller-saves and callee-saves registers. As both the cost of memory operations and the number of registers have risen, the cost of saving and restoring registers at call sites has increased, to the point where it merits careful attention.
In choosing a strategy to save and restore registers, the compiler writer must consider both efficiency and code size. Some processor features impact this choice. Features that spill a portion of the register set can reduce code size. Examples of such features include register windows on the SPARC machines, the multiword load and store operations on the Power architec-tures, and the high-level call operation on the DEC VAX-11. Each of these features offers the compiler a compact way to save and restore some portion of the register set.
While larger register sets can increase the number of registers that the code saves and restores, in general, using these additional registers improves the speed of the resulting code. With fewer registers, the compiler would be forced to generate loads and stores throughout the code; with more registers, many of these spills occur only at a call site.(The larger register set should reduce the total number of spills in the code.) The concentration of saves and restores at call sites presents the compiler with opportunities to handle them in better ways than it might if they were spread across an entire procedure.
Using Multiregister Memory Operations When saving and restoring adjacent registers, the compiler can use a multiregister memory operation. Many ISAs support doubleword and quadword load and store operations. Using these operations can reduce code size; it may also improve execution speed.
Using a Library Routine As the number of registers grows, so do the precall and postreturn sequences. The compiler may benefit from using custom save and restore routines with simplified call sequences. Across all calls, this strategy could produce a significant code-size savings.
The save and restore routines can take an argument that specifies which registers must be preserved. It may be worthwhile to generate optimized versions for common cases, such as preserving all the caller-saves or callee-saves registers.
Combining Responsibilities To reduce overhead further, the compiler might have the precall sequence pass the callee a value that specifies which caller-saves registers to preserve. The callee can then invoke the compiler’s save routine to preserve both the caller and callee save registers in a single call. The epilog sequence can pass the same specification to the restore routine to reload the saved registers. This approach limits the overhead to a single call to save and another to restore. It separates responsibility(caller saves versus callee saves) from the cost to call the routine.
The compiler writer should pay close attention to the differences in code size and runtime speed among these distinct approaches. The code should use the fastest operations for saves and restores. This requires a close look at the costs of single-register and multiregister operations on the target architecture. Using library routines to perform saves and restores can save space;careful implementation of those library routines may mitigate the added cost of invoking them.
SECTION REVIEW
Section titled “SECTION REVIEW”The code for a procedure call is split between the caller and the callee, and among the prolog, epilog, precall, and postreturn sequences. These sequences cooperate to implement the linkage convention, as discussed in Chapter 6. Language rules and parameter binding rules dictate both the order and the manner of evaluation for actual parameters. System-wide conventions determine responsibility for saving and restoring registers.
Compiler writers pay particular attention to the implementation of procedure calls because the optimization opportunities are difficult for general techniques to discover (see Chapters 8 and 10). The many-to-one nature of the caller-callee relationship complicates analysis and transformation, as does the distributed nature of the cooperating code sequences. Equally important, minor deviations from the defined conventions can cause incompatibilities in code from different compilers.
REVIEW QUESTIONS
Section titled “REVIEW QUESTIONS”-
When a procedure saves registers, either callee-saves registers in its prolog or caller-saves registers in a precall sequence, where do the values in those registers go? How much space should the compiler reserve to hold them?
-
In some situations, the compiler must create a storage location to hold the value of a call-by-reference parameter. What kinds of parameters may not have their own storage locations? What actions might be required in the precall and postreturn sequences to handle these actual parameters correctly?
7.8 SUMMARY AND PERSPECTIVE
Section titled “7.8 SUMMARY AND PERSPECTIVE”One of the more subtle tasks that confronts the compiler writer is selecting a scheme to implement each source-language construct. Almost any source language construct can be implemented in multiple ways. The specific choices that the compiler writer makes at design time have a strong impact on the code that the compiler generates.
In a compiler that is not intended for production use—where the performance of the compiled code is less important—the compiler writer might select easy to implement translations that produce simple code. If the customers expect performance, as with an optimizing compiler, the compiler writer should focus on translations that expose as much information as possible to the later phases of the compiler—low-level optimization, instruction scheduling, and register allocation. These two different perspectives lead to different shapes for loops, to different disciplines for naming temporary variables, and, possibly, to different evaluation orders for expressions.
The classic example of this distinction is the case statement. In a debugging compiler, the implementation as a cascaded series of if-then-else constructs is fine. In an optimizing compiler, the inefficiency of the myriad tests and branches makes a more complex implementation scheme worthwhile. The effort to improve the case statement must be made when the IR is generated; few, if any, optimizers will convert a cascaded series of conditionals into a binary search or a direct jump table.
CHAPTER NOTES
Section titled “CHAPTER NOTES”The material contained in this chapter falls, roughly, into two categories:generating code for expressions and handling control-flow constructs. Ex-pression evaluation is well explored in the literature. Discussions of how to handle control flow are more rare; much of the material on control flow in this chapter derives from folklore, experience, and careful reading of the output of compilers.
Floyd presented the first multipass algorithm for generating code from expression trees[160]. He points out that both redundancy elimination and algebraic reassociation have the potential to improve the results of his algorithm. Sethi and Ullman[321] proposed a two-pass algorithm that is optimal for a simple machine model; Proebsting and Fischer extended this work to account for small memory latencies[299]. Aho and Johnson[6] introduced dynamic programming to find least-cost implementations.
The predominance of array calculations in scientific programs led to work on array-address expressions and to optimizations(like strength reduction, Section 10.7.2) that improve them. The algebraic transformations used to simplify the address polynomial for multidimensional arrays follow Scar-borough and Kolsky[317]. Dope vectors appeared in ALGOL-60 systems; Sattley describes their use to handle dynamically allocated arrays[316].
Harrison used string manipulation as a motivating example for discussing pervasive inline substitution and specialization[192]. The example with length(a+b) in Section 7.6.4 comes from that paper.
Mueller and Whalley describe the impact of different loop shapes on performance[280]. Bernstein provides a detailed discussion of the options that arise in generating code for case statements[43]. The best descriptions of inkage conventions and their implementations appear in processor-specific rating-system-specific manuals.
EXERCISES
Section titled “EXERCISES”- Extend the pseudocode for the treewalk code generator in Fig. 7.2 to insert type conversions for x, +, +, and -. Assume that type(node) returns an enumerated value from the set { Short, Int, Float, Double }
and that the conversions are specified by the table:
| Short | Int | Float | Double | |
|---|---|---|---|---|
| Short | Short | Int | Float | Double |
| Int | Int | Int | Float | Double |
| Float | Float | Float | Float | Double |
| Double | Double | Double | Double | Double |
-
For each of the trees below, show the ILOC code that the treewalk code-generation algorithm from Fig. 7.2 would emit. Assume an unlimited set of virtual registers.
-
For trees (a) and (b) above, show ILOC code that a translator might emit if it tried to minimize register use. For each interior node, indicate which of its children should be evaluated first.
-
Implementation concerns often mean that textually identical references in the source program have different runtime costs. Compare and contrast the cost of reading the value of a local scalar variable x when:
a. x is unambiguous b. x is ambiguous c. x is a call-by-value parameter of the current procedure d. x is a call-by-reference parameter of the current procedure e. x is static
-
For a character array A[10:12,1:3] stored in row-major order, show ILOC code to calculate the address of A[i,j]. Assume that A begins at@A. Use as few ILOC operations as you can.
-
Consider an integer array A[1:7,2:9] stored in column-major order(as in FORTRAN). Assume that A begins at@A.
Derive the formula to compute the address of A[i,j] and write down ILOC code for the calculation.
Section 7.4
Section titled “Section 7.4”- For the assignment x←a>b∧b>c:
a. Write ILOC to evaluate the statement using the ILOC comparison and conditional branch syntax(see page 763).
b. Write ILOC to evaluate the statement using predicated operations, as shown in Section 7.4.
- Consider a simple if-then-else construct:
if(x<y) then
block1;
else block2;
What properties of block1 and block2 should the compiler consider in choosing between an implementation with(a) a comparison and a conditional branch,(b) predicated execution, and(c) a conditional move? How does branch latency affect the decision?
Section 7.5
Section titled “Section 7.5”- You recently implemented, by hand, a scanner. The scanner spends most of its time in a single while loop that contains a large case statement.
a. How would the different case statement implementation techniques affect the efficiency of your scanner?
b. How would you change your source code to improve the run-time performance under each of the case statement implementation strategies?
- Convert the following C tail-recursive function to a loop:
Listlast(List1){
if (1== NULL)
return NULL;
else if (1->next== NULL)
return 1;
else
return last (1->next);}
Show the C code for the loop. loadI @b => r@b loadI @a => r@a loadI NULL => r1 L1: cload r@b => r2 cstore r2 => r@a addI r@b,1 => r@b addI r@a,1 => r@a cmp_NE r1,r2 => r4 cbr r4 => L1,L2 L2: nop // next statement
(a) Original Code (b) Generated ILOC
■ FIGURE 7.12 Example for Exercise 11.
- Consider the character copying loop shown in Fig. 7.12. Modify the ILOC code so that it branches to an error handler at Lsov on any attempt to overrun the allocated length of a. Assume that the allocated length of a is stored as an unsigned four-byte integer at an offset of -8 from the start of a.
- String assignment on overlapping strings can become complex. a. Write the pseudocode for a function shuffle(a,s,1,o) that copies 1 characters starting at a[s] to a[s+o]. Note that o can be positive or negative. b. How would you range check the assignment in shuffle? Assume that length(a) returns the number of characters stored in a and size_of(a) returns the allocated size of a.
- Consider an unambiguous, local, integer variable x. A call site in the procedure that declares x passes it as a call-by-reference actual parameter. The compiler can keep x in a register except at the call site. Inside the callee, x must have a memory address. a. Where should the compiler store x? b. How should the compiler handle x at the call site? c. How would your answers change if x was passed as a call-by-value parameter?
- The linkage convention is a contract between the compiled code for a procedure and its callers. It creates a known interface that callers can use to safely invoke the procedure. Thus, the compiler should only violate
Section 7.6 Section 7.7
the linkage convention when such a violation cannot be detected from outside the compiled code.
a. Under what circumstances can the compiler safely choose to implement a variant (e.g., nonstandard) linkage? Give examples from real programming languages.
b. What changes might make the calling sequence more efficient and what facts would the compiler need to make those changes?
← node-book_engineering-a-compiler_chapter-06-implementing-procedures | node-book_engineering-a-compiler | node-book_engineering-a-compiler_chapter-08-introduction-to-optimization →