Docsity

Scalable Certification for Typed Assembly Language, Lecture notes of Compiler Design

Toggle sidebar
bg1
Scalable Certification for
Typed Assembly Language
Dan Grossman and Greg Morrisett 
Department of Computer Science, Cornell University
Abstract. A type-based certifying compiler maps source code to ma-
chine code and target-level type annotations. The target-level annota-
tions make it possible to prove easily that the machine code is type-safe,
independent of the source code or compiler. To be useful across a range of
source languages and compilers, the target-language type system should
provide powerful type constructors for encoding higher-level invariants.
Unfortunately, it is difficult to engineer such type systems so that anno-
tation sizes are small and verification times are fast.
In this paper, we describe our experience writing a certifying compiler
that targets Typed Assembly Language (TALx86) and discuss some gen-
eral techniques we have used to keep annotation sizes small and verifi-
cation times fast. We quantify the effectiveness of these techniques by
measuring their effects on a sizeable application — the certifying com-
piler itself. Using these techniques, which include common-subexpression
elimination of types, higher-order type abbreviations, and selective rever-
ification, can dramatically change certificate size and verification time.
1 Background
A certifying compiler takes high-level source code and produces target code with
acert ifi cat e that ensures that the target code respects a desired safety or security
policy. To date, certifying compilers have primarily concentrated on producing
certificates of type safety. For example, Sun’s javac compiler maps Java source
code to statically typed Java Virtual Machine Language (JVML) code. The
JVML code includes type annotations that a verifier based on dataflow analysis
can use to ensure that the code is type-safe.
However, both the instructions and the type system of JVML are at a rel-
atively high level and are specifically tailored to Java. Consequently, JVML is
ill-suited for compiling a variety of source-level programming languages to high-
performance code. For example, JVML provides only high-level method-call and
This material is based on work supp orted in part by the AFOSR grant F49620-
97-1-0013, ARPA/RADC grant F30602-1-0317, and a National Science Foundation
Graduate Fellowship. Any opinions, findings, and conclusions or recommendations
expressed in this publication are those of the authors and do not reflect the views
of these agencies.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d

Partial preview of the text

Download Scalable Certification for Typed Assembly Language and more Lecture notes Compiler Design in PDF only on Docsity!

Scalable Certification for

Typed Assembly Language

Dan Grossman and Greg Morrisett 

Department of Computer Science, Cornell University

Abstract. A type-based certifying compiler maps source code to ma- chine code and target-level type annotations. The target-level annota- tions make it possible to prove easily that the machine code is type-safe, independent of the source code or compiler. To be useful across a range of source languages and compilers, the target-language type system should provide powerful type constructors for encoding higher-level invariants. Unfortunately, it is difficult to engineer such type systems so that anno- tation sizes are small and verification times are fast. In this paper, we describe our experience writing a certifying compiler that targets Typed Assembly Language (TALx86) and discuss some gen- eral techniques we have used to keep annotation sizes small and verifi- cation times fast. We quantify the effectiveness of these techniques by measuring their effects on a sizeable application — the certifying com- piler itself. Using these techniques, which include common-subexpression elimination of types, higher-order type abbreviations, and selective rever- ification, can dramatically change certificate size and verification time.

1 Background

A certifying compiler takes high-level source code and produces target code with a certificate that ensures that the target code respects a desired safety or security policy. To date, certifying compilers have primarily concentrated on producing certificates of type safety. For example, Sun’s javac compiler maps Java source code to statically typed Java Virtual Machine Language (JVML) code. The JVML code includes type annotations that a verifier based on dataflow analysis can use to ensure that the code is type-safe. However, both the instructions and the type system of JVML are at a rel- atively high level and are specifically tailored to Java. Consequently, JVML is ill-suited for compiling a variety of source-level programming languages to high- performance code. For example, JVML provides only high-level method-call and

 (^) This material is based on work supported in part by the AFOSR grant F49620- 97-1-0013, ARPA/RADC grant F30602-1-0317, and a National Science Foundation Graduate Fellowship. Any opinions, findings, and conclusions or recommendations expressed in this publication are those of the authors and do not reflect the views of these agencies.

method-return operations. Also, it provides no provision for performing gen- eral tail-calls on methods. Therefore, JVML is a difficult target for compilers of functional languages such as Scheme that require tail-call elimination. In addition, current platforms for JVML either interpret programs or compile them further to native code. Achieving acceptable performance seems to demand compilation with a good deal of optimization. To avoid security or safety holes, the translation from JVML to native code should also be done by a certifying compiler. That way, we can verify the safety of the resulting code instead of trusting the ā€œjust-in-timeā€ compiler.

Another example of a certifying compiler is Necula and Lee’s Touchstone compiler [22]. Touchstone compiles a small, type-safe subset of C to optimized DEC-Alpha assembly language. The key novelty of Touchstone is that the cer- tificate it produces is a formal ā€œproofā€ that the code is type-correct. Checking the proof for type-correctness is relatively easy, especially compared to the ad hoc verification process for JVML. As such, the Touchstone certificates provide a higher degree of trustworthiness. The proofs of the Touchstone system are represented using the general- purpose logical framework LF [11]. The advantage of using LF to encode the proofs is that, from an implementation perspective, it is easy to change the type system of the target language. In particular, the proof checker is parameterized by a set of primitive axioms and inference rules that effectively define the type system. The checker itself does not need to change if these rules are changed. Consequently, the use of LF makes it easy to change type systems to adapt to different source languages or different compilation strategies. Indeed, more re- cent work uses a very different type system for certifying the output of Special J [5, 24], a compiler for Java. Although changing the type system is easy for the implementor, doing so obligates one to an enormous proof burden: Every change requires a proof of the soundness of the type system with respect to the underlying machine’s semantics. Constructing such proofs is an extremely difficult task. In the absence of a proof, it is not clear what assurances a verifier is actually providing.

1.1 An Alternative Approach

Our goal is to make it easy for certifying compilers to produce provably type- correct code without having to change the type system of the target language. That way, it suffices to write and trust one verifier for one type system. To- ward this end, we have been studying the design and implementation of general- purpose type systems suitable for assembly language [20, 19]. Ultimately, we hope to discover typing constructs that support certifying compilation of many orthogonal programming-language features. Our current work focuses on the design of an extremely expressive type sys- tem for Intel’s IA32 assembly language and a verifier we call TALx86 [18]. Where possible, we have avoided including high-level language abstractions like pro- cedures, exception handlers, or objects. In fact, the only high-level operation

type annotations and the time needed to verify the code are essentially linear in the size of the object code. The constant factors are small enough to permit verification of our entire compiler in much less than one minute.

In the next section, we give a taxonomy for general approaches to reducing type-annotation overhead and further discuss other projects related to certifying compilation. Although it is an informal description of existing techniques, we have found this classification useful and we know of no other attempt to classify the approaches. In Section 3, we summarize relevant aspects of the TALx86 type system, annotations, and verification process. We then show how these features are used to encode the provably safe compilation of the control-flow aspects of Popcorn, including procedures and exceptions. This extended example demonstrates that an expressive type system can permit reasonable compilation of a language for which it is not specifically designed. It also shows qualitatively that if handled naively, type-annotation size becomes unwieldy. In Section 4, we use the example to analyze several approaches that we have examined for reducing type-annotation overhead. Section 5 presents the quantitative results of our investigation; we conclude that the TALx86 approach scales to verify our Popcorn compiler, the largest Popcorn application we have written. Moreover, all of the techniques contribute significantly to reducing the overhead of certifying compilation. Finally, we summarize our conclusions as a collection of guidelines for designers of low-level safety policies.

2 Approaches to Efficient Certification

Keeping annotation size small and verification time fast in the presence of op- timizations and advanced source languages is an important requirement for a practical system that relies on certified code. In this section, we classify some approaches to managing the overhead of certifying compilation and discuss their relative merits. None of the approaches are mutually exclusive; any system will probably have elements of all of them.

The ā€œBake it inā€ Approach If the type system supports only one way of compiling something, then compilers do not need to write down that they are using that way. For example, the type system could fix a calling convention and require compilers to group code blocks into procedures. JVML, Touchstone, and Special J all use this approach. Baking in assumptions about procedures eliminates the need for any annota- tions describing the interactions between procedures. However, it inhibits some inter-procedural optimizations, such as inter-procedural register allocation, and makes it difficult to compile languages with other control features, such as ex- ception handlers. In general, the ā€œbake it inā€ approach reflects particular source features into the target language rather than providing low-level constructors suitable for encoding a variety of source constructs. For example, the certifier for Special J first processes a, ā€œclass descriptor whose form is very close to that

of the JVM class descriptorsā€ [24], so only programs conforming to the JVML class hierarchy and type system are certifiable by this checker. Even general frameworks inevitably bake in more than the underlying ma- chine requires. A TALx86 example is that labels are abstract — well-formed code cannot examine the actual address used to implement a label. This abstraction prevents some clever implementation techniques. Any verifiable safety policy must impose some conservative restrictions; choosing the restrictions is a crucial design decision that is a fundamental part of a policy.

The ā€œDon’t optimizeā€ Approach If a complicated analysis is necessary to prove an optimization safe, then the reasoning involved must be encoded in the an- notations. For example, when compiling dynamically typed languages such as Scheme, dynamic type tests are in general necessary to ensure type safety. A simple strategy is to perform the appropriate type test before every operation. With this approach, a verifier can easily ensure safety with a minimum of an- notations. This strategy is the essence of the verification approach suggested by Kozen [14]. Indeed, it results in relatively small annotations and fast verification, but at the price of performance and flexibility. In contrast, an optimizing compiler may attempt to eliminate the dynamic checks by performing a ā€œsoft-typingā€ analysis [30]. However, the optimized code requires a more sophisticated type system to convince the verifier that type tests are unnecessary. To make verification tractable, such type systems require additional annotations. For example, the Touchstone type system supports static elimination of array-bounds checks, but it requires additional invariants and proof terms to support the optimization. Another example is record initialization: An easy way to prove that memory is properly initialized is to write to the memory in the same basic block in which the memory is allocated. Proving that other instruction schedules are safe may require dataflow annotations that describe the location of uninitialized memory. Unoptimized code also tends to be more uniform, which in turn makes the annotations more uniform. For example, if a callee-save register is always pushed onto the stack by the callee (even when the register is not used), then the annota- tions that describe the stack throughout the program will have more in common. Such techniques can improve the results of the ā€œCompressionā€ approach (dis- cussed below) at the expense of efficiency.

The ā€œReconstructionā€ Approach If it is easy for the verifier to infer a correct annotation, then such annotations can be elided. For example, Necula shows how simple techniques may be used for automatically reconstructing large portions of the proofs produced by the Touchstone compiler [23]. It is important that verification time not unduly suffer, however. For this reason, code producers should know the effects that annotation elision can have. Unfortunately, in expressive systems such as TALx86, many forms of type recon- struction are intractable or undecidable. The verifier could provide some simple heuristics or default guesses, but such maneuvers are weaker forms of the ā€œbake it inā€ approach.

future require only retrieving the answer from a table. The problem of managing low-level types during compilation is quite similar to the problem of managing them during verification, but in the case of type-directed compilation, it is ap- propriate to specialize the task to the compiler. Finally, we should note that comparing the size of compressed low-level types to the size of uncompressed object code is somewhat misleading because object code compresses quite well [16, 7]. Domain-specific techniques include taking the instruction format into account (instead of the generic compression technique of processing entire bytes); detecting common sequences of instructions; and de- tecting similarity modulo a rarely repeated field, such as a branch target address. Analogous techniques may prove useful for annotations as well, but we know of no work that has tried them.

The ā€œAbbreviationā€ Approach The next step beyond simple sharing is to use higher-order annotations to factor out common portions. Such annotations are essentially functions at the level of types. Tarditi and others used this approach in their TIL compiler [28]. As we show in Section 4, this approach can exploit similarities that sharing cannot. Furthermore, higher-order annotations make it relatively easy for a compiler writer to express high-level abstractions within the type system of the target language. In our experience, using abbreviations places no additional burden on the compiler writer because she is already rea- soning in terms of these abstractions. However, if the verifier must expand the abbreviations in order to verify the code, verification time may suffer. Higher-order abbreviations are also an important component in the certified- code framework that Appel and Felty [1] propose. They suggest formalizing a machine’s semantics and a safety policy in a higher-order logical framework. The code producer must then supply a formal proof that a program obeys the policy. Because a proof expressed directly in terms of a machine’s semantics would presumably be enormous, Appel and Felty suggest that a compiler would first prove that a collection of lemmas are sound with respect to the semantics and then apply the lemmas to a program. In a sense, these lemmas are parameterized abbreviations that define a suitably concise type system.

In our system, we use all of these approaches to reduce annotation size and verification time. However, we have attempted to minimize the ā€œbake it inā€ and ā€œdon’t optimizeā€ approaches in favor of the other techniques. Unlike javac, Touchstone, or Special J, TALx86 makes no commitment to calling convention or data representation. In fact, it has no built-in notion of functions; all control flow is just between blocks of code. The design challenge for TALx86, then, is to provide generally useful constructors that compilers can use in novel ways to encode the safety of their compilation strategies. As a type system, TALx86 does ā€œbake inā€ more than a primitive logical de- scription of the machine. For example, it builds in a distinction between integers and pointers. As a result, programs cannot use the low bits of pointers to store information and then mask these bits before reading memory. Also, memory lo- cations are statically divided into code and data (although extensions support

run-time code generation [12]). In order to investigate the practicality of expres- sive low-level safety policies, we have relied on a rigorous, hand-written proof of type soundness and a procedural implementation of the verifier. A more formal approach would be to encode the proof in a logical framework and use a verifier produced mechanically from the proof. Using our approach, we have been able to examine the feasibility of compiler- independent safety policies on a far larger scale than has been previously possible. To date, certifiers based on proof-carrying code technology have all had compiler- specific safety policies and no compiler has targeted the compiler-independent safety policies of Appel and Felty. Not only was TALx86 designed to be compiler- independent, but we and others have written three separate compilers that target TALx86. In this paper, we discuss our optimizing Popcorn compiler.^1 This com- piler, itself a certified TALx86 program, is a several-hundred kilobyte executable compiled from over eighteen thousand lines of source code.

3Compiling to TALx86: An Extended Example

In this section, we briefly review the structure of the TALx86 type system, its annotations, and the process of verification. In what follows, we present relevant TALx86 constructs as necessary, but for the purposes of this paper, it is sufficient to treat the types as low-level syntaxfor describing pre-conditions. Our purpose is not to dwell on the artifacts of TALx86 or its relative expressiveness. Rather, we want to give some intuition for the following claims, which we believe transcend TALx86:

  • If the safety policy does not bake in data and control abstractions, then the annotations that the compiler uses to encode them can become large.
  • In fact, the annotations describing compiler conventions consume much more space than the annotations that are specific to a particular source program.
  • Although the annotations for compiler conventions are large, they are also very uniform and repetitious, though they become much less so in the pres- ence of optimizations.

Because of this focus, we purposely do not explain some aspects of the annota- tions other than to mention the general things they are encoding. The reader interested in such details should consult the literature [20, 19, 10, 18, 9, 27]. A TALx86 object file consists of IA32 assembly-language instructions and data. As in a conventional assembly language, the instructions and data are organized into labeled sequences. Unlike conventional assembly language, some labels are equipped with a type annotation. The type annotations on the labels of instruction sequences, called code types, specify a pre-condition that must be satisfied before control may be transferred to the label. The pre-condition specifies, among other things, the types of registers and stack slots. For exam- ple, if the code type annotating a label L is {eax:int4, ebx:S(3), ecx: ^

(^1) The other compilers are a simple stack-based compiler for Popcorn and a compiler for a core subset of Scheme.

TALx86 type int4. Arithmetic operations are allowed on values of this type; treating them as pointers is not. Our compiler uses the standard C calling con- vention for the IA32 architecture. Under this convention, the parameters are passed on the stack, the return address is shallowest on the stack, the return value is passed in register eax, and the caller pops the parameters upon return. All of these specifics are encoded in TALx86 by giving foo this pre-condition:

foo: āˆ€s:Ts. {esp: { eax: int esp: int4::s} ::int ::s}

The pre-condition for foo concerns only esp (the stack pointer) and requires that this register point to a stack that contains a return address (which itself has a pre-condition), then an int4 (i.e. the parameter), and then some stack, s. The return address expects an int4 in register eax and the stack to have shape int4::s. (The int4 is there because the caller pops the parameters.) The pre-condition is polymorphic over the ā€œrestā€ of the stack as indicated by the universal quantification over the stack-type variable s. This technique allows a caller to abstract the current type of the stack upon entry, and it ensures that the type is preserved upon return. Types in TALx86 are classified into kinds (types of types), so that we do not confuse ā€œstandardā€ types such as int4 with ā€œnon-standardā€ types such as stack types. To maintain the distinction, we must label the bound type variable s with its kind (Ts). Notice that our annotation already includes much more information than it would need to if the safety policy dictated a calling convention. In that case, we would presumably just give the parameter types and return type of the function. Some systems, including the certifier for Special J [5], go even further — they encode the types in the string for the label, so it appears that no annotation is necessary. Of course, the safety policy now attaches specific meaning to the characters in a label; the annotations are encoded in the assembly listing. Our annotation does not quite describe the standard C calling convention. In particular, the standard requires registers ebx, esi, and edi to be callee- save. (It also requires ebp, traditionally the frame pointer, to be callee-save. Our compiler uses ebp for the exception handler.) We encode callee-save registers using polymorphism:^3

foo: āˆ€s:Ts a1:T4 a2:T4 a3:T. {esp: {eax:int4 esp: int4::s ebx:a1 esi:a2 edi:a3} ::int4::s ebx:a1 esi:a2 edi:a3}

This pre-condition indicates that for any standard types a1, a2, a3,^4 the appropriate registers must have those types before foo is called and again when

(^3) Here and below, underlining is only for emphasis. (^4) The kind T4 includes all types whose values fit in a register.

the return address is invoked. This annotation restricts the behavior of foo to preserve these registers because it does not know of any other values with these types. More formally, this fact follows from parametricity [6, 29]. Notice that if we wish to use different conventions about which registers should be callee-save, then we need to change only the pre-condition on foo. In particular, we do not need to change the underlying type system of TALx86. Much more detail is required to encode our compiler’s translation of exception handling [19], so we just sketch the main ideas. We reserve register ebp to point into the middle of the stack where a pointer to the current exception handler resides. This handler expects an exception packet in register eax. Because foo might need to raise an exception, its pre-condition must encode this strategy. Also, it must encode that if foo returns normally, the exception handler is still in ebp. We express all these details below, where @ is an infixoperator for appending two stack types.

foo: āˆ€s1:Ts s2:Ts a1:T4 a2:T4 a3:T. {esp: {eax:int esp: int4::s1@{esp:s2 eax:exn}::s ebp: {esp:s2 eax:exn}::s ebx:a1 esi:a2 edi:a3} ::int4::s1@{esp:s2 eax:exn}::s2} ebp: {esp:s2 eax:exn}::s ebx:a1 esi:a2 edi:a3}

We urge the reader not to focus on the details other than to notice that none of the additions are particular to foo, nor would it be appropriate for a safety policy to bake in this specific treatment of exception handlers. Also, we have assumed there is a type exn for exception packets. TALx86 does not provide this type directly, so our compiler must encode its own representation using an extensible sum [9]. Each of the four occurrences of exn above should in fact be replaced by the type

∃c:Tm ^[(^T^rw(c)[int4^rw])^rw,c]

but in the interest of type-setting, we spare the reader the result. For the sake of completeness, we offer a final amendment to make this pre- condition correct. Our compiler schedules function calls while some heap records may be partially initialized. This strategy is arguably better than the ā€œdon’t optimizeā€ approach of always initializing records within a basic block, but it re- quires that we convince the verifier that no aliases to partially initialized records escape. In particular, the pre-condition for foo uses two capability variables [27], as shown below,^5 to indicate that it does not create any aliases to partially initialized records reachable from the caller or exception handler.

(^5) The constructor &[...] joins two capabilities to produce a harder-to-satisfy capa- bility; we omit its definition.

some ā€œplace-holderā€ type so that the stack type describes a stack of the correct size. Different control-flow paths may use the same stack slot for temporary variables of different types. In these cases, no previously seen type can serve as this place-holder. TALx86 provides a primitive type top4 which is a supertype of all types ranging over word-sized values. We give this type to the dead stack slots at the control-flow join; the appropriate subtyping on control transfers is handled implicitly by the verifier.^6 In addition to live variables, all of the invariants involving the stack, the exception handler, etc. must be preserved as control flows through labels, so this information looks much as it does for function-entry labels. For example, suppose our function foo uses all of the callee-save registers and needs three spill slots. Furthermore, suppose that at an internal label, l, there are two live variables, both of type int4, one in register esi and one in the middle spill slot. Then a correct pre-condition for l is:

l: āˆ€s1:Ts s2:Ts e1:Tcap e2:Tcap a1:T4 a2:T4 a3:T4. {esp: top4::int4::top4::a3::a2::a ::{eax:int esp: int4::s1@{esp:s2 eax:exn cap:e2}::s ebp: {esp:s2 eax:exn cap:e2}::s ebx:a1 esi:a2 edi:a cap: &[e1,e2]} ::int4::s1@{esp:s2 eax:exn cap:e2}::s2} ebp: {esp:s2 eax:exn cap:e2}::s cap: &[e1,e2] esi: int4}

Our register allocator tries not to use callee-save registers so that functions do not have to save and restore them. For example, suppose registers esi and edi are not used in a function. Then internal labels will encode that a value of type a1 is on the stack in the appropriate place, esi contains a value of type a2, and edi contains a value of type a3. If one or more records were partially initialized on entry to l, then the pre- condition would have a more complicated capability; we omit the details. What should be clear at this point is that the type annotations for internal labels are considerably less uniform than function-entry annotations.

4 Recovering Conciseness and Efficiency

Continuing the examples from the previous section, we describe three techniques for reducing the size of annotations. We then discuss techniques, most notably hash-consing, that can reduce the space and time required during verification. The next section quantifies the effectiveness of these and other techniques. (^6) It is theoretically possible to use polymorphism instead of a supertype, but in practice we found doing so very unwieldy.

4.1 Sharing Common Subterms

Because the annotations repeat information, we can greatly reduce their total size by replacing identical terms with a pointer to a shared term. As an example, consider again the pre-condition for the function foo, which takes and returns an int:

type exn = ∃c:Tm ^[(^T^rw(c)[int4^rw])^rw,c] foo: āˆ€s1:Ts s2:Ts e1:Tcap e2:Tcap a1:T4 a2:T4 a3:T. {esp: {eax:int esp: int4::s1@{esp:s2 eax:exn cap:e2}::s ebp: {esp:s2 eax:exn cap:e2}::s ebx:a1 esi:a2 edi:a cap: &[e1,e2]} ::int4::s1@{esp:s2 eax:exn cap:e2}::s2} ebp: {esp:s2 eax:exn cap:e2}::s ebx:a1 esi:a2 edi:a cap: &[e1,e2]} Removing some common subterms by hand, we can represent the same in- formation with the following pseudo-annotation:

1 = ∃c:Tm ^[(^T^rw(c)[int4^rw])^rw,c] 2 = &[e1,e2] 3 = {esp:s2 eax: 1 cap:e2}::s

4 = int4::s1@ 3

5 = {eax:int4 esp: 4 ebp: 3

ebx:a1 esi:a2 edi:a3 cap: 2 }:: 4

foo: āˆ€s1:Ts s2:Ts e1:Tcap e2:Tcap a1:T4 a2:T4 a3:T. {esp: 5 ebp: 3 ebx:a1 esi:a2 edi:a3 cap: 2 }

Other pre-conditions can share subterms with this one. For example, the pre-condition for l from the previous section can be rewritten as:

l: āˆ€s1:Ts s2:Ts e1:Tcap e2:Tcap a1:T4 a2:T4 a3:T4. {esp: top4::int4::top4::a3::a2::a1:: 5 ebp: 3 cap: 2 esi:int4} Despite exploiting significant sharing, this example illustrates some limita- tions of sharing common subterms. First, we would like to share all the occur- rences of ā€œs1:Ts s2:Ts ... a3:T4ā€, but whether or not we can do so depends on the abstract syntaxof the language. Second, pre-conditions for functions with different parameter types or return types cannot exploit subterms 4 or 5. An- other possible shortcoming not demonstrated is that alpha-equivalent terms may not appear to be the same. In practice, compilers can re-use variable names for compiler-introduced variables, so detecting alpha-equivalence for the purpose of sharing is not so important.

ters as one pre-condition and merge it with a pre-condition that describes the reserved registers.

type L = fn params:Ts ret:T4 spills:Ts part:Tcap regs:Tpre. āˆ€s1:Ts s2:Ts e1:Tcap e2:Tcap a1:T4 a2:T4 a3:T4. {esp: spills@a3::a2::a ::{eax: ret esp: params@s1@{esp:s2 eax:exn cap:e2}::s ebp: {esp:s2 eax:exn cap:e2}::s ebx:a1 esi:a2 edi:a cap: &[e1,e2]} ::params@s1@{esp:s2 eax:exn cap:e2}::s2} ebp: {esp:s2 eax:exn cap:e2}::s cap: &[part,e1,e2]} & regs

l: L int4::se int top4::int4::top4::se ce {esi:int4}

L is correct, but it is useful only for labels in functions where all three callee- save values are stored on the stack. With a ā€œdon’t optimizeā€ approach, we could make all functions meet this description, but we lose most of the advantages of callee-save registers as a result. A better approach is to provide 2^3 = 8 different abbreviations, one for each combination of callee-save values being stored on the stack. In fact, we need only 4 such abbreviations because our register allocator uses the callee-save registers in a fixed order. Because the compiler provides the abbreviations, this specialization is possible and appropriate. Rather than require the compiler-writer to write and use higher-order ab- breviations, one might hope to write a tool that took a collection of TALx types and re-wrote them in terms of some automatically generated abbrevi- ations. Creating an optimal result appears at least as difficult as finding the shortest simply-typed lambda calculus term equivalent to a given one. We have not investigated using heuristics to discover useful abbreviations.

4.3 Eliding Pre-conditions

Recall that the verifier checks a code block by assuming its pre-condition is true and then processing each instruction in turn, checking it for safety and computing a pre-condition for the remainder of the block. At a control transfer to another block, it suffices to ensure that the current pre-condition implies the pre-condition on the destination label. TALx86 uses a reconstruction approach by allowing many label pre-conditions to be elided. Clearly, the result of eliding a pre-condition is a direct decrease in annotation size. To check a control transfer to a block with an elided pre- condition, the verifier simply uses the current pre-condition at the source of the

transfer to check the target block. Hence, if a block with elided pre-condition has multiple control-flow predecessors, it is verified multiple times under (possibly) different pre-conditions. To ensure that the verifier terminates, we prohibit annotation-free loops in the control-flow graph. For this reason, TALx86 allows a pre-condition to be elided only if the block is only the target of forward jumps. Even with this restriction, the number of times a block is checked is the number of paths through the control-flow graph to the block such that no block on the path has an explicit pre-condition. This number can be exponential in the number of code blocks, so it is unwise to elide explicit pre-conditions indiscriminantly. As the next section demonstrates, an exponential number of paths is rare, but it does occur and it can have a disastrous effect on verification time. The approach our compiler takes is to set an elision threshold, T , and insist that no code block is verified more than T times. Notice T = 1 means all merge points have explicit pre-conditions. We interpret T = 0 to mean that all code labels, even those with a single predecessor, have explicit pre-conditions. For higher values of T , we expect space requirements to decrease, but verification time to increase. Given a value for T , we might like to minimize the number of labels that have explicit pre-conditions. Unfortunately, we have proven that this problem is NP-Complete for T ≄ 3. (We do not know the tractability when T = 2.) Currently, the compiler does a greedy depth-first traversal of the control- flow graph, leaving off pre-conditions until the threshold demands otherwise. In pathological cases, this heuristic can do arbitrarily poorly, but it seems to do well in practice. Using an elision threshold is actually over-constraining the problem — it is more important to minimize the total number of times that we verify blocks. That is, we would prefer to verify some block more than T times in order to verify several other blocks many fewer times. For structured programs (all intra- procedural jumps are for loops and conditionals), it appears that this relaxed problem can be solved in polynomial time (O(n^9 ) where^ n^ is the number of blocks [13]), but the algorithm seems impractical.

4.4 Hash-Consing and Fast Type Operations

So far, we have discussed techniques for reducing the size of the annotations that the code producer writes. For the verifier, these explicit types provide guidance to check that each assembly instruction is safe. To do this checking, the verifier determines the type of the context (i.e., the registers and the stack) before the instruction, the types of the operands, and the type of the context after the instruction. The operands must be subtypes of the types that the instruction requires. In short, the verifier itself creates many type expressions and often checks that one is a subtype of another. Therefore, it is important that these operations consume as little time and space as possible. Our primary technique for reducing space is hash-consing, which is essentially just the on-line form of sharing. As types are created, we first check a table to see if they have been created before. If so, we return a pointer to the table entry;

spilling [3] and conservative coalescing [8]) and the elimination of fully redun- dant null-checks for object dereferences. The entire compiler is roughly 18, lines of source code and compiles to 816 kilobytes of object code (335 kilobytes after running strip). The sizes we report include the sum across files of all annotations, not just those for code labels. They do not include the separate module-interface files that the TALx86 link-checker uses to ensure type-safe linking. All execution times were measured on a 266MHz Pentium II with 64MB of RAM running Windows NT 4.0. The verifier and assembler are written in Objective Caml [15] and compiled to native code. We first show that naive choices in the annotation language and compiler can produce a system with unacceptable space and/or time overhead. Then we show that our actual implementation avoids these pitfalls. Next we adjust various parameters and disable various techniques to discover the usefulness of individual approaches and how they interact. Finally, we discuss how we could extend our techniques to further lower the TALx86 overhead.

5.1 Two Bad Approaches

A simple encoding of the TALx86 annotations is insufficient. First, consider a system where we do not use the abbreviations developed in Section 4, our type annotations repeat types rather than share them, and we put types on all code labels. Then the total annotation size for our program is over 4.5 megabytes, several times the size of the object code. As for verification time, if we make no attempt to share common subterms created during verification, then it takes 59 seconds to verify all of the files. A second possibility is to remove as many pre-conditions as possible. That is, we put an explicit pre-condition on a code label only if the label is used as a call destination, a backwards-branch destination, or a first-class value. Indeed, the total size of our annotations drops to 1.85 megabytes. However, the verifier now checks some code blocks a very large number of times. Total verification time rises to 18 minutes and 30 seconds. These two coarse experiments yield some immediate conclusions. First, the actual amount of safety information describing a compiled program is large. Second, the number of loop-free paths through our application code is, in places, much larger than the size of the code. Therefore, it is unwise to make verification time proportional to the number of loop-free paths as the second approach does. The latter conclusion is important for certified-code frameworks that con- struct verification conditions at verification time via a form of weakest pre- condition computation. Essentially, such systems construct pre-conditions for loop-free code segments using a backward flow analysis. In an expressive sys- tem, the pre-condition at a backward merge-point could be the logical disjunc- tion of two conditions. Hence, if done naively, the constructed condition can have exponential size by having a different clause for every loop-free path. When the number of loop-free paths is large, it is clear that constructing an enormous pre-condition is wasteful. For a compiler to exploit the weakness of

such a pre-condition, it would need to have optimized based on an exponential amount of path-sensitive information. We conclude that constructing weakest pre-conditions in this way is impractical. Instead, annotations should guide the construction of the verification condition; the optional code pre-conditions of TALx86 fill this role.

5.2 A Usable System

Having shown how bad matters can get, we now present the actual overhead that our system achieves. First, we identify the main techniques used and the overhead that results. Then we show that verification time is roughly proportional to file size; this fact suggests that our approach should scale to larger applications. Finally, we partition the source code into several styles, show that the overhead is reasonable for all of them, and discuss salient differences. Unlike the ā€œstraw manā€ systems constructed above, the real encoding of TALx86 annotations uses several tables to share common occurrences. Specif- ically, uses of identifiers, types, kinds, and coercions are actually indices into tables that contain the annotations. The code producer can avoid duplicates when constructing the tables. The benefit of this approach is proportional to the amount of repetition; there is a small penalty for annotations that occur only once. We call this technique ā€œsharingā€; more specifically it is full common- subexpression elimination on types at the file level. Sharing is just off-line hash- consing; we use the latter term to refer to sharing within the verifier for types created during verification. Sharing does not create parameterized abbreviations, so we also use the ab- breviations developed in Section 3. The compiler provides the abbreviations and uses them in a text version of TALx86. An independent tool converts the text version into a binary version that has sharing. In this sense, we use abbreviations ā€œbeforeā€ sharing. We set the elision threshold to four. At this value, many forward control-flow points will not need explicit pre-conditions, but no block is verified more than four times. Finally, the verifier uses hash-consing to share types that are created during verification. That is, when creating a new type, the verifier consults a table to see if it has encountered the type previously. If so, it uses the type in the ta- ble. Because the entire sharing table is parsed prior to verification, any types in the table will be used rather than repeated. Reductions on higher-order type constructors are performed in a lazy manner. In particular, we use a weak-head normalization strategy with memoization to avoid both unnecessary reductions and duplicated reductions. As such, other uses of the type will not have to recom- pute the reduction. Shao and associates use a similar strategy [26]. Because of complications with the scope of abbreviations, the hash-consing table is emptied before verifying each file. If memory becomes scarce, we could empty the table at any point, but this measure has not been necessary in practice. Note that the use of hash-consing cannot affect the size of explicit annotations; hash-consing attempts to share types created during verification.