source: Papers/itp-2013/ccexec2.tex @ 3366

Last change on this file since 3366 was 3366, checked in by tranquil, 6 years ago

...

File size: 128.5 KB
Line 
1\documentclass[bookmarksdepth=2,bookmarksopen,envcountsame]{llncs}
2\usepackage{hyperref}
3\usepackage{graphicx}
4\usepackage{color}
5\usepackage{listings}
6\usepackage{bcprules}%\bcprulessavespace
7\usepackage{verbatim}
8\usepackage{alltt}
9\usepackage{subcaption}
10\usepackage{listings}
11\usepackage{amssymb,amsmath}
12% \usepackage{amsmath}
13\usepackage{multicol}
14
15\providecommand{\eqref}[1]{(\ref{#1})}
16
17% NB: might be worth removing this if changing class in favour of
18% a built-in definition.
19%\newtheorem{theorem}{Theorem}
20% \usepackage{aliascnt} %% this will make autoref give correct names
21% \def\mynewtheorem#1[#2]#3{%
22%   \newaliascnt{#1}{#2}%
23%   \newtheorem{#1}[#1]{#3}%
24%   \aliascntresetthe{#1}%
25%   \expandafter\def\csname #1autorefname\endcsname{#3}%
26% }
27% \let\proof\relax
28% \let\endproof\relax
29% \usepackage{amsthm}
30% theorem environments
31% \theoremstyle{definition}
32\spnewtheorem{condition}[theorem]{Condition}{\bfseries}{}
33
34\lstdefinelanguage{coq}
35  {keywords={Definition,Lemma,Theorem,Remark,Qed,Save,Inductive,Record},
36   morekeywords={[2]if,then,else,forall,Prop,match,with,end,let},
37  }
38
39\lstdefinelanguage[mine]{C}[ANSI]{C}{
40  morekeywords={int8_t},
41  mathescape,
42  escapechar=\%
43}
44
45\newcommand\LSTfont{\tt\fontsize{8}{8.2}\selectfont}
46
47\lstset{language=[mine]C,basicstyle=\LSTfont,breaklines=false,
48%         keywordstyle=\color{red}\bfseries,
49%         keywordstyle=[2]\color{blue},
50%         commentstyle=\color{green},
51%         stringstyle=\color{blue},
52        showspaces=false,showstringspaces=false,
53%         xleftmargin=1em
54        }
55
56\usepackage{tikz}
57\usetikzlibrary{positioning,calc,patterns,chains,shapes.geometric,scopes}
58\makeatletter
59\pgfutil@ifundefined{pgf@arrow@code@implies}{% supply for lack of double arrow special arrow tip if it is not there%
60  \pgfarrowsdeclare{implies}{implies}%
61  {%
62  \pgfarrowsleftextend{2.2pt}%
63  \pgfarrowsrightextend{2.2pt}%
64  }%
65  {%
66    \pgfsetdash{}{0pt} % do not dash%
67    \pgfsetlinewidth{.33pt}%
68    \pgfsetroundjoin   % fix join%
69    \pgfsetroundcap    % fix cap%
70    \pgfpathmoveto{\pgfpoint{-1.5pt}{2.5pt}}%
71    \pgfpathcurveto{\pgfpoint{-.75pt}{1.5pt}}{\pgfpoint{0.5pt}{.5pt}}{\pgfpoint{2pt}{0pt}}%
72    \pgfpathcurveto{\pgfpoint{0.5pt}{-.5pt}}{\pgfpoint{-.75pt}{-1.5pt}}{\pgfpoint{-1.5pt}{-2.5pt}}%
73    \pgfusepathqstroke%
74  }%
75}{}%
76\makeatother
77
78\tikzset{state/.style={inner sep = 0, outer sep = 2pt, draw, fill},
79         every node/.style={inner sep=2pt},
80         every on chain/.style = {inner sep = 0, outer sep = 2pt},
81         join all/.style = {every on chain/.append style={join}},
82         on/.style={on chain={#1}, state},
83         m/.style={execute at begin node=$, execute at end node=$},
84         node distance=3mm,
85         is other/.style={circle, minimum size = 3pt, state},
86         other/.style={on, is other},
87         is jump/.style={diamond, minimum size = 6pt, state},
88         jump/.style={on, is jump},
89         is call/.style={regular polygon, regular polygon sides=3, minimum size=5pt, state},
90         call/.style={on=going below, is call, node distance=6mm, label=above left:$#1$},
91         is ret/.style={regular polygon, regular polygon sides=3, minimum size=5pt, shape border rotate=180, state},
92         ret/.style={on=going above, is ret, node distance=6mm},
93         chain/.style={start chain=#1 going left},
94         rev ar/.style={stealth-, thick},
95         ar/.style={-stealth, thick},
96         every join/.style={rev ar},
97         vcenter/.style={baseline={([yshift=-.5ex]current bounding box)}},
98         every picture/.style={thick},
99         double equal sign distance/.prefix style={double distance=1.5pt}, %% if already defined (newest version of pgf) it should be ignored%}
100         implies/.style={double, -implies, thin, double equal sign distance, shorten <=5pt, shorten >=5pt},
101         new/.style={densely dashed},
102         newn/.style={solid, fill=white},
103         rel/.style={font=\scriptsize, fill=white, inner sep=2pt},
104         diag/.style={row sep={11mm,between origins},
105                      column sep={11mm,between origins},
106                      every node/.style={execute at begin node=$, execute at end node=$},
107%                       every node/.style={draw, is other},
108                      },
109         small vgap/.style={row sep={7mm,between origins}},
110         small hgap/.style={column sep={7mm,between origins}},
111         small gap/.style={small vgap, small hgap},
112         % for article, maybe temporary
113         is jump/.style=is other,
114         is call/.style=is other,
115         is ret/.style=is other,
116}
117
118\def\L{\mathrel{\mathcal L}}
119\def\S{\mathrel{\mathcal S}}
120\def\R{\mathrel{\mathcal R}}
121\def\C{\mathrel{\mathcal C}}
122\def\LS{\mathrel{\mathcal{L_S}}}
123
124\def\Labels{\mathbb L}
125\def\Functions{\mathbb F}
126
127\newsavebox{\execbox}
128\savebox{\execbox}{\tikz[baseline=-.5ex]\draw [-stealth] (0,0) -- ++(1em, 0);}
129% \newcommand{\exec}{\ensuremath{\mathrel{\usebox{\execbox}}}}
130\newcommand{\exec}{\to}
131\let\ar\triangleright
132\renewcommand{\verb}{\lstinline[mathescape,basicstyle=\tt\selectfont,
133                                identifierstyle=\texttt]}
134
135\let\class\colon
136\let\andalso\quad
137
138\newcommand{\append}{\mathbin{@}}
139\newcommand{\iffdef}{\mathrel{:\Leftrightarrow}}
140\newcommand{\Deltacost}{\Delta\verb+cost+}
141
142\let\oldto\to
143\makeatletter
144\def\to{\@ifnextchar[{\new@to}{\oldto}}
145\def\new@to[#1]{\xrightarrow{#1}}
146% \def\st@ck#1[#2]{\stackrel{#2}{#1}}
147% \def\defst@ck#1#2{\def#1{\@ifnextchar[{\st@ck#2}{#2}}}
148\let\To\implies
149% \let\MeasTo\rightsquigarrow
150\makeatother
151
152
153\begin{document}
154\pagestyle{plain}
155
156\title{Certification of the Preservation of Structure by a Compiler's Back-end Pass\thanks{The project CerCo acknowledges the financial support of the Future and
157Emerging Technologies (FET) programme within the Seventh Framework
158Programme for Research of the European Commission, under FET-Open grant
159number: 243881}}
160\author{Paolo Tranquilli \and Claudio Sacerdoti Coen}
161\institute{Department of Computer Science and Engineering, University of Bologna,\\\email{Paolo.Tranquilli@unibo.it}, \email{Claudio.SacerdotiCoen@unibo.it}}
162\maketitle
163\begin{abstract}
164The labelling approach is a technique to lift cost models for non-functional
165properties of programs from the object code to the source code. It is based
166on the preservation of the structure of the high level program in every
167intermediate language used by the compiler. Such structure is captured by
168observables that are added to the semantics and that needs to be preserved
169by the forward simulation proof of correctness of the compiler. Additional
170special observables are required for function calls. In this paper we
171present a generic forward simulation proof that preserves all these observables.
172The proof statement is based on a new mechanised semantics that traces the
173structure of execution when the language is unstructured. The generic semantics
174and simulation proof have been mechanised in the interactive theorem prover
175Matita.
176\end{abstract}
177
178\section{Introduction}
179The \emph{labelling approach} has been introduced in~\cite{easylabelling} as
180a technique to \emph{lift} cost models for non-functional properties of programs
181from the object code to the source code. Examples of non-functional properties
182are execution time, amount of stack/heap space consumed and energy required for
183communication. The basic premise of the approach is that it is impossible to
184provide a \emph{uniform} cost model for an high level language that is preserved
185\emph{precisely} by a compiler. For instance, two instances of an assignment
186$x = y$ in the source code can be compiled very differently according to the
187place (registers vs stack) where $x$ and $y$ are stored at the moment of
188execution. Therefore a precise cost model must assign a different cost
189to every occurrence, and the exact cost can only be known after compilation.
190
191According to the labelling approach, the compiler is free to compile and optimise
192the source code without any major restriction, but it must keep trace
193of what happens to basic blocks during the compilation. The cost model is
194then computed on the object code. It assigns a cost to every basic block.
195Finally, the compiler propagates back the cost model to the source level,
196assigning a cost to each basic block of the source code.
197
198Implementing the labelling approach in a certified compiler
199allows to reason formally on the high level source code of a program to prove
200non-functional properties that are granted to be preserved by the compiler
201itself. The trusted code base is then reduced to 1) the interactive theorem
202prover (or its kernel) used in the certification of the compiler and
2032) the software used to certify the property on the source language, that
204can be itself certified further reducing the trusted code base.
205In~\cite{easylabelling} the authors provide an example of a simple
206certified compiler that implements the labelling approach for the
207imperative \verb+While+ language~\cite{while}, that does not have
208pointers and function calls.
209
210The labelling approach has been shown to scale to more interesting scenarios.
211In particular in~\cite{functionallabelling} it has been applied to a functional
212language and in~\cite{loopoptimizations} it has been shown that the approach
213can be slightly complicated to handle loop optimisations and, more generally,
214program optimisations that do not preserve the structure of basic blocks.
215On-going work also shows that the labelling approach is also compatible with
216the complex analyses required to obtain a cost model for object code
217on processors that implement advanced features like pipelining, superscalar
218architectures and caches.
219
220In the European Project CerCo (Certified Complexity\footnote{\url{http://cerco.cs.unibo.it}})~\cite{cerco} we are certifying a labelling approach based compiler for a large subset of C to
2218051 object code. The compiler is
222moderately optimising and implements a compilation chain that is largely
223inspired to that of CompCert~\cite{compcert1,compcert2}. Compared to work done in~\cite{easylabelling}, the main novelty and source of difficulties is due to the presence
224of function calls. Surprisingly, the addition of function calls require a
225revisitation of the proof technique given in~\cite{easylabelling}. In
226particular, at the core of the labelling approach there is a forward
227simulation proof that, in the case of \verb+While+, is only minimally
228more complex than the proof required for the preservation of the
229functional properties only. In the case of a programming language with
230function calls, instead, it turns out that the forward simulation proof for
231the back-end languages, which are unstructured, must grant a whole new set of invariants.
232
233In this paper we present a formalisation in the Matita interactive theorem
234prover~\cite{matita1,matita2} of a generic version of the simulation proof required for unstructured
235languages. All back-end languages of the CerCo compiler are unstructured
236languages, so the proof covers half of the correctness of the compiler.
237The statement of the generic proof is based on a new semantics
238for imperative unstructured languages that is based on \emph{structured
239traces} and that restores the preservation of structure in the observables of
240the semantics. The generic proof allows to almost completely split the
241part of the simulation that deals with functional properties only from the
242part that deals with the preservation of structure.
243
244The plan of this paper is the following. In Section~\ref{sec:labelling} we
245sketch the labelling method and the problems derived from the application
246to languages with function calls. In Section~\ref{sec:semantics} we introduce
247a generic description of an unstructured imperative language and the
248corresponding structured traces (the novel semantics). In
249Section~\ref{sec:simulation} we describe the forward simulation proof.
250Conclusions and future works are in Section~\ref{sec:conclusions}
251
252\section{The labelling approach}
253\label{sec:labelling}
254% \subsection{A brief introduction to the labelling approach}
255We briefly explain the labelling approach as introduced in~\cite{easylabelling}
256on the example in \autoref{examplewhile}.
257The user wants to analyse the execution time of the program (the black lines in
258\autoref{subfig:example_input}). He compiles the program using
259a special compiler that first inserts in the code three label emission
260statements (\verb+EMIT $L_i$+) to mark the beginning of basic blocks
261(\autoref{subfig:example_input});
262then the compiler compiles the code to machine code (\autoref{subfig:example_oc}),
263granting that the execution of the source and object
264code emits the same sequence of labels ($L_1; L_2; L_2; L_3$ in the example).
265This is achieved by keeping track of basic blocks during compilation, avoiding
266all optimizations that alter the control flow. The latter can be recovered with
267a more refined version of the labelling approach~\cite{loopoptimizations}, but in the
268present paper we stick to this simple variant for simplicity. Once the object
269code is produced, the compiler runs a static code analyzer to associate to
270each label $L_1, \ldots, L_3$ the cost (in clock cycles) of the instructions
271that belong to the corresponding basic block. For example, the cost $k_1$
272associated to $L_1$ is the number of cycles required to execute the block
273$I_3$ and \verb+COND $l_2$+, while the cost $k_2$ associated to $L_2$ counts the
274cycles required by the block $I_4$, \verb+GOTO $l_1$+ and \verb+COND $l_2$+. The compiler also guarantees
275that every executed instruction is in the scope of some code emission label,
276that each scope does not contain loops (to associate a finite cost), and that
277both branches of a conditional statement are followed by a code emission
278statement. Under these assumptions it is true that the total execution cost
279of the program $\Delta_t$ is equal to the sum over the sequence of emitted
280labels of the cost associated to every label:
281$\Delta_t = k(L_1; L_2; L_2; L_3) = k_1 + k_2 + k_2 + k_3$.
282Finally, the compiler emits an instrumented version of the source code
283(\autoref{subfig:example_instrument}) where label emission statements are replaced
284by increments of a global variable \verb+cost+ that, before every increment, holds the
285exact number of clock cycles spent by the microprocessor so far:
286the difference $\Deltacost$ between the final and initial value of the
287internal clock is $\Deltacost = k_1 + k_2 + k_2 + k_3 = \Delta_t$. Finally, the
288user can employ any available method (e.g. Hoare logic, invariant generators,
289abstract interpretation and automated provers) to certify that $\Deltacost$
290never exceeds a certain bound~\cite{cerco}, which is now a functional property
291of the code.
292
293\vspace{-0.5cm}
294\begin{figure}[!h]
295\begin{subfigure}[t]{.32\linewidth}
296\begin{lstlisting}[moredelim={[is][\color{red}]{|}{|}}]
297|EMIT $L_1$;|
298$I_1$;
299for (i=0; i<2; i++) {
300  |EMIT $L_2$;|
301  $I_2$;
302}
303|EMIT $L_3$;|
304\end{lstlisting}
305\caption{The input program (black lines) with its labelling (red lines).}
306\label{subfig:example_input}
307\end{subfigure}
308\hfill
309\begin{subfigure}[t]{.23\linewidth}
310\begin{lstlisting}
311   EMIT $L_1$
312   $I_3$
313$l_1$:$\!$  COND $l_2$
314   EMIT $L_2$
315   $I_4$
316   GOTO $l_1$
317$l_2$:$\!$  EMIT $L_3$
318\end{lstlisting}
319\caption{The output labelled object code.}
320\label{subfig:example_oc}
321\end{subfigure}
322\hfill
323\begin{subfigure}[t]{.32\linewidth}
324\begin{lstlisting}
325cost += $k_1$;
326$I_1$;
327for (i=0; i<2; i++) {
328  cost += $k_2$;
329  $I_2$;
330}
331cost += $k_3$;           
332\end{lstlisting}
333\caption{The output instrumented code.}
334\label{subfig:example_instrument}
335\end{subfigure}
336% \begin{verbatim}
337% EMIT L_1;                         EMIT L_1         cost += k_1;
338% I_1;                              I_3              I_1;
339% for (i=0; i<2; i++) {        l_1: COND l_2         for (i=0; i<2; i++) {
340%   EMIT L_2;                       EMIT L_2           cost += k_2;           
341%   I_2;                            I_4                I_2;               
342%  }                                GOTO l_1          }                   
343% EMIT L_3;                    l_2: EMIT L_3         cost += k_3;           
344% \end{verbatim}
345\caption{The labelling approach applied to a simple program.\label{examplewhile}. The $I_i$ are sequences of instructions not containing jumps or loops. }
346\end{figure}
347
348\section{Extending the labelling approach to function calls}
349%
350Let's now consider a simple program written in C that contains a function
351pointer call inside the scope of the cost label $L_1$, in \autoref{subfig:call_input}.
352The labelling method works exactly as before, inserting
353code emission statements/\verb+cost+ variable increments at the beginning
354of every basic block and at the beginning of every function. The compiler
355still grants that the sequence of labels observed on the two programs are
356the same. A new difficulty appears when the compiler needs to statically
357analyze the object code to assign a cost to every label. What should the scope
358of the $L_1$ label be? After executing the $I_4$ block, the \verb+CALL+
359statement passes control to a function that cannot be determined statically.
360Therefore the cost of executing the body must be paid by some other label
361(hence the requirement that every function starts with a code emission
362statement). What label should pay for the cost for the block $I_5$? The only
363reasonable answer is $L_1$, i.e. \emph{the scope of labels should extend to the
364next label emission statement or the end of the function, stepping over function calls}.
365%
366\begin{figure}
367{}\hfill
368\begin{subfigure}[t]{.45\linewidth}
369\centering
370\begin{lstlisting}[xleftmargin=20pt]
371void main() {
372  EMIT $L_1$;
373  $I_1$;
374  (*f)();
375  $I_2$;
376}
377
378void g() {
379  EMIT $L_2$;
380  $I_3$;
381}
382\end{lstlisting}
383\caption{The input labelled C program.}
384\label{subfig:call_input}
385\end{subfigure}
386\hfill
387\begin{subfigure}[t]{.45\linewidth}
388\centering
389\begin{lstlisting}[xleftmargin=20pt]
390main:
391  EMIT $L_1$
392  $I_4$
393  CALL
394  $I_5$
395  RETURN
396
397g:
398  EMIT $L_2$
399  $I_6$
400  RETURN
401\end{lstlisting}
402\caption{The output labelled object code.}
403\label{subfig:call_output}
404\end{subfigure}
405\hfill{}
406\caption{An example compilation of a simple program with a function pointer
407         call.}
408\label{subfig:call_example}
409\end{figure}
410
411The latter definition of scope is adeguate on the source level because
412C is a structured language that guarantees that every function call, if it
413returns, passes control to the first instruction that follows the call. However,
414this is not guaranteed for object code, the backend languages of a compiler
415and, more generally, for unstructured
416languages that use a writable control stack to store the return address of
417calls. For example, $I_6$ could increment by $1$ the return address on the
418stack so that the next \verb+RETURN+ would start at the second instruction
419of $I_5$. The compiler would still be perfectly correct if a random, dead
420code instruction was added after the \verb+CALL+ as the first instruction of $I_5$. More generally,
421\emph{there is no guarantee that a correct compiler that respects the functional
422behaviour of a program also respects the calling structure of the source code}.
423Without such an assumption, however, it may not be true that the execution cost
424of the program is the sum of the costs associated to the labels emitted. In our
425example, the cost of $I_5$ is paid by $L_1$, but in place of $I_5$ the processor could execute any other code after $g$ returns.
426
427Obviously, any reasonably written compiler produces object code that behaves
428as if the language was structured (i.e. by properly nesting function
429calls/returns and without tampering with the return addresses on the control
430stack). This property, however, is a property of the runs of object code
431programs, and not a property of the object code that can be easily statically
432verified (as the ones required in \autoref{sec:labelling} in absence of function calls).
433Therefore, we now need to single out those runs whose cost behaviour can be
434statically predicted, and we need to prove that every run of programs generated
435by our compiler are of that type. We call them \emph{structured} since their
436main property is to respect properties that hold for free on the source code
437because of structure. Moreover, in order to avoid proving
438too many preservation properties of our compiler, we drop the original
439requirements on the object code (all instructons must be in scope of some labels,
440no loops inside a scope, etc.) in favour of the corresponding requirement
441for structured runs (a structured run must start with a label emission, no
442instruction can be executed twice between two emissions, etc.).
443
444We will therefore proceed as follows. In the following section
4451) we formally introduce the notion of
446structured trace, which captures structured runs in the style of labelled
447transition systems; 2) we show that on the object code we can correctly
448compute the execution time of a structured run from the sequence of labels
449observed; 3) we show that on the source code we can correctly compute the
450execution time of a program if the compiler produces object code whose
451runs are weakly similar to the source code runs and structured.
452
453The proof of correctness of such a compiler is harder than a traditional
454proof of preservation of functional properties, and a standard forward
455simulation argument does not work. In \autoref{sec:simulation} we present
456a refinement of forward simulation that grants all required correctness
457properties.
458
459All the definitions and theorems presented in the paper have been formalized
460in the interactive theorem prover Matita and are being used to certify
461the complexity preserving compiler developed in the CerCo project~\cite{cerco}.
462The formalization can be
463found at~\ref{YYY} and it heavily relies on algebraic and dependent types for
464both structured traces and the definition of weak similarity. In the paper
465we did not try to stay close to the formalization. On the contrary,
466the definitions given in the paper are the result of a significant
467simplification effort for
468the sake of presentation and to make easier the re-implementation of the
469concepts in a proof assistant which is not based on the Calculus of Inductive
470Constructions. In any case the formalization is heavily commented to allow the
471reader to understand the technical details of the formalization.
472
473
474% @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
475%
476% We briefly sketch here a simplified version of the labelling approach as
477% introduced in~\cite{easylabelling}. The simplification strengthens the
478% sufficient conditions given in~\cite{easylabelling} to allow a simpler
479% explanation. The simplified conditions given here are also used in the
480% CerCo compiler to simplify the proof.
481%
482% Let $\mathcal{P}$ be a programming language whose semantics is given in
483% terms of observables: a run of a program yields a finite or infinite
484% stream of observables. We also assume for the time being that function
485% calls are not available in $\mathcal{P}$. We want to associate a cost
486% model to a program $P$ written in $\mathcal{P}$. The first step is to
487% extend the syntax of $\mathcal{P}$ with a new construct $\verb+emit L+$
488% where $L$ is a label distinct from all observables of $\mathcal{P}$.
489% The semantics of $\verb+emit L+$ is the emission of the observable
490% \verb+L+ that is meant to signal the beginning of a basic block.
491%
492% There exists an automatic procedure that injects into the program $P$ an
493% $\verb+emit L+$ at the beginning of each basic block, using a fresh
494% \verb+L+ for each block. In particular, the bodies of loops, both branches
495% of \verb+if-then-else+s and the targets of \verb+goto+s must all start
496% with an emission statement.
497%
498% Let now $C$ be a compiler from $\mathcal{P}$ to the object code $\mathcal{M}$,
499% that is organised in passes. Let $\mathcal{Q}_i$ be the $i$-th intermediate
500% language used by the compiler. We can easily extend every
501% intermediate language (and its semantics) with an $\verb+emit L+$ statement
502% as we did for $\mathcal{P}$. The same is possible for $\mathcal{M}$ too, with
503% the additional difficulty that the syntax of object code is given as a
504% sequence of bytes. The injection of an emission statement in the object code
505% can be done using a map that maps two consecutive code addresses with the
506% statement. The intended semantics is that, if $(pc_1,pc_2) \mapsto \verb+emit L+$ then the observable \verb+L+ is emitted after the execution of the
507% instruction stored at $pc_1$ and before the execution of the instruction
508% stored at $pc_2$. The two program counters are necessary because the
509% instruction stored at $pc_1$ can have multiple possible successors (e.g.
510% in case of a conditional branch or an indirect call). Dually, the instruction
511% stored at $pc_2$ can have multiple possible predecessors (e.g. if it is the
512% target of a jump).
513%
514% The compiler, to be functionally correct, must preserve the observational
515% equivalence, i.e. executing the program after each compiler pass should
516% yield the same stream of observables. After the injection of emission
517% statements, observables now capture both functional and non-functional
518% behaviours.
519% This correctness property is called in the literature a forward simulation
520% and is sufficient for correctness when the target language is
521% deterministic~\cite{compcert3}.
522% We also require a stronger, non-functional preservation property: after each
523% pass all basic blocks must start with an emission statement, and all labels
524% \verb+L+ must be unique.
525%
526% Now let $M$ be the object code obtained for the program $P$. Let us suppose
527% that we can statically inspect the code $M$ and associate to each basic block
528% a cost (e.g. the number of clock cycles required to execute all instructions
529% in the basic block, or an upper bound to that time). Every basic block is
530% labelled with an unique label \verb+L+, thus we can actually associate the
531% cost to \verb+L+. Let call it $k(\verb+L+)$.
532%
533% The function $k$ is defined as the cost model for the object code control
534% blocks. It can be equally used as well as the cost model for the source
535% control blocks. Indeed, if the semantics of $P$ is the stream
536% $L_1 L_2 \ldots$, then, because of forward simulation, the semantics of $M$ is
537% also $L_1 L_2 \ldots$ and its actual execution cost is $\Sigma_i k(L_i)$ because
538% every instruction belongs to a control block and every control block is
539% labelled. Thus it is correct to say that the execution cost of $P$ is also
540% $\Sigma_i k(L_i)$. In other words, we have obtained a cost model $k$ for
541% the blocks of the high level program $P$ that is preserved by compilation.
542%
543% How can the user profit from the high level cost model? Suppose, for instance,
544% that he wants to prove that the WCET of his program is bounded by $c$. It
545% is sufficient for him to prove that $\Sigma_i k(L_i) \leq c$, which is now
546% a purely functional property of the code. He can therefore use any technique
547% available to certify functional properties of the source code.
548% What is suggested in~\cite{easylabelling} is to actually instrument the
549% source code $P$ by replacing every label emission statement
550% $\verb+emit L+$ with the instruction $\verb+cost += k(L)+$ that increments
551% a global fresh variable \verb+cost+. The bound is now proved by establishing
552% the program invariant $\verb+cost+ \leq c$, which can be done for example
553% using the Frama-C~\cite{framaC} suite if the source code is some variant of
554% C.
555%
556% In order to extend the labelling approach to function calls we make
557% \verb+CALL f+ emit the observable \verb+f+ and \verb+RET+ emit a distinguished observable
558% \verb+ret+.
559%
560% For example the following execution history of the program in \autoref{fig:esempio}
561% $$I_1; \verb+CALL f+; \verb+COND l+; \verb+EMIT $L_2$+; I_3; \verb+RET+; I_2; \verb+RET+$$
562% emits the trace
563% $$\verb+main+, \verb+f+$$
564% \begin{figure}
565% \hfil
566% \begin{minipage}{.2\linewidth}
567% \begin{lstlisting}
568% main: $\!I_1$
569%       CALL f
570%       $I_2$
571%       RET
572% \end{lstlisting}
573% \end{minipage}
574% \begin{minipage}{.1\linewidth}
575% \begin{lstlisting}
576% main
577% main
578% main
579% main
580% \end{lstlisting}
581% \end{minipage}
582% \hfil
583% \begin{minipage}{.2\linewidth}
584% \begin{lstlisting}
585% f: $\!$COND l
586%    EMIT $L_2$
587%    RET
588% l: $\!$EMIT $L_3$
589%    $I_3$
590%    RET
591% \end{lstlisting}
592% \end{minipage}
593% \begin{minipage}{.1\linewidth}
594% \begin{lstlisting}
595% f
596%
597% $L_2$
598%
599% $L_3$
600% $L_3$
601% \end{lstlisting}
602% \end{minipage}
603% \hfil{}
604% \caption{}
605% \label{fig:esempio}
606% \end{figure}
607%
608%
609% \subsection{Labelling function calls}
610% We now want to extend the labelling approach to support function calls.
611% On the high level, \emph{structured} programming language $\mathcal{P}$ there
612% is not much to change.
613% When a function is invoked, the current basic block is temporarily exited
614% and the basic block the function starts with take control. When the function
615% returns, the execution of the original basic block is resumed. Thus the only
616% significant change is that basic blocks can now be nested. Let \verb+E+
617% be the label of the external block and \verb+I+ the label of a nested one.
618% Since the external starts before the internal, the semantics observed will be
619% \verb+E I+ and the cost associated to it on the source language will be
620% $k(\verb+E+) + k(\verb+I+)$, i.e. the cost of executing all instructions
621% in the block \verb+E+ first plus the cost of executing all the instructions in
622% the block \verb+I+. However, we know that some instructions in \verb+E+ are
623% executed after the last instruction in \verb+I+. This is actually irrelevant
624% because we are here assuming that costs are additive, so that we can freely
625% permute them\footnote{The additivity assumption fails on modern processors that have stateful subsystems, like caches and pipelines. The extension of the labelling approach to those systems is therefore non trivial and under development in the CerCo project.}. Note that, in the present discussion, we are assuming that
626% the function call terminates and yields back control to the basic block
627% \verb+E+. If the call diverges, the instrumentation
628% $\verb+cost += k(E)+$ executed at the beginning of \verb+E+ is still valid,
629% but just as an upper bound to the real execution cost: only precision is lost.
630%
631% Let now consider what happens when we move down the compilation chain to an
632% unstructured intermediate or final language. Here unstructured means that
633% the only control operators are conditional and unconditional jumps, function
634% calls and returns. Unlike a structured language, though, there is no guarantee
635% that a function will return control just after the function call point.
636% The semantics of the return statement, indeed, consists in fetching the
637% return address from some internal structure (typically the control stack) and
638% jumping directly to it. The code can freely manipulate the control stack to
639% make the procedure returns to whatever position. Indeed, it is also possible
640% to break the well nesting of function calls/returns.
641%
642% Is it the case that the code produced by a correct compiler must respect the
643% additional property that every function returns just after its function call
644% point? The answer is negative and the property is not implied by forward
645% simulation proofs. For instance, imagine to modify a correct compiler pass
646% by systematically adding one to the return address on the stack and by
647% putting a \verb+NOP+ (or any other instruction that takes one byte) after
648% every function call. The obtained code will be functionally indistinguishable,
649% and the added instructions will all be dead code.
650%
651% This lack of structure in the semantics badly interferes with the labelling
652% approach. The reason is the following: when a basic block labelled with
653% \verb+E+ contains a function call, it no longer makes any sense to associate
654% to a label \verb+E+ the sum of the costs of all the instructions in the block.
655% Indeed, there is no guarantee that the function will return into the block and
656% that the instructions that will be executed after the return will be the ones
657% we are paying for in the cost model.
658%
659% How can we make the labelling approach work in this scenario? We only see two
660% possible ways. The first one consists in injecting an emission statement after
661% every function call: basic blocks no longer contain function calls, but are now
662% terminated by them. This completely solves the problem and allows the compiler
663% to break the structure of function calls/returns at will. However, the
664% technique has several drawbacks. First of all, it greatly augments the number
665% of cost labels that are injected in the source code and that become
666% instrumentation statements. Thus, when reasoning on the source code to prove
667% non-functional properties, the user (or the automation tool) will have to handle
668% larger expressions. Second, the more labels are emitted, the more difficult it
669% becomes to implement powerful optimisations respecting the code structure.
670% Indeed, function calls are usually implemented in such a way that most registers
671% are preserved by the call, so that the static analysis of the block is not
672% interrupted by the call and an optimisation can involve both the code before
673% and after the function call. Third, instrumenting the source code may require
674% unpleasant modification of it. Take, for example, the code
675% \verb+f(g(x));+. We need to inject an emission statement/instrumentation
676% instruction just after the execution of \verb+g+. The only way to do that
677% is to rewrite the code as \verb+y = g(x); emit L; f(y);+ for some fresh
678% variable \verb+y+. It is pretty clear how in certain situations the obtained
679% code would be more obfuscated and then more difficult to manually reason on.
680%
681% For the previous reasons, in this paper and in the CerCo project we adopt a
682% different approach. We do not inject emission statements after every
683% function call. However, we want to propagate a strong additional invariant in
684% the forward simulation proof. The invariant is the propagation of the structure
685%  of the original high level code, even if the target language is unstructured.
686% The structure we want to propagate, that will become more clear in the next
687% section, comprises 1) the property that every function should return just after
688% the function call point, which in turns imply well nesting of function calls;
689% 2) the property that every basic block starts with a code emission statement.
690%
691% In the original labelling approach of~\cite{easylabelling}, the second property
692% was granted syntactically as a property of the generated code.
693% In our revised approach, instead, we will impose the property on the runs:
694% it will be possible to generate code that does not respect the syntactic
695% property, as soon as all possible runs respect it. For instance, dead code will no longer
696% be required to have all basic blocks correctly la. The switch is suggested
697% from the fact that the first of the two properties --- that related to
698% function calls/returns --- can only be defined as property of runs,
699% not of the static code. The switch is
700% beneficial to the proof because the original proof was made of two parts:
701% the forward simulation proof and the proof that the static property was granted.
702% In our revised approach the latter disappears and only the forward simulation
703% is kept.
704%
705% In order to capture the structure semantics so that it is preserved
706% by a forward simulation argument, we need to make the structure observable
707% in the semantics. This is the topic of the next section.
708
709\subsection{Structured traces}
710\label{sec:semantics}
711
712Let's consider a generic unstructured language already equipped with a
713small step structured operational semantics (SOS). We introduce a
714deterministic labelled transition system $(S,\Lambda,\to)$
715that refines the
716SOS by observing function calls/returns and the beginning of basic blocks.
717$S$ is the set of states of the program and
718$\Lambda = \{ \tau, RET \} \cup \Labels \cup \Functions$
719where $\Functions$ is the set of names of functions that can occur in the
720program, $\Labels$ is a set of labels disjoint from $\Functions$
721and $\tau$ and $RET$ do not belong to $\Functions \cup \Labels$. Moreover there
722is an injective function $\ell : \Functions \to \Labels$ that tells the
723starting label of the body of each function, and $\ell(\Functions)\subseteq \Labels$
724denotes the image of this function.
725The transition function is defined as $s_1 \to[o] s_2$ if
726$s_1$ moves to $s_2$ according to the SOS and $o = f \in \Functions$ if
727the function $f$ is called, $o = RET$ if a \verb+RETURN+ is executed,
728$o = L \in \Labels$ if an \verb+EMIT $L$+ is executed to signal the
729beginning of a basic block, and $o = \tau$ in all other cases.
730Because we assume the language to be deterministic, the label emitted can
731actually be computed simply observing $s_1$. Finally, $S$ is also endowed with
732a relation $s\ar s'$ ($s'$ \emph{follows} $s$) that holds when the instruction
733to be executed in $s'$ follows syntactically the one in $s$ in the source program.
734
735In the rest of the paper we write $s_0 \to^{*} s_n$ for the finite execution
736fragment $T = s_0 \to[o_0] s_1 \to[o_1] \ldots \to[o_{n-1}] s_n$
737and, we call \emph{weak trace} of $T$ (denoted as $|T|$) the
738subsequence $o_{i_0} \ldots o_{i_m}$ of $o_0 \ldots o_{n-1}$ obtained dropping
739every internal action $\tau$.
740
741%Let $k$ be a cost model for observables actions that maps elements of
742%$\Lambda \setminus \{\tau\}$ to any commutative cost monoid
743%(e.g. natural numbers). We extend the domain of $k$ to executable fragments
744%by posing $k(T) = \Sigma_{o \in |T|} k(o)$.
745
746\paragraph{Structured execution fragments}
747Among all possible finite execution fragments we want to
748identify the ones that satisfy the requirements we sketched in the previous
749section. We say that an execution fragment
750$s_0 \to^{*} s_n$
751is \emph{structured} (and we denote it as $s_0 \To s_n$) iff the following conditions
752are met.
753\begin{enumerate}
754 \item For every $i$, if $s_i \to[f] s_{i+1}$ then there is a
755   label $L$ and a $k\ge i+2$ such that
756    $s_{i+1} \to[\ell(f)] s_{i+2} \To s_k \to[RET] s_{k+1}$, with
757    $s_i \ar s_{k+1}$.
758   In other words, $s_{i+1}$ must start execution with \verb+EMIT $\ell(f)$+
759   --- so that no instruction falls outside the scope of every label ---
760   and then continue with a structured fragment returning control
761   to the instruction immediately following the call.
762
763   The condition also enforces convergence of every function call, which is
764   necessary to bound the cost of the fragment. Note that
765   non convergent programs may still have structured execution fragments
766   that are worth measuring. For example, we can measure the reaction time
767   of a server implemented as an unbounded loop whose body waits for an
768   input, process it and performs an output before looping: the processing
769   steps form a structured execution fragment.
770 \item The number of $RET$'s in the fragment is equal to the number of
771   calls performed. In combination with the previous condition, this ensures
772   well-backeting of function calls.
773 \item
774   \label{req3}
775   For every $i$ and $f$, if $s_{i+1}\to[\ell(f)]s_{i+2}$ then
776   $s_i\to[f]s_{i+1}$. This is a technical condition needed to ensure that a
777   label associated with a function is only used at the beginning of its
778   body. Its use will become clear in~\autoref{sec:simulation}.
779 \item For every $i$, if the instruction to be executed in $s_i$ is a
780   conditional branch, then there is an $L$ such that $s_{i+1} \to[L] s_{i+2}$ or, equivalently, that $s_{i+1}$ must start execution with an
781   \verb+EMIT $L$+. This captures the requirement that every branch which is
782   live code must start with a label emission. Otherwise, it would be possible
783   to have conditional instructions whose branches are assigned different
784   costs, making impossible to assign a single cost to the label whose scope
785   contains the jump.
786\end{enumerate}
787One might wonder why $f$ and $\ell(f)$, that aways appear in this order, are not
788collapsed into a single observable. This would simplify some aspects of the
789formalisation at the price of others. For example, we should add special
790cases when the fragment starts at the beginning of a function body
791(e.g. the one of \texttt{main}) because in that case nobody would have emitted
792the observable $\ell(f)$. We plan to compare the two approaches in the future.
793
794\paragraph{Measurable execution fragments and their cost prediction.}
795The first main theorem of CerCo deals with the object code.
796It states that the execution cost of
797certain execution fragments, that we call \emph{measurable fragments}, can be
798computed from their weak trace by choosing the cost model $k$ that assigns to
799any label the cost (in clock cycles) of the instructions in its scope, and
800$0$ to function calls and $RET$ observables.
801
802\begin{theorem}
803 \label{thm:static}
804 for all measurable fragment $T = s_0 \to^{*} s_n$,\\
805 $$\Delta_t := \verb+clock+_{s_n} - \verb+clock+_{s_0} = \Sigma_{o \in |T|} k(o)$$
806\end{theorem}
807
808An execution fragment $s_0 \to^{*} s_n$ is
809measurable if it is structured (up to a possible final \texttt{RETURN}) and
810if it does not start or end in the middle of a basic block.
811Ending in the middle of a block would mean that the last label encountered
812would have pre-paid more instructions than the ones executed; starting in the
813middle would mean not paying any instruction up to the first label emission.
814
815Formally, $s_0 \to^{*} s_n$ is measurable iff $o_0 \in \Labels$ (or equivalently
816in $s_0$ the program must emit a label) and either
817$s_0 \To s_{n-1}$ and $s_{n-1}\to[RET]s_n$ or
818$s_0 \To s_n$ and $s_n$ must be a label emission statement.
819
820%\textbf{CSC: PROVA----------------------}
821% The theorem is proved by structural induction over the structured
822% trace, and is based on the invariant that
823% iff the function that computes the cost model has analysed the instruction
824% to be executed at $s_2$ after the one to be executed at $s_1$, and if
825% the structured trace starts with $s_1$, then eventually it will contain also
826% $s_2$. When $s_1$ is not a function call, the result holds trivially because
827% of the $s_1\exec s_2$ condition obtained by inversion on
828% the trace. The only non
829% trivial case is the one of function calls: the cost model computation function
830% does recursion on the first instruction that follows that function call; the
831% \verb+as_after_return+ condition of the \verb+tal_base_call+ and
832% \verb+tal_step_call+ grants exactly that the execution will eventually reach
833% this state.
834
835\paragraph{Weak similarity and cost invariance.}
836Given two deterministic unstructured programming languages with their own
837operational semantics, we say that two execution fragments are
838\emph{weakly trace equivalent} if their weak traces are equal.
839
840A compiler (pass) that preserves the program semantics also preserves weak
841traces and propagates measurability iff for every measurable
842fragment $T_1 = s_1 \to^{*} s_1'$ of the source code, the corresponding
843execution fragment $T_2 = s_2 \to^{*} s_2'$ of the object code is measurable
844and $T_1$ and $T_2$ are weakly trace equivalent. The very intuitive notion of
845``corresponding fragment'' is made clear in the forward simulation proof of
846preservation of the semantics of the program by saying that $s_2$ and $s_1$
847are in a certain relation. Clearly the property holds for a compiler if it
848holds for each compiler pass.
849
850Having proved in~\autoref{thm:static} that the statically computed cost model is
851accurate for the object code, we get as a corollary that it is also accurate
852for the source code if the compiler preserves weak traces and
853propagates measurability. Thus, as prescribed by the CerCo's methodology~\cite{fopara}, it becomes possible to compute cost models
854on the object code, transfer it to the source code and then reason comfortably
855on the source code only.
856
857\begin{theorem}\label{thm:preservation}
858Given a compiler that preserves weak traces and propagates measurability,
859for all measurable execution fragment $T_1 = s_1 \to^{*} s_1'$ of the source
860code such that $T_2 = s_2 \to^{*} s_2'$ is the corresponding fragment of the
861object code,
862
863$$\Delta_t := \verb+clock+_{s_2'} - \verb+clock+_{s_2} = \Sigma_{o \in |T_2|} k(o) = \Sigma_{o \in |T_1|} k(o)$$
864\end{theorem}
865
866\section{Proving the compiler correctness}
867\label{sec:simulation}
868Because of \autoref{thm:preservation}, to certify a compiler for the labelling
869approach we need to both prove that it respects the functional semantics of the
870program, and that it preserves weak traces and propagates measurability.
871We achieve this by independently proving the three properties for each compiler
872pass.
873The first property is standard and can be proved by means of a forward simulation argument (see for example~\cite{compcert3}) that runs like this.
874First a relation between the corresponding
875source and target states is defined. Then a lemma establishes
876a local simulation condition: given two states in relation, if the source
877one performs one step then the target one performs zero or more steps and
878the two resulting states are synchronized again according to the relation.
879No requirements are imposed on the intermediate target states.
880Finally, the lemma is iterated over the execution trace to establish the
881final result.
882
883In principle, preservation of weak traces could be easily shown with the same
884argument (and also at the same time). Surprisingly, propagation of
885measurability cannot. What makes the standard forward
886simulation proof work is the fact that usually a compiler pass performs some
887kind of local or global analysis of the code followed by a compositional, order
888preserving translation of every instruction. In order to produce structured
889traces, however, code emission cannot be fully compositional any longer,
890and requirements need to be enforced on intermediate target states.
891
892For example, consider~requirement \ref{req3} that asks every function body
893to start with a label emission statement. Some compiler passes must
894add preambles to functions, for example to take care of the parameter passing
895convention. In order to not violate the requirement, the preamble must be
896inserted after the label emission. In the forward simulation proof, however,
897function call steps in the source language are simulated by the new function
898call followed by the execution of the preamble, and only at the end of the
899preamble the reached states are again in the expected relation. In the meantime,
900however, the object code has already performed the label emission statement,
901that still needs to be executed in the source code, breaking forward simulation.
902
903Another reason why the standard argument breaks is due to the requirement that
904function calls should yield back control after the calling point. Some passes
905need to translate a function call to a function call followed by some
906instructions (for example to restore caller-saved registers in the pass that
907sets the parameter convenction). In the forward simulation proof, these
908instructions are taken care of when simulating the \texttt{RETURN} step:
909the state just after the return in the source code is matched by the state $s_2$
910after these steps in the object code. However, the aforementioned requirement
911does not involve $s_2$, but the intermediate state reached after the return in the object
912code. Therefore this requirement too
913cannot be enforced with the standard forward simulation argument.
914
915In this section we present now a modified forward simulation argument that
916can be used to prove at once that a compiler preserves the semantics of the
917program, its weak traces and that the compiler propagates measurability.
918
919% @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
920%
921% The program semantics adopted in the traditional labelling approach is based
922% on labelled deductive systems. Given a set of observables $\mathcal{O}$ and
923% a set of states $\S$, the semantics of one deterministic execution
924% step is
925% defined as a function $S \to S \times O^*$ where $O^*$ is a (finite) stream of
926% observables. The semantics is then lifted compositionally to multiple (finite
927% or infinite) execution steps.
928% Finally, the semantics of a a whole program execution is obtained by forgetting
929% about the final state (if any), yielding a function $S \to O^*$ that given an
930% initial status returns the finite or infinite stream of observables in output.
931%
932% We present here a new definition of semantics where the structure of execution,
933% as defined in the previous section, is now observable. The idea is to replace
934% the stream of observables with a structured data type that makes explicit
935% function call and returns and that grants some additional invariants by
936% construction. The data structure, called \emph{structured traces}, is
937% defined inductively for terminating programs and coinductively for diverging
938% ones. In the paper we focus only on the inductive structure, i.e. we assume
939% that all programs that are given a semantics are total. The Matita formalisation
940% also shows the coinductive definitions. The semantics of a program is then
941% defined as a function that maps an initial state into a structured trace.
942%
943% In order to have a definition that works on multiple intermediate languages,
944% we abstract the type of structure traces over an abstract data type of
945% abstract statuses, which we aptly call $\verb+abstract_status+$. The fields
946% of this record are the following.
947% \begin{itemize}
948%  \item \verb+S : Type[0]+, the type of states.
949%  \item \verb+as_execute : S $\to$ S $\to$ Prop+, a binary predicate stating
950%  an execution step. We write $s_1\exec s_2$ for $\verb+as_execute+~s_1~s_2$.
951%  \item \verb+as_classifier : S $\to$ classification+, a function tagging all
952%  states with a class in
953%  $\{\verb+cl_return,cl_jump,cl_call,cl_other+\}$, depending on the instruction
954%  that is about to be executed (we omit tail-calls for simplicity). We will
955%  use $s \class c$ as a shorthand for both $\verb+as_classifier+~s=c$
956%  (if $c$ is a classification) and $\verb+as_classifier+~s\in c$
957%  (if $c$ is a set of classifications).
958%  \item \verb+as_label : S $\to$ option label+, telling whether the
959%  next instruction to be executed in $s$ is a cost emission statement,
960%  and if yes returning the associated cost label. Our shorthand for this function
961%  will be $\ell$, and we will also abuse the notation by using $\ell~s$ as a
962%  predicate stating that $s$ is labelled.
963%  \item \verb+as_call_ident : ($\Sigma$s:S. s $\class$ cl_call) $\to$ label+,
964%  telling the identifier of the function which is being called in a
965%  \verb+cl_call+ state. We will use the shorthand $s\uparrow f$ for
966%  $\verb+as_call_ident+~s = f$.
967%  \item \verb+as_after_return : ($\Sigma$s:S. s $\class$ cl_call) $\to$ S $\to$ Prop+,
968%  which holds on the \verb+cl_call+ state $s_1$ and a state $s_2$ when the
969%  instruction to be executed in $s_2$ follows the function call to be
970%  executed in (the witness of the $\Sigma$-type) $s_1$. We will use the notation
971%  $s_1\ar s_2$ for this relation.
972% \end{itemize}
973%
974% % \begin{alltt}
975% % record abstract_status := \{ S: Type[0];
976% %  as_execute: S \(\to\) S \(\to\) Prop;   as_classifier: S \(\to\) classification;
977% %  as_label: S \(\to\) option label;    as_called: (\(\Sigma\)s:S. c s = cl_call) \(\to\) label;
978% %  as_after_return: (\(\Sigma\)s:S. c s = cl_call) \(\to\) S \(\to\) Prop \}
979% % \end{alltt}
980%
981% The inductive type for structured traces is actually made by three multiple
982% inductive types with the following semantics:
983% \begin{enumerate}
984%  \item $(\verb+trace_label_return+~s_1~s_2)$ (shorthand $\verb+TLR+~s_1~s_2$)
985%    is a trace that begins in
986%    the state $s_1$ (included) and ends just before the state $s_2$ (excluded)
987%    such that the instruction to be executed in $s_1$ is a label emission
988%    statement and the one to be executed in the state before $s_2$ is a return
989%    statement. Thus $s_2$ is the state after the return. The trace
990%    may contain other label emission statements. It captures the structure of
991%    the execution of function bodies: they must start with a cost emission
992%    statement and must end with a return; they are obtained by concatenating
993%    one or more basic blocks, all starting with a label emission
994%    (e.g. in case of loops).
995%  \item $(\verb+trace_any_label+~b~s_1~s_2)$ (shorthand $\verb+TAL+~b~s_1~s_2$)
996%    is a trace that begins in
997%    the state $s_1$ (included) and ends just before the state $s_2$ (excluded)
998%    such that the instruction to be executed in $s_2$/in the state before
999%    $s_2$ is either a label emission statement or
1000%    or a return, according to the boolean $b$. It must not contain
1001%    any label emission statement. It captures the notion of a suffix of a
1002%    basic block.
1003%  \item $(\verb+trace_label_label+~b~s_1~s_2)$ (shorthand $\verb+TLL+~b~s_1~s_2$ is the special case of
1004%    $\verb+TAL+~b~s_1~s_2)$ such that the instruction to be
1005%    executed in $s_1$ is a label emission statement. It captures the notion of
1006%    a basic block.
1007% \end{enumerate}
1008%
1009% \begin{multicols}{3}
1010% \infrule[\verb+tlr_base+]
1011%  {\verb+TLL+~true~s_1~s_2}
1012%  {\verb+TLR+~s_1~s_2}
1013%
1014% \infrule[\verb+tlr_step+]
1015%  {\verb+TLL+~false~s_1~s_2 \andalso
1016%   \verb+TLR+~s_2~s_3
1017%  }
1018%  {\verb+TLR+~s_1~s_3}
1019%
1020% \infrule[\verb+tll_base+]
1021%  {\verb+TAL+~b~s_1~s_2 \andalso
1022%   \ell~s_1
1023%  }
1024%  {\verb+TLL+~b~s_1~s_2}
1025% \end{multicols}
1026%
1027% \infrule[\verb+tal_base_not_return+]
1028%  {s_1\exec s_2 \andalso
1029%   s_1\class\{\verb+cl_jump+, \verb+cl_other+\}\andalso
1030%   \ell~s_2
1031%  }
1032%  {\verb+TAL+~false~s_1~s_2}
1033%
1034% \infrule[\verb+tal_base_return+]
1035%  {s_1\exec s_2 \andalso
1036%   s_1 \class \verb+cl_return+
1037%  }
1038%  {\verb+TAL+~true~s_1~s_2}
1039%
1040% \infrule[\verb+tal_base_call+]
1041%  {s_1\exec s_2 \andalso
1042%   s_1 \class \verb+cl_call+ \andalso
1043%   s_1\ar s_3 \andalso
1044%   \verb+TLR+~s_2~s_3 \andalso
1045%   \ell~s_3
1046%  }
1047%  {\verb+TAL+~false~s_1~s_3}
1048%
1049% \infrule[\verb+tal_step_call+]
1050%  {s_1\exec s_2 \andalso
1051%   s_1 \class \verb+cl_call+ \andalso
1052%   s_1\ar s_3 \andalso
1053%   \verb+TLR+~s_2~s_3 \andalso
1054%   \verb+TAL+~b~s_3~s_4
1055%  }
1056%  {\verb+TAL+~b~s_1~s_4}
1057%
1058% \infrule[\verb+tal_step_default+]
1059%  {s_1\exec s_2 \andalso
1060%   \lnot \ell~s_2 \andalso
1061%   \verb+TAL+~b~s_2~s_3\andalso
1062%   s_1 \class \verb+cl_other+
1063%  }
1064%  {\verb+TAL+~b~s_1~s_3}
1065% \begin{comment}
1066% \begin{verbatim}
1067% inductive trace_label_return (S:abstract_status) : S → S → Type[0] ≝
1068%   | tlr_base:
1069%       ∀status_before: S.
1070%       ∀status_after: S.
1071%         trace_label_label S ends_with_ret status_before status_after →
1072%         trace_label_return S status_before status_after
1073%   | tlr_step:
1074%       ∀status_initial: S.
1075%       ∀status_labelled: S.
1076%       ∀status_final: S.
1077%         trace_label_label S doesnt_end_with_ret status_initial status_labelled →
1078%         trace_label_return S status_labelled status_final →
1079%           trace_label_return S status_initial status_final
1080% with trace_label_label: trace_ends_with_ret → S → S → Type[0] ≝
1081%   | tll_base:
1082%       ∀ends_flag: trace_ends_with_ret.
1083%       ∀start_status: S.
1084%       ∀end_status: S.
1085%         trace_any_label S ends_flag start_status end_status →
1086%         as_costed S start_status →
1087%           trace_label_label S ends_flag start_status end_status
1088% with trace_any_label: trace_ends_with_ret → S → S → Type[0] ≝
1089%   (* Single steps within a function which reach a label.
1090%      Note that this is the only case applicable for a jump. *)
1091%   | tal_base_not_return:
1092%       ∀start_status: S.
1093%       ∀final_status: S.
1094%         as_execute S start_status final_status →
1095%         (as_classifier S start_status cl_jump ∨
1096%          as_classifier S start_status cl_other) →
1097%         as_costed S final_status →
1098%           trace_any_label S doesnt_end_with_ret start_status final_status
1099%   | tal_base_return:
1100%       ∀start_status: S.
1101%       ∀final_status: S.
1102%         as_execute S start_status final_status →
1103%         as_classifier S start_status cl_return →
1104%           trace_any_label S ends_with_ret start_status final_status
1105%   (* A call followed by a label on return. *)
1106%   | tal_base_call:
1107%       ∀status_pre_fun_call: S.
1108%       ∀status_start_fun_call: S.
1109%       ∀status_final: S.
1110%         as_execute S status_pre_fun_call status_start_fun_call →
1111%         ∀H:as_classifier S status_pre_fun_call cl_call.
1112%           as_after_return S «status_pre_fun_call, H» status_final →
1113%           trace_label_return S status_start_fun_call status_final →
1114%           as_costed S status_final →
1115%             trace_any_label S doesnt_end_with_ret status_pre_fun_call status_final
1116%   (* A call followed by a non-empty trace. *)
1117%   | tal_step_call:
1118%       ∀end_flag: trace_ends_with_ret.
1119%       ∀status_pre_fun_call: S.
1120%       ∀status_start_fun_call: S.
1121%       ∀status_after_fun_call: S.
1122%       ∀status_final: S.
1123%         as_execute S status_pre_fun_call status_start_fun_call →
1124%         ∀H:as_classifier S status_pre_fun_call cl_call.
1125%           as_after_return S «status_pre_fun_call, H» status_after_fun_call →
1126%           trace_label_return S status_start_fun_call status_after_fun_call →
1127%           ¬ as_costed S status_after_fun_call →
1128%           trace_any_label S end_flag status_after_fun_call status_final →
1129%             trace_any_label S end_flag status_pre_fun_call status_final
1130%   | tal_step_default:
1131%       ∀end_flag: trace_ends_with_ret.
1132%       ∀status_pre: S.
1133%       ∀status_init: S.
1134%       ∀status_end: S.
1135%         as_execute S status_pre status_init →
1136%         trace_any_label S end_flag status_init status_end →
1137%         as_classifier S status_pre cl_other →
1138%         ¬ (as_costed S status_init) →
1139%           trace_any_label S end_flag status_pre status_end.
1140% \end{verbatim}
1141% \end{comment}
1142% A \verb+trace_label_return+ is isomorphic to a list of
1143% \verb+trace_label_label+s that ends with a cost emission followed by a
1144% return terminated \verb+trace_label_label+.
1145% The interesting cases are those of $\verb+trace_any_label+~b~s_1~s_2$.
1146% A \verb+trace_any_label+ is a sequence of steps built by a syntax directed
1147% definition on the classification of $s_1$. The constructors of the datatype
1148% impose several invariants that are meant to impose a structure to the
1149% otherwise unstructured execution. In particular, the following invariants are
1150% imposed:
1151% \begin{enumerate}
1152%  \item the trace is never empty; it ends with a return iff $b$ is
1153%        true
1154%  \item a jump must always be the last instruction of the trace, and it must
1155%        be followed by a cost emission statement; i.e. the target of a jump
1156%        is always the beginning of a new basic block; as such it must start
1157%        with a cost emission statement
1158%  \item a cost emission statement can never occur inside the trace, only in
1159%        the status immediately after
1160%  \item the trace for a function call step is made of a subtrace for the
1161%        function body of type
1162%        $\verb+trace_label_return+~s_1~s_2$, possibly followed by the
1163%        rest of the trace for this basic block. The subtrace represents the
1164%        function execution. Being an inductive datum, it grants totality of
1165%        the function call. The status $s_2$ is the one that follows the return
1166%        statement. The next instruction of $s_2$ must follow the function call
1167%        instruction. As a consequence, function calls are also well nested.
1168% \end{enumerate}
1169%
1170% There are three mutual structural recursive functions, one for each of
1171% \verb+TLR+, \verb+TLL+ and \verb+TAL+, for which we use the same notation
1172% $|\,.\,|$: the \emph{flattening} of the traces. These functions
1173% allow to extract from a structured trace the list of emitted cost labels.
1174% %  We only show here the type of one
1175% % of them:
1176% % \begin{alltt}
1177% % flatten_trace_label_return:
1178% %  \(\forall\)S: abstract_status. \(\forall\)\(s_1,s_2\).
1179% %   trace_label_return \(s_1\) \(s_2\) \(\to\) list (as_cost_label S)
1180% % \end{alltt}
1181%
1182% \paragraph{Structured traces similarity and cost prediction invariance.}
1183%
1184% A compiler pass maps source to object code and initial states to initial
1185% states. The source code and initial state uniquely determine the structured
1186% trace of a program, if it exists. The structured trace fails to exists iff
1187% the structural conditions are violated by the program execution (e.g. a function
1188% body does not start with a cost emission statement). Let us assume that the
1189% target structured trace exists.
1190%
1191% What is the relation between the source and target structured traces?
1192% In general, the two traces can be arbitrarily different. However, we are
1193% interested only in those compiler passes that maps a trace $\tau_1$ to a trace
1194% $\tau_2$ such that
1195% \begin{equation}|\tau_1| = |\tau_2|.\label{th2}\end{equation}
1196% The reason is that the combination of~\eqref{th1} with~\eqref{th2} yields the
1197% corollary
1198% \begin{equation}\label{th3}
1199% \forall s_1,s_2. \forall \tau: \verb+TLR+~s_1~s_2.~
1200%   \verb+clock+~s_2 - \verb+clock+~s_1 =
1201%   \Sigma_{\alpha \in |\tau_1|}\;k(\alpha) =
1202%   \Sigma_{\alpha \in |\tau_2|}\;k(\alpha).
1203% \end{equation}
1204% This corollary states that the actual execution time of the program can be computed equally well on the source or target language. Thus it becomes possible to
1205% transfer the cost model from the target to the source code and reason on the
1206% source code only.
1207%
1208% We are therefore interested in conditions stronger than~\eqref{th2}.
1209% Therefore we introduce here a similarity relation between traces with
1210% the same structure. Theorem~\verb+tlr_rel_to_traces_same_flatten+
1211% in the Matita formalisation shows that~\eqref{th2} holds for every pair
1212% $(\tau_1,\tau_2)$ of similar traces.
1213%
1214% Intuitively, two traces are similar when one can be obtained from
1215% the other by erasing or inserting silent steps, i.e. states that are
1216% not \verb+as_costed+ and that are classified as \verb+cl_other+.
1217% Silent steps do not alter the structure of the traces.
1218% In particular,
1219% the relation maps function calls to function calls to the same function,
1220% label emission statements to emissions of the same label, concatenation of
1221% subtraces to concatenation of subtraces of the same length and starting with
1222% the same emission statement, etc.
1223%
1224% In the formalisation the three similarity relations --- one for each trace
1225% kind --- are defined by structural recursion on the first trace and pattern
1226% matching over the second. Here we turn
1227% the definition into the inference rules shown in \autoref{fig:txx_rel}
1228% for the sake of readability. We also omit from trace constructors all arguments,
1229% but those that are traces or that
1230% are used in the premises of the rules. By abuse of notation we denote all three
1231% relations by infixing $\approx$.
1232%
1233% \begin{figure}
1234% \begin{multicols}{2}
1235% \infrule
1236%  {tll_1\approx tll_2
1237%  }
1238%  {\verb+tlr_base+~tll_1 \approx \verb+tlr_base+~tll_2}
1239%
1240% \infrule
1241%  {tll_1 \approx tll_2 \andalso
1242%   tlr_1 \approx tlr_2
1243%  }
1244%  {\verb+tlr_step+~tll_1~tlr_1 \approx \verb+tlr_step+~tll_2~tlr_2}
1245% \end{multicols}
1246% \vspace{3ex}
1247% \begin{multicols}{2}
1248% \infrule
1249%  {\ell~s_1 = \ell~s_2 \andalso
1250%   tal_1\approx tal_2
1251%  }
1252%  {\verb+tll_base+~s_1~tal_1 \approx \verb+tll_base+~s_2~tal_2}
1253%
1254% \infrule
1255%  {tal_1\approx tal_2
1256%  }
1257%  {\verb+tal_step_default+~tal_1 \approx tal_2}
1258% \end{multicols}
1259% \vspace{3ex}
1260% \infrule
1261%  {}
1262%  {\verb+tal_base_not_return+\approx taa \append \verb+tal_base_not_return+}
1263% \vspace{1ex}
1264% \infrule
1265%  {}
1266%  {\verb+tal_base_return+\approx taa \append \verb+tal_base_return+}
1267% \vspace{1ex}
1268% \infrule
1269%  {tlr_1\approx tlr_2 \andalso
1270%   s_1 \uparrow f \andalso s_2\uparrow f
1271%  }
1272%  {\verb+tal_base_call+~s_1~tlr_1\approx taa \append \verb+tal_base_call+~s_2~tlr_2}
1273% \vspace{1ex}
1274% \infrule
1275%  {tlr_1\approx tlr_2 \andalso
1276%   s_1 \uparrow f \andalso s_2\uparrow f \andalso
1277%   \verb+tal_collapsable+~tal_2
1278%  }
1279%  {\verb+tal_base_call+~s_1~tlr_1 \approx taa \append \verb+tal_step_call+~s_2~tlr_2~tal_2)}
1280% \vspace{1ex}
1281% \infrule
1282%  {tlr_1\approx tlr_2 \andalso
1283%   s_1 \uparrow f \andalso s_2\uparrow f \andalso
1284%   \verb+tal_collapsable+~tal_1
1285%  }
1286%  {\verb+tal_step_call+~s_1~tlr_1~tal_1 \approx taa \append \verb+tal_base_call+~s_2~tlr_2)}
1287% \vspace{1ex}
1288% \infrule
1289%  {tlr_1 \approx tlr_2 \andalso
1290%   s_1 \uparrow f \andalso s_2\uparrow f\andalso
1291%   tal_1 \approx tal_2 \andalso
1292%  }
1293%  {\verb+tal_step_call+~s_1~tlr_1~tal_1 \approx taa \append \verb+tal_step_call+~s_2~tlr_2~tal_2}
1294% \caption{The inference rule for the relation $\approx$.}
1295% \label{fig:txx_rel}
1296% \end{figure}
1297% %
1298% \begin{comment}
1299% \begin{verbatim}
1300% let rec tlr_rel S1 st1 st1' S2 st2 st2'
1301%   (tlr1 : trace_label_return S1 st1 st1')
1302%   (tlr2 : trace_label_return S2 st2 st2') on tlr1 : Prop ≝
1303% match tlr1 with
1304%   [ tlr_base st1 st1' tll1 ⇒
1305%     match tlr2 with
1306%     [ tlr_base st2 st2' tll2 ⇒ tll_rel … tll1 tll2
1307%     | _ ⇒ False
1308%     ]
1309%   | tlr_step st1 st1' st1'' tll1 tl1 ⇒
1310%     match tlr2 with
1311%     [ tlr_step st2 st2' st2'' tll2 tl2 ⇒
1312%       tll_rel … tll1 tll2 ∧ tlr_rel … tl1 tl2
1313%     | _ ⇒ False
1314%     ]
1315%   ]
1316% and tll_rel S1 fl1 st1 st1' S2 fl2 st2 st2'
1317%  (tll1 : trace_label_label S1 fl1 st1 st1')
1318%  (tll2 : trace_label_label S2 fl2 st2 st2') on tll1 : Prop ≝
1319%   match tll1 with
1320%   [ tll_base fl1 st1 st1' tal1 H ⇒
1321%     match tll2 with
1322%     [ tll_base fl2 st2 st2 tal2 G ⇒
1323%       as_label_safe … («?, H») = as_label_safe … («?, G») ∧
1324%       tal_rel … tal1 tal2
1325%     ]
1326%   ]
1327% and tal_rel S1 fl1 st1 st1' S2 fl2 st2 st2'
1328%  (tal1 : trace_any_label S1 fl1 st1 st1')
1329%  (tal2 : trace_any_label S2 fl2 st2 st2')
1330%    on tal1 : Prop ≝
1331%   match tal1 with
1332%   [ tal_base_not_return st1 st1' _ _ _ ⇒
1333%     fl2 = doesnt_end_with_ret ∧
1334%     ∃st2mid,taa,H,G,K.
1335%     tal2 ≃ taa_append_tal ? st2 ??? taa
1336%       (tal_base_not_return ? st2mid st2' H G K)
1337%   | tal_base_return st1 st1' _ _ ⇒
1338%     fl2 = ends_with_ret ∧
1339%     ∃st2mid,taa,H,G.
1340%     tal2 ≃ taa_append_tal ? st2 ? st2mid st2' taa
1341%       (tal_base_return ? st2mid st2' H G)
1342%   | tal_base_call st1 st1' st1'' _ prf _ tlr1 _ ⇒
1343%     fl2 = doesnt_end_with_ret ∧
1344%     ∃st2mid,G.as_call_ident S2 («st2mid, G») = as_call_ident ? «st1, prf» ∧
1345%     ∃taa : trace_any_any ? st2 st2mid.∃st2mid',H.
1346%     (* we must allow a tal_base_call to be similar to a call followed
1347%       by a collapsable trace (trace_any_any followed by a base_not_return;
1348%       we cannot use trace_any_any as it disallows labels in the end as soon
1349%       as it is non-empty) *)
1350%     (∃K.∃tlr2 : trace_label_return ? st2mid' st2'.∃L.
1351%       tal2 ≃ taa @ (tal_base_call … H G K tlr2 L) ∧ tlr_rel … tlr1 tlr2) ∨
1352%     ∃st2mid'',K.∃tlr2 : trace_label_return ? st2mid' st2mid''.∃L.
1353%     ∃tl2 : trace_any_label … doesnt_end_with_ret st2mid'' st2'.
1354%       tal2 ≃ taa @ (tal_step_call … H G K tlr2 L tl2) ∧
1355%       tlr_rel … tlr1 tlr2 ∧ tal_collapsable … tl2
1356%   | tal_step_call fl1 st1 st1' st1'' st1''' _ prf _ tlr1 _ tl1 ⇒
1357%     ∃st2mid,G.as_call_ident S2 («st2mid, G») = as_call_ident ? «st1, prf» ∧
1358%     ∃taa : trace_any_any ? st2 st2mid.∃st2mid',H.
1359%     (fl2 = doesnt_end_with_ret ∧ ∃K.∃tlr2 : trace_label_return ? st2mid' st2'.∃L.
1360%       tal2 ≃ taa @ tal_base_call … H G K tlr2 L ∧
1361%       tal_collapsable … tl1 ∧ tlr_rel … tlr1 tlr2) ∨
1362%     ∃st2mid'',K.∃tlr2 : trace_label_return ? st2mid' st2mid''.∃L.
1363%     ∃tl2 : trace_any_label ? fl2 st2mid'' st2'.
1364%       tal2 ≃ taa @ (tal_step_call … H G K tlr2 L tl2) ∧
1365%       tal_rel … tl1 tl2 ∧ tlr_rel … tlr1 tlr2
1366%   | tal_step_default fl1 st1 st1' st1'' _ tl1 _ _ ⇒
1367%     tal_rel … tl1 tal2 (* <- this makes it many to many *)
1368%   ].
1369% \end{verbatim}
1370% \end{comment}
1371% %
1372% In the preceding rules, a $taa$ is an inhabitant of the
1373% $\verb+trace_any_any+~s_1~s_2$ (shorthand $\verb+TAA+~s_1~s_2$),
1374% an inductive data type whose definition
1375% is not in the paper for lack of space. It is the type of valid
1376% prefixes (even empty ones) of \verb+TAL+'s that do not contain
1377% any function call. Therefore it
1378% is possible to concatenate (using ``$\append$'') a \verb+TAA+ to the
1379% left of a \verb+TAL+. A \verb+TAA+ captures
1380% a sequence of silent moves.
1381% The \verb+tal_collapsable+ unary predicate over \verb+TAL+'s
1382% holds when the argument does not contain any function call and it ends
1383% with a label (not a return). The intuition is that after a function call we
1384% can still perform a sequence of silent actions while remaining similar.
1385%
1386% As should be expected, even though the rules are asymmetric $\approx$ is in fact
1387% an equivalence relation.
1388%
1389This argument enjoys the following remarkable properties:
1390\begin{enumerate}
1391 \item it is generic enough to accommodate all passes of the CerCo compiler;
1392 \item the requested conditions are
1393       just slightly stricter than the statement of a 1-to-many forward
1394       simulation in the classical case;
1395%        . In particular, they only require
1396%        the construction of very simple forms of structured traces made of
1397%        silent states only.
1398 \item they allow to prove our main result of the paper: the conditions we will
1399 present are sufficient to prove the intensional preservation needed to prove
1400 the compiler correct (\autoref{thm:main}).
1401\end{enumerate}
1402The last point is the important one. First of all it means that we have reduced
1403the complex problem of preserving the structure of fragments to a much simpler one that,
1404moreover, can be solved with slight adaptations of the forward simulation proof
1405that is performed for a compiler that only cares about functional properties.
1406Therefore we have successfully split as much as possible the proof of
1407preservation of functional properties from that of non-functional ones.
1408
1409% @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1410
1411\paragraph{Relation sets.}
1412Let $S_1$ and $S_2$ be two deterministic labelled transition systems as described
1413in \autoref{sec:semantics}. We introduce now the four relations $\mathcal{S,C,R,L}\subseteq S_1\times S_2$
1414between states of the two systems. The first two are abstract and must be instantiated
1415by every pass. The remaining two are derived.
1416
1417The $\S$ relation between states is the classical relation used
1418in forward simulation proofs. It correlates the data of the states
1419(e.g. registers, memory, etc.).
1420
1421The $\C$ relation correlates states that are about to execute calls.
1422It allows to track the position in the target code of every call in the source code.
1423
1424% The $\L$ relation simply says that the two states are both label
1425% emitting states that emit the same label, \emph{i.e.}\ $s_1\L s_2\iffdef \ell~s_1=\ell~s_2$.
1426% It allows to track the position in
1427% the target code of every cost emitting statement in the source code.
1428
1429\begin{definition}[$\R$ and $\LS$]
1430\label{def:R_LS}
1431Two states
1432$s_1$ and $s_2$ are $\R$-related if every time $s_1$ is the
1433successor of a call state $s_1'$ that is $\C$-related to a call state
1434$s_2'$ in the target code, then $s_2$ is the successor of $s_2'$. Formally:
1435$$s_1\R s_2 \iffdef \forall s_1',s_2'.s_1'\C s_2' \to s_1'\ar s_1 \to s_2' \ar s_2.$$
1436
1437We say states in $s_1\in S_1$ and $s_2\in S_2$ are label-related
1438(marked $s_1\LS s_2$) if
1439\begin{itemize}
1440\item they both emit the same label $L$;
1441\item if $L\in \ell(\Functions)$ then
1442there is a state $s_2'$ such that $s_2\to[L]\to[\tau *]s_2'$ with
1443 $s_1\S s_2'$, otherwise if $L\notin\ell(\Functions)$ then $s_1\S s_2$.
1444\end{itemize}
1445\end{definition}
1446We will require all pairs of states that return from related calls to be
1447$\R$-related. This, in combinantion with a dual requirement on function calls,
1448will grant that calls return exactly where they are supposed to be.
1449On the other hand the $\LS$ relation captures the fact that synchronisation on labels can be decoupled from
1450``semantic synchronisation'' (in particular at the start of functions). $s_1\LS s_2$
1451tells that the two state are synchronised as to labels, and $s_2$ will eventually
1452synchronise semantically using only silent execution steps (apart from the very first
1453emit).
1454
1455Given the relations $\S$ and $\C$, \autoref{fig:forwardsim} defines a set of
1456local simulation conditions that are sufficient to grant the correctness of
1457the compiler, as stated by the results that follow.
1458\begin{figure}
1459\centering
1460% \begin{subfigure}{.475\linewidth}
1461% \centering
1462% \begin{tikzpicture}[every join/.style={ar}, join all, thick,
1463%                             every label/.style=overlay, node distance=10mm]
1464%     \matrix [diag] (m) {%
1465%          \node (s1) [is jump] {}; & \node [fill=white] (t1) {};\\
1466%          \node (s2) {}; & \node (t2) {}; \\
1467%     };
1468%     \node [above=0 of t1, overlay] {$\alpha$};
1469%     {[-stealth]
1470%     \draw (s1) -- (t1);
1471%     \draw [new] (s2) -- node [above] {$*$} (t2);
1472%     }
1473%     \draw (s1) to node [rel] {$\S$} (s2);
1474%     \draw [new] (t1) to node [rel] {$\S,\L$} (t2);
1475% \end{tikzpicture}
1476% \caption{The \verb+cl_jump+ case.}
1477% \label{subfig:cl_jump}
1478% \end{subfigure}
1479% &
1480\centering
1481\tikzset{diag/.append style=
1482         {every node/.append style={is other,
1483                                    text height=0,text depth=0,text width=0,
1484                                    text opacity=0}                                                         
1485         },
1486         }
1487\begin{tikzpicture}[baseline={([yshift=-.5ex]s2)}]
1488    \matrix [diag] (m) {%
1489         \node (s1) {s_1}; & \node (t1) {s_1'};\\
1490         \node (s2) {s_2}; & \node [newn] (t2) {s_2'}; \\
1491    };
1492    {[-stealth]
1493    \draw (s1) -- node [above] {$\tau$} (t1);
1494    \draw [new] (s2) -- node [above] {$\tau *$} (t2);
1495    }
1496    \draw (s1) to [bend right, anchor=mid] node [rel] {$\S$} (s2);
1497    \draw [new] (t1) to [bend left, anchor=mid] node [rel] {$\S$} (t2);
1498\end{tikzpicture}
1499\qquad
1500\begin{tikzpicture}[baseline={([yshift=-.5ex]s2)}]
1501    \matrix [diag] (m) {%
1502         \node (s1) {s_1}; & \node (t1) {s_1'};\\
1503         \node (s2) {s_2}; & \node  [newn](mid) {s_a}; & \node [newn] (t2) {s_2'}; \\
1504    };
1505    {[-stealth]
1506    \draw (s1) -- node [above] {$L$} (t1);
1507    \draw [new] (s2) -- node [above] {$L$} (mid);
1508    \draw [new] (mid) -- node [above] {$\tau *$} (t2);
1509    }
1510    \draw (s1) to [bend right, anchor=mid] node [rel] {$\S$} (s2);
1511    \draw [new] (t1) to [bend left, anchor=mid] node [rel] {$\S$} (t2);
1512\end{tikzpicture}
1513\text{ if $L\notin\ell(\Functions)$}
1514\qquad
1515\begin{tikzpicture}[baseline={([yshift=-.5ex]s2)}]
1516    \matrix [diag] (m) {%
1517         \node (s1) {s_1}; & \node (t1) {s_1'};\\
1518         \node (s2) {s_2};\\
1519    };
1520    {[-stealth]
1521    \draw (s1) -- node [above] {$\ell(f)$} (t1);
1522    }
1523    \draw (s1) to [bend right, anchor=mid] node [rel] {$\S$} (s2);
1524    \draw [new] (t1) to [bend left, anchor=mid] node [rel] {$\S$} (s2);
1525\end{tikzpicture}
1526\\[10pt]
1527\begin{tikzpicture}
1528    \matrix [diag, small vgap] (m) {%
1529         &\node (t1) {s_1'}; \\
1530         \node (s1) {s_1}; \\
1531         && \node [newn] (l1) {s_b}; & \node [newn] (l2) {s_c}; & \node [newn] (t2) {s_2'};\\
1532         \node [newn] (s2) {s_2}; & \node [newn] (c) {s_a};\\   
1533    };
1534    {[-stealth]
1535    \draw (s1) -- node [above left] {$f$} (t1);
1536    \draw [new] (s2) -- node [above] {$\tau *$} (c);
1537    \draw [new] (c) -- node [above left] {$f$} (l1);
1538    \draw [new] (l1) -- node [above] {$\ell(f)$} (l2);
1539    \draw [new] (l2) -- node [above] {$\tau *$} (t2);
1540    }
1541    \draw (s1) to [bend right] node [rel] {$\S$} (s2);
1542    \draw [new] (t1) to [bend left] node [rel] {$\S$} (t2);
1543    \draw [new] (s1) to [bend left] node [rel] {$\C$} (c);
1544\end{tikzpicture}
1545\qquad\qquad
1546\begin{tikzpicture}
1547    \matrix [diag, small vgap] (m) {%
1548        \node (s1) {s_1}; \\
1549        &\node (t1) {s_1'}; \\
1550        \node (s2) {s_2}; & \node [newn] (c) {s_a};\\
1551        && \node [newn] (r) {s_b}; & \node [newn] (t2) {s_2'}; \\   
1552    };
1553    {[-stealth]
1554    \draw (s1) -- node [above right] {$RET$} (t1);
1555    \draw [new] (s2) -- node [above] {$\tau *$} (c);
1556    \draw [new] (c) -- node [below left] {$RET$} (r);
1557    \draw [new] (r) -- node [above] {$\tau *$} (t2);
1558    }
1559    \draw (s1) to [bend right] node [rel] {$\S$} (s2);
1560    \draw [new, overlay] (t1) to [bend left=60] node [rel] {$\S$} (t2);
1561    \draw [new, overlay] (t1) to [bend left ] node [rel] {$\R$} (r);
1562\end{tikzpicture}
1563\caption{Local simulation conditions. Each one states that the assumptions
1564         drawn solid imply the existence of the white states and the dashed relations.}
1565\label{fig:forwardsim}
1566\end{figure}
1567%
1568\begin{lemma}[Preservation of structured fragments]
1569If $S_1$, $S_2$, $\S$ and $\C$ satisfy the diagrams in \autoref{fig:forwardsim},
1570$T_1=s_1\To s_1'$ is a structured fragment not starting with a $\ell(f)$ emission,
1571and $s_1\S s_2$, then there is $T_2=s_2\To s_2'$ with $T\approx T'$ and $s_1'\S s_2'$.
1572\end{lemma}
1573\begin{theorem}[Preservation of measurable fragments]
1574\label{thm:main}
1575If $S_1$, $S_2$, $\S$ and $\C$ satisfy the diagrams in \autoref{fig:forwardsim},
1576$M_1 = s_1\to^* s_1'$ is a measurable fragment of $S_1$ and $s_2$ is such that
1577$s_1\LS s_2$, then there is a measurable $M_2 = s_2\to^* s_2'$ with $|M_1|=|M_2|$. Moreover,
1578there is a state $s_2''$ with $s_2'\to[\tau *]s_2''$ and $s_1'\S s_2''$.
1579\end{theorem}
1580In particular, the above theorem
1581applied to the \verb+main+ function of the program together with an assumption
1582stating that initial states are $\LS$-related shows that
1583for each measurable execution of the source code,
1584the compiled code produces a measurable execution with the same observables.
1585Combined with \autoref{thm:static} and by proving the conditions in
1586\autoref{fig:forwardsim} for every pass, the compiler is proved correct.
1587
1588
1589% \begin{figure}
1590% \centering
1591% \begin{tabular}{@{}c@{}c@{}c@{}}
1592% % \begin{subfigure}{.475\linewidth}
1593% % \centering
1594% % \begin{tikzpicture}[every join/.style={ar}, join all, thick,
1595% %                             every label/.style=overlay, node distance=10mm]
1596% %     \matrix [diag] (m) {%
1597% %          \node (s1) [is jump] {}; & \node [fill=white] (t1) {};\\
1598% %          \node (s2) {}; & \node (t2) {}; \\
1599% %     };
1600% %     \node [above=0 of t1, overlay] {$\alpha$};
1601% %     {[-stealth]
1602% %     \draw (s1) -- (t1);
1603% %     \draw [new] (s2) -- node [above] {$*$} (t2);
1604% %     }
1605% %     \draw (s1) to node [rel] {$\S$} (s2);
1606% %     \draw [new] (t1) to node [rel] {$\S,\L$} (t2);
1607% % \end{tikzpicture}
1608% % \caption{The \verb+cl_jump+ case.}
1609% % \label{subfig:cl_jump}
1610% % \end{subfigure}
1611% % &
1612% \begin{subfigure}{.25\linewidth}
1613% \centering
1614% \begin{tikzpicture}[every join/.style={ar}, join all, thick,
1615%                             every label/.style=overlay, node distance=10mm]
1616%     \matrix [diag] (m) {%
1617%          \node (s1) {}; & \node (t1) {};\\
1618%          \node (s2) {}; & \node (t2) {}; \\
1619%     };
1620%     {[-stealth]
1621%     \draw (s1) -- (t1);
1622%     \draw [new] (s2) -- node [above] {$*$} (t2);
1623%     }
1624%     \draw (s1) to [bend right, anchor=mid] node [rel] {$\S$} (s2);
1625%     \draw [new] (t1) to [bend left, anchor=mid] node [rel] {$\S,\L$} (t2);
1626% \end{tikzpicture}
1627% \caption{The \verb+cl_oher+ and \verb+cl_jump+ cases.}
1628% \label{subfig:cl_other_jump}
1629% \end{subfigure}
1630% &
1631% \begin{subfigure}{.375\linewidth}
1632% \centering
1633% \begin{tikzpicture}[every join/.style={ar}, join all, thick,
1634%                             every label/.style=overlay, node distance=10mm]
1635%     \matrix [diag, small gap] (m) {%
1636%          &\node (t1) {}; \\
1637%          \node (s1) [is call] {}; \\
1638%          && \node (l) {}; & \node (t2) {};\\
1639%          \node (s2) {}; & \node (c) [is call] {};\\   
1640%     };
1641%     {[-stealth]
1642%     \draw (s1) -- node [above left] {$f$} (t1);
1643%     \draw [new] (s2) -- node [above] {$*$} (c);
1644%     \draw [new] (c) -- node [below right] {$f$} (l);
1645%     \draw [new] (l) -- node [above] {$*$} (t2);
1646%     }
1647%     \draw (s1) to [bend right] node [rel] {$\S$} (s2);
1648%     \draw [new] (t1) to [bend left] node [rel] {$\S$} (t2);
1649%     \draw [new] (t1) to [bend left] node [rel] {$\L$} (l);
1650%     \draw [new] (t1) to [bend right] node [rel] {$\C$} (c);
1651%     \end{tikzpicture}
1652% \caption{The \verb+cl_call+ case.}
1653% \label{subfig:cl_call}
1654% \end{subfigure}
1655% &
1656% \begin{subfigure}{.375\linewidth}
1657% \centering
1658% \begin{tikzpicture}[every join/.style={ar}, join all, thick,
1659%                             every label/.style=overlay, node distance=10mm]
1660%     \matrix [diag, small gap] (m) {%
1661%         \node (s1) [is ret] {}; \\
1662%         &\node (t1) {}; \\
1663%         \node (s2) {}; & \node (c) [is ret] {};\\
1664%         && \node (r) {}; & \node (t2) {}; \\   
1665%     };
1666%     {[-stealth]
1667%     \draw (s1) -- node [above right] {$RET$} (t1);
1668%     \draw [new] (s2) -- node [above] {$*$} (c);
1669%     \draw [new] (c) -- node [below left] {$RET$} (r);
1670%     \draw [new] (r) -- node [above] {$*$} (t2);
1671%     }
1672%     \draw (s1) to [bend right] node [rel] {$\S$} (s2);
1673%     \draw [new, overlay] (t1) to [bend left=60] node [rel] {$\S,\L$} (t2);
1674%     \draw [new, overlay] (t1) to [bend left ] node [rel] {$\R$} (r);
1675% \end{tikzpicture}
1676% \caption{The \verb+cl_return+ case.}
1677% \label{subfig:cl_return}
1678% \end{subfigure}
1679% \end{tabular}
1680% \caption{Mnemonic diagrams depicting the hypotheses for the preservation of structured traces.
1681%          Dashed lines
1682%          and arrows indicates how the diagrams must be closed when solid relations
1683%          are present.}
1684% \label{fig:forwardsim}
1685% \end{figure}
1686
1687% \paragraph{1-to-many forward simulation conditions.}
1688% \begin{condition}[Cases \verb+cl_other+ and \verb+cl_jump+]
1689%  For all $s_1,s_1',s_2$ such that $s_1 \S s_1'$, and
1690%  $s_1\exec s_1'$, and either $s_1 \class \verb+cl_other+$ or
1691%  both $s_1\class\verb+cl_other+\}$ and $\ell~s_1'$,
1692%  there exists an $s_2'$ and a $\verb+trace_any_any_free+~s_2~s_2'$ called $taaf$
1693%  such that $s_1' \mathrel{{\S} \cap {\L}} s_2'$ and either
1694% $taaf$ is non empty, or one among $s_1$ and $s_1'$ is \verb+as_costed+.
1695% \end{condition}
1696%
1697% In the above condition depicted in \autoref{subfig:cl_other_jump},
1698% a $\verb+trace_any_any_free+~s_1~s_2$ (which from now on
1699% will be shorthanded as \verb+TAAF+) is an
1700% inductive type of structured traces that do not contain function calls or
1701% cost emission statements. Differently from a \verb+TAA+, the
1702% instruction to be executed in the lookahead state $s_2$ may be a cost emission
1703% statement.
1704%
1705% The intuition of the condition is that one step can be replaced with zero or more steps if it
1706% preserves the relation between the data and if the two final statuses are
1707% labelled in the same way. Moreover, we must take special care of the empty case
1708% to avoid collapsing two consecutive states that emit a label, missing one of the two emissions.
1709%
1710% \begin{condition}[Case \verb+cl_call+]
1711%  For all $s_1,s_1',s_2$ s.t. $s_1 \S s_1'$ and
1712%  $s_1\exec s_1'$ and $s_1 \class \verb+cl_call+$, there exists $s_a, s_b, s_2'$, a
1713% $\verb+TAA+~s_2~s_a$, and a
1714% $\verb+TAAF+~s_b~s_2'$ such that:
1715% $s_a\class\verb+cl_call+$, the \verb+as_call_ident+'s of
1716% the two call states are the same, $s_1 \C s_a$,
1717% $s_a\exec s_b$, $s_1' \L s_b$ and
1718% $s_1' \S s_2'$.
1719% \end{condition}
1720%
1721% The condition, depicted in \autoref{subfig:cl_call} says that, to simulate a function call, we can perform a
1722% sequence of silent actions before and after the function call itself.
1723% The old and new call states must be $\C$-related, the old and new
1724% states at the beginning of the function execution must be $\L$-related
1725% and, finally, the two initial and final states must be $\S$-related
1726% as usual.
1727%
1728% \begin{condition}[Case \verb+cl_return+]
1729%  For all $s_1,s_1',s_2$ s.t. $s_1 \S s_1'$,
1730%  $s_1\exec s_1'$ and $s_1 \class \verb+cl_return+$, there exists $s_a, s_b, s_2'$, a
1731% $\verb+TAA+~s_2~s_a$, a
1732% $\verb+TAAF+~s_b~s_2'$ called $taaf$ such that:
1733% $s_a\class\verb+cl_return+$,
1734% $s_a\exec s_b$,
1735% $s_1' \R s_b$ and
1736% $s_1' \mathrel{{\S} \cap {\L}} s_2'$ and either
1737% $taaf$ is non empty, or $\lnot \ell~s_a$.
1738% \end{condition}
1739%
1740% Similarly to the call condition, to simulate a return we can perform a
1741% sequence of silent actions before and after the return statement itself,
1742% as depicted in \autoref{subfig:cl_return}.
1743% The old and the new statements after the return must be $\R$-related,
1744% to grant that they returned to corresponding calls.
1745% The two initial and final states must be $\S$-related
1746% as usual and, moreover, they must exhibit the same labels. Finally, when
1747% the suffix is non empty we must take care of not inserting a new
1748% unmatched cost emission statement just after the return statement.
1749%
1750% \begin{comment}
1751% \begin{verbatim}
1752% definition status_simulation ≝
1753%   λS1 : abstract_status.
1754%   λS2 : abstract_status.
1755%   λsim_status_rel : status_rel S1 S2.
1756%     ∀st1,st1',st2.as_execute S1 st1 st1' →
1757%     sim_status_rel st1 st2 →
1758%     match as_classify … st1 with
1759%     [ None ⇒ True
1760%     | Some cl ⇒
1761%       match cl with
1762%       [ cl_call ⇒ ∀prf.
1763%         (*
1764%              st1' ------------S----------\
1765%               ↑ \                         \
1766%              st1 \--L--\                   \
1767%               | \       \                   \
1768%               S  \-C-\  st2_after_call →taa→ st2'
1769%               |       \     ↑
1770%              st2 →taa→ st2_pre_call
1771%         *)
1772%         ∃st2_pre_call.
1773%         as_call_ident ? st2_pre_call = as_call_ident ? («st1, prf») ∧
1774%         call_rel ?? sim_status_rel «st1, prf» st2_pre_call ∧
1775%         ∃st2_after_call,st2'.
1776%         ∃taa2 : trace_any_any … st2 st2_pre_call.
1777%         ∃taa2' : trace_any_any … st2_after_call st2'.
1778%         as_execute … st2_pre_call st2_after_call ∧
1779%         sim_status_rel st1' st2' ∧
1780%         label_rel … st1' st2_after_call
1781%       | cl_return ⇒
1782%         (*
1783%              st1
1784%             / ↓
1785%            | st1'----------S,L------------\
1786%            S   \                           \
1787%             \   \-----R-------\            |     
1788%              \                 |           |
1789%              st2 →taa→ st2_ret |           |
1790%                           ↓   /            |
1791%                      st2_after_ret →taaf→ st2'
1792%
1793%            we also ask that st2_after_ret be not labelled if the taaf tail is
1794%            not empty
1795%         *)
1796%         ∃st2_ret,st2_after_ret,st2'.
1797%         ∃taa2 : trace_any_any … st2 st2_ret.
1798%         ∃taa2' : trace_any_any_free … st2_after_ret st2'.
1799%         (if taaf_non_empty … taa2' then ¬as_costed … st2_after_ret else True) ∧
1800%         as_classifier … st2_ret cl_return ∧
1801%         as_execute … st2_ret st2_after_ret ∧ sim_status_rel st1' st2' ∧
1802%         ret_rel … sim_status_rel st1' st2_after_ret ∧
1803%         label_rel … st1' st2'
1804%       | cl_other ⇒
1805%           (*         
1806%           st1 → st1'
1807%             |      \
1808%             S      S,L
1809%             |        \
1810%            st2 →taaf→ st2'
1811%           
1812%            the taaf can be empty (e.g. tunneling) but we ask it must not be the
1813%            case when both st1 and st1' are labelled (we would be able to collapse
1814%            labels otherwise)
1815%          *)
1816%         ∃st2'.
1817%         ∃taa2 : trace_any_any_free … st2 st2'.
1818%         (if taaf_non_empty … taa2 then True else (¬as_costed … st1 ∨ ¬as_costed … st1')) ∧
1819%         sim_status_rel st1' st2' ∧
1820%         label_rel … st1' st2'
1821%       | cl_jump ⇒
1822%         (* just like cl_other, but with a hypothesis more *)
1823%         as_costed … st1' →
1824%         ∃st2'.
1825%         ∃taa2 : trace_any_any_free … st2 st2'.
1826%         (if taaf_non_empty … taa2 then True else (¬as_costed … st1 ∨ ¬as_costed … st1')) ∧
1827%         sim_status_rel st1' st2' ∧
1828%         label_rel … st1' st2'
1829%       ]
1830%     ].
1831% \end{verbatim}
1832% \end{comment}
1833
1834% \paragraph{Main result: the 1-to-many forward simulation conditions
1835% are sufficient to trace reconstruction}
1836%
1837% Let us assume that a relation set is given such that the 1-to-many
1838% forward simulation conditions are satisfied. Under this assumption we
1839% can prove the following three trace reconstruction theorems by mutual
1840% structural induction over the traces given in input between the
1841% $s_1$ and $s_1'$ states.
1842%
1843% In particular, the \verb+status_simulation_produce_tlr+ theorem
1844% applied to the \verb+main+ function of the program and equal
1845% $s_{2_b}$ and $s_2$ states shows that, for every initial state in the
1846% source code that induces a structured trace in the source code,
1847% the compiled code produces a similar structured trace.
1848%
1849% \begin{theorem}[\verb+status_simulation_produce_tlr+]
1850% For every $s_1,s_1',s_{2_b},s_2$ s.t.
1851% there is a $\verb+TLR+~s_1~s_1'$ called $tlr_1$ and a
1852% $\verb+TAA+~s_{2_b}~s_2$ and $s_1 \L s_{2_b}$ and
1853% $s_1 \S s_2$, there exists $s_{2_m},s_2'$ s.t.
1854% there is a $\verb+TLR+~s_{2_b}~s_{2_m}$ called $tlr_2$ and
1855% there is a $\verb+TAAF+~s_{2_m}~s_2'$ called $taaf$
1856% s.t. if $taaf$ is non empty then $\lnot (\ell~s_{2_m})$,
1857% and $tlr_1\approx tlr_2$
1858% and $s_1' \mathrel{{\S} \cap {\L}} s_2'$ and
1859% $s_1' \R s_{2_m}$.
1860% \end{theorem}
1861%
1862% The theorem states that a \verb+trace_label_return+ in the source code
1863% together with a precomputed preamble of silent states
1864% (the \verb+TAA+) in the target code induces a
1865% similar \verb+trace_label_return+ in the target code which can be
1866% followed by a sequence of silent states. Note that the statement does not
1867% require the produced \verb+trace_label_return+ to start with the
1868% precomputed preamble, even if this is likely to be the case in concrete
1869% implementations. The preamble in input is necessary for compositionality, e.g.
1870% because the 1-to-many forward simulation conditions allow in the
1871% case of function calls to execute a preamble of silent instructions just after
1872% the function call.
1873%
1874% Clearly similar results are also available for the other two types of structured
1875% traces (in fact, they are all proved simultaneously by mutual induction).
1876% \begin{theorem}[\verb+status_simulation_produce_tll+]
1877% For every $s_1,s_1',s_{2_b},s_2$ s.t.
1878% there is a $\verb+TLL+~b~s_1~s_1'$ called $tll_1$ and a
1879% $\verb+TAA+~s_{2_b}~s_2$ and $s_1 \L s_{2_b}$ and
1880% $s_1 \S s_2$, there exists $s_{2_m},s_2'$ s.t.
1881% \begin{itemize}
1882%  \item if $b$ (the trace ends with a return) then there exists $s_{2_m},s_2'$
1883%        and a trace $\verb+TLL+~b~s_{2_b}~s_{2_m}$ called $tll_2$
1884%        and a $\verb+TAAF+~s_{2_m}~s_2'$ called $taa_2$ s.t.
1885%        $s_1' \mathrel{{\S} \cap {\L}} s_2'$ and
1886%        $s_1' \R s_{2_m}$ and
1887%        $tll_1\approx tll_2$ and
1888%        if $taa_2$ is non empty then $\lnot \ell~s_{2_m}$;
1889%  \item else there exists $s_2'$ and a
1890%        $\verb+TLL+~b~s_{2_b}~s_2'$ called $tll_2$ such that
1891%        $s_1' \mathrel{{\S} \cap {\L}} s_2'$ and
1892%        $tll_1\approx tll_2$.
1893% \end{itemize}
1894% \end{theorem}
1895%
1896% The statement is similar to the previous one: a source
1897% \verb+trace_label_label+ and a given target preamble of silent states
1898% in the target code induce a similar \verb+trace_label_label+ in the
1899% target code, possibly followed by a sequence of silent moves that become the
1900% preamble for the next \verb+trace_label_label+ translation.
1901%
1902% \begin{theorem}[\verb+status_simulation_produce_tal+]
1903% For every $s_1,s_1',s_2$ s.t.
1904% there is a $\verb+TAL+~b~s_1~s_1'$ called $tal_1$ and
1905% $s_1 \S s_2$
1906% \begin{itemize}
1907%  \item if $b$ (the trace ends with a return) then there exists $s_{2_m},s_2'$
1908%    and a trace $\verb+TAL+~b~s_2~s_{2_m}$ called $tal_2$ and a
1909%    $\verb+TAAF+~s_{2_m}~s_2'$ called $taa_2$ s.t.
1910%    $s_1' \mathrel{{\S} \cap {\L}} s_2'$ and
1911%    $s_1' \R s_{2_m}$ and
1912%    $tal_1 \approx tal_2$ and
1913%    if $taa_2$ is non empty then $\lnot \ell~s_{2_m}$;
1914%  \item else there exists $s_2'$ and a
1915%    $\verb+TAL+~b~s_2~s_2'$ called $tal_2$ such that
1916%    either $s_1' \mathrel{{\S} \cap {\L}} s_2'$ and
1917%        $tal_1\approx tal_2$
1918%    or $s_1' \mathrel{{\S} \cap {\L}} s_2$ and
1919%    $\verb+tal_collapsable+~tal_1$ and $\lnot \ell~s_1$.
1920% \end{itemize}
1921% \end{theorem}
1922%
1923% The statement is also similar to the previous ones, but for the lack of
1924% the target code preamble.
1925
1926\begin{comment}
1927\begin{corollary}
1928For every $s_1,s_1',s_2$ s.t.
1929there is a $\verb+trace_label_return+~s_1~s_1'$ called $tlr_1$ and
1930$s_1 (\L \cap \S) s_2$
1931there exists $s_{2_m},s_2'$ s.t.
1932there is a $\verb+trace_label_return+~s_2~s_{2_m}$ called $tlr_2$ and
1933there is a $\verb+trace_any_any_free+~s_{2_m}~s_2'$ called $taaf$
1934s.t. if $taaf$ is non empty then $\lnot (\verb+as_costed+~s_{2_m})$,
1935and $\verb+tlr_rel+~tlr_1~tlr_2$
1936and $s_1' (\S \cap \L) s_2'$ and
1937$s_1' \R s_{2_m}$.
1938\end{corollary}
1939\end{comment}
1940
1941\begin{comment}
1942\begin{verbatim}
1943status_simulation_produce_tlr S1 S2 R
1944(* we start from this situation
1945     st1 →→→→tlr→→→→ st1'
1946      | \
1947      L  \---S--\
1948      |          \
1949   st2_lab →taa→ st2   (the taa preamble is in general either empty or given
1950                        by the preceding call)
1951   
1952   and we produce
1953     st1 →→→→tlr→→→→ st1'
1954             \\      /  \
1955             //     R    \-L,S-\
1956             \\     |           \
1957   st2_lab →tlr→ st2_mid →taaf→ st2'
1958*)
1959  st1 st1' st2_lab st2
1960  (tlr1 : trace_label_return S1 st1 st1')
1961  (taa2_pre : trace_any_any S2 st2_lab st2)
1962  (sim_execute : status_simulation S1 S2 R)
1963  on tlr1 : R st1 st2 → label_rel … st1 st2_lab →
1964  ∃st2_mid.∃st2'.
1965  ∃tlr2 : trace_label_return S2 st2_lab st2_mid.
1966  ∃taa2 : trace_any_any_free … st2_mid st2'.
1967  (if taaf_non_empty … taa2 then ¬as_costed … st2_mid else True) ∧
1968  R st1' st2' ∧ ret_rel … R st1' st2_mid ∧ label_rel … st1' st2' ∧
1969  tlr_rel … tlr1 tlr2
1970\end{verbatim}
1971\end{comment}
1972\section{The formalisation}
1973As we already explained, for the sake of presentation we explained the formal
1974content of our results departing from the actual Matita formalisation. In this
1975section we explain the basis of the Matita development, heavily based on
1976inductive definitions and dependent types.
1977
1978\paragraph*{The main differences.} The main points where the development diverges
1979from the material presented in the previous sections are the following.
1980\begin{itemize}
1981 \item Rather than having a generic notion of fragment and a predicate of
1982 structuredness and measurability, we use inductive definitions internalising
1983 the conditions. Among other things this turns the proof of \autoref{thm:preservation} a matter of
1984 structural induction, when it would require more complex induction schemes
1985 otherwise.
1986 \item As we are dealing with a deterministic labelling transition system, we
1987 purposedly blur the distinction between labelling the transitions and labelling
1988 the states originating them, and opt in general for the latter in the actual
1989 definitions.
1990 \item ................. ALTRO?
1991 \item A small difference lies in the naming conventions. In this paper we went
1992 with the tradition of labelled transition systems and named sequences of states
1993 and steps \emph{execution fragments}. In the development we named our structures
1994 \emph{traces} (that usually refer to the sequence of emitted labels only).
1995 In the remainder of this section we will use both names.
1996\end{itemize}
1997
1998\paragraph*{The main definitions.}
1999The notion of deterministic labelled transition system is captured in the development
2000via the abstract data type called $\verb+abstract_status+$. The fields
2001of this record are the following.
2002\begin{itemize}
2003 \item \verb+S : Type[0]+, the type of states.
2004 \item \verb+as_execute : S $\to$ S $\to$ Prop+, a the binary predicate modelling
2005 the execution. As in the previous sections, we write $s_1\exec s_2$ for $\verb+as_execute+~s_1~s_2$.
2006 \item \verb+as_classifier : S $\to$ classification+, a function tagging all
2007 states with a class in
2008 $\{$\verb+cl_return,cl_jump,cl_call,cl_other+$\}$, depending on the instruction
2009 that is about to be executed (we omit tail-calls for simplicity). We will
2010 use $s \class c$ as a shorthand for both $\verb+as_classifier+~s=c$
2011 (if $c$ is a classification) and $\verb+as_classifier+~s\in c$
2012 (if $c$ is a set of classifications). This partly replaces the labelling of execution
2013 steps.
2014 \item \verb+as_label : S $\to$ option label+, telling whether the
2015 next instruction to be executed in $s$ is a cost emission statement,
2016 and if yes returning the associated cost label. Our shorthand for this function
2017 will be $L$, and we will also abuse the notation by using $L~s$ as a
2018 predicate stating that $s$ is labelled.
2019 \item \verb+as_call_ident : ($\Sigma$s:S. s $\class$ cl_call) $\to$ label+,
2020 telling the identifier of the function which is being called in a
2021 \verb+cl_call+ state. We will use the shorthand $s\uparrow f$ for
2022 $\verb+as_call_ident+~s = f$.
2023 \item \verb+as_after_return : ($\Sigma$s:S. s $\class$ cl_call) $\to$ S $\to$ Prop+,
2024 which holds on the \verb+cl_call+ state $s_1$ and a state $s_2$ when the
2025 instruction to be executed in $s_2$ follows the function call to be
2026 executed in (the witness of the $\Sigma$-type) $s_1$, i.e. when $s_1\ar s_2$.
2027\end{itemize}
2028%
2029% % \begin{alltt}
2030% % record abstract_status := \{ S: Type[0];
2031% %  as_execute: S \(\to\) S \(\to\) Prop;   as_classifier: S \(\to\) classification;
2032% %  as_label: S \(\to\) option label;    as_called: (\(\Sigma\)s:S. c s = cl_call) \(\to\) label;
2033% %  as_after_return: (\(\Sigma\)s:S. c s = cl_call) \(\to\) S \(\to\) Prop \}
2034% % \end{alltt}
2035%
2036The inductive type for structured traces is actually made by three multiple
2037inductive types with the following semantics:
2038\begin{enumerate}
2039 \item $(\verb+trace_label_return+~s_1~s_2)$ (shorthand $\verb+TLR+~s_1~s_2$)
2040   is in fact what we called a measurable fragment ending in a return step.
2041%    is a trace that begins in
2042%    the state $s_1$ (included) and ends just before the state $s_2$ (excluded)
2043%    such that the instruction to be executed in $s_1$ is a label emission
2044%    statement and the one to be executed in the state before $s_2$ is a return
2045%    statement. Thus $s_2$ is the state after the return. The trace
2046%    may contain other label emission statements. It captures the structure of
2047%    the execution of function bodies: they must start with a cost emission
2048%    statement and must end with a return; they are obtained by concatenating
2049%    one or more basic blocks, all starting with a label emission
2050%    (e.g. in case of loops).
2051 \item $(\verb+trace_label_label+~b~s_1~s_2)$ (shorthand $\verb+TLL+~b~s_1~s_2$)
2052   models basic blocks. It is the special case of a measurable fragment containing
2053   only its first label emission.
2054 \item $(\verb+trace_any_label+~b~s_1~s_2)$ (shorthand $\verb+TAL+~b~s_1~s_2$)
2055   is a structured fragment, possibly with a return step appended to it, that
2056   does not contain any label apart possibly from the first state.
2057\end{enumerate}
2058The above definition summarise the formal rules shown in \autoref{fig:traces}.
2059\begin{figure}
2060\begin{multicols}{3}
2061\infrule[\verb+tlr_base+]
2062 {\verb+TLL+~true~s_1~s_2}
2063 {\verb+TLR+~s_1~s_2}
2064
2065\infrule[\verb+tlr_step+]
2066 {\verb+TLL+~false~s_1~s_2 \andalso
2067  \verb+TLR+~s_2~s_3
2068 }
2069 {\verb+TLR+~s_1~s_3}
2070
2071\infrule[\verb+tll_base+]
2072 {\verb+TAL+~b~s_1~s_2 \andalso
2073  L~s_1
2074 }
2075 {\verb+TLL+~b~s_1~s_2}
2076\end{multicols}
2077
2078\infrule[\verb+tal_base_not_return+]
2079 {s_1\exec s_2 \andalso
2080  s_1\class\{\verb+cl_jump+, \verb+cl_other+\}\andalso
2081  L~s_2
2082 }
2083 {\verb+TAL+~false~s_1~s_2}
2084
2085\infrule[\verb+tal_base_return+]
2086 {s_1\exec s_2 \andalso
2087  s_1 \class \verb+cl_return+
2088 }
2089 {\verb+TAL+~true~s_1~s_2}
2090
2091\infrule[\verb+tal_base_call+]
2092 {s_1\exec s_2 \andalso
2093  s_1 \class \verb+cl_call+ \andalso
2094  s_1\ar s_3 \andalso
2095  \verb+TLR+~s_2~s_3 \andalso
2096  L~s_3
2097 }
2098 {\verb+TAL+~false~s_1~s_3}
2099
2100\infrule[\verb+tal_step_call+]
2101 {s_1\exec s_2 \andalso
2102  s_1 \class \verb+cl_call+ \andalso
2103  s_1\ar s_3 \andalso
2104  \verb+TLR+~s_2~s_3 \andalso
2105  \verb+TAL+~b~s_3~s_4
2106 }
2107 {\verb+TAL+~b~s_1~s_4}
2108
2109\infrule[\verb+tal_step_default+]
2110 {s_1\exec s_2 \andalso
2111  \lnot L~s_2 \andalso
2112  \verb+TAL+~b~s_2~s_3\andalso
2113  s_1 \class \verb+cl_other+
2114 }
2115 {\verb+TAL+~b~s_1~s_3}
2116\caption{The rules forming the inductive definitions of structured
2117         traces.}
2118\label{fig:traces}
2119\end{figure}
2120\begin{comment}
2121\begin{verbatim}
2122inductive trace_label_return (S:abstract_status) : S → S → Type[0] ≝
2123  | tlr_base:
2124      ∀status_before: S.
2125      ∀status_after: S.
2126        trace_label_label S ends_with_ret status_before status_after →
2127        trace_label_return S status_before status_after
2128  | tlr_step:
2129      ∀status_initial: S.
2130      ∀status_labelled: S.
2131      ∀status_final: S.
2132        trace_label_label S doesnt_end_with_ret status_initial status_labelled →
2133        trace_label_return S status_labelled status_final →
2134          trace_label_return S status_initial status_final
2135with trace_label_label: trace_ends_with_ret → S → S → Type[0] ≝
2136  | tll_base:
2137      ∀ends_flag: trace_ends_with_ret.
2138      ∀start_status: S.
2139      ∀end_status: S.
2140        trace_any_label S ends_flag start_status end_status →
2141        as_costed S start_status →
2142          trace_label_label S ends_flag start_status end_status
2143with trace_any_label: trace_ends_with_ret → S → S → Type[0] ≝
2144  (* Single steps within a function which reach a label.
2145     Note that this is the only case applicable for a jump. *)
2146  | tal_base_not_return:
2147      ∀start_status: S.
2148      ∀final_status: S.
2149        as_execute S start_status final_status →
2150        (as_classifier S start_status cl_jump ∨
2151         as_classifier S start_status cl_other) →
2152        as_costed S final_status →
2153          trace_any_label S doesnt_end_with_ret start_status final_status
2154  | tal_base_return:
2155      ∀start_status: S.
2156      ∀final_status: S.
2157        as_execute S start_status final_status →
2158        as_classifier S start_status cl_return →
2159          trace_any_label S ends_with_ret start_status final_status
2160  (* A call followed by a label on return. *)
2161  | tal_base_call:
2162      ∀status_pre_fun_call: S.
2163      ∀status_start_fun_call: S.
2164      ∀status_final: S.
2165        as_execute S status_pre_fun_call status_start_fun_call →
2166        ∀H:as_classifier S status_pre_fun_call cl_call.
2167          as_after_return S «status_pre_fun_call, H» status_final →
2168          trace_label_return S status_start_fun_call status_final →
2169          as_costed S status_final →
2170            trace_any_label S doesnt_end_with_ret status_pre_fun_call status_final
2171  (* A call followed by a non-empty trace. *)
2172  | tal_step_call:
2173      ∀end_flag: trace_ends_with_ret.
2174      ∀status_pre_fun_call: S.
2175      ∀status_start_fun_call: S.
2176      ∀status_after_fun_call: S.
2177      ∀status_final: S.
2178        as_execute S status_pre_fun_call status_start_fun_call →
2179        ∀H:as_classifier S status_pre_fun_call cl_call.
2180          as_after_return S «status_pre_fun_call, H» status_after_fun_call →
2181          trace_label_return S status_start_fun_call status_after_fun_call →
2182          ¬ as_costed S status_after_fun_call →
2183          trace_any_label S end_flag status_after_fun_call status_final →
2184            trace_any_label S end_flag status_pre_fun_call status_final
2185  | tal_step_default:
2186      ∀end_flag: trace_ends_with_ret.
2187      ∀status_pre: S.
2188      ∀status_init: S.
2189      ∀status_end: S.
2190        as_execute S status_pre status_init →
2191        trace_any_label S end_flag status_init status_end →
2192        as_classifier S status_pre cl_other →
2193        ¬ (as_costed S status_init) →
2194          trace_any_label S end_flag status_pre status_end.
2195\end{verbatim}
2196\end{comment}
2197
2198
2199The equivalent of $|T|$ on fragments can be easily defined by mutual recursion
2200on the three types of traces defined in \autoref{fig:traces}.
2201
2202\paragraph{The forward simulation result.}
2203In the formalisation, the equivalent conditions of those
2204depicted in \autoref{fig:forwardsim} can be seen in \autoref{fig:forwardsim'}.
2205Again we must produce for each pass the relations $\S$ and $\C$. Another derived
2206relation is $\L$, which holds for states $s_1$ and $s_2$ when $L~s_1=L~s_2$.
2207%
2208Some details are skipped in the figure regarding the nature of the repeated steps depicted with
2209an asterisk.
2210There are three kinds of iterated steps without
2211calls nor returns involved in the conditions:
2212\begin{itemize}
2213 \item sequences where all states strictly after the first one are unlabelled;
2214 these are what can be safely prepended to \verb+TAL+'s, and are modelled
2215 by the inductive definition \verb+trace_any_any+ (\verb+TAA+) in the formalisation;
2216 \item sequences where all ``internal'' states strictly after the first and before the last
2217 are unlabelled; these are \verb+trace_any_any_free+ in the formalisation (\verb+TAAF+, which
2218 is just a \verb+TAA+ followed by a step);
2219 \item sequences where all states strictly before the last are unlabelled that we
2220 will call here \verb+trace_any_any_right+ (\verb+TAAR+); in the formalisation
2221 these are in fact \verb+TAAF+'s with an additional condition.
2222\end{itemize}
2223%
2224\begin{figure}
2225\centering
2226\tikzset{diag/.append style=
2227         {every node/.append style={is other,
2228                                    text height=0,text depth=0,text width=0,
2229                                    text opacity=0}                                                         
2230         },
2231         }
2232\begin{tabular}{@{}c@{}c@{}c@{}}
2233% \begin{subfigure}{.475\linewidth}
2234% \centering
2235% \begin{tikzpicture}[every join/.style={ar}, join all, thick,
2236%                             every label/.style=overlay, node distance=10mm]
2237%     \matrix [diag] (m) {%
2238%          \node (s1) [is jump] {}; & \node [fill=white] (t1) {};\\
2239%          \node (s2) {}; & \node (t2) {}; \\
2240%     };
2241%     \node [above=0 of t1, overlay] {$\alpha$};
2242%     {[-stealth]
2243%     \draw (s1) -- (t1);
2244%     \draw [new] (s2) -- node [above] {$*$} (t2);
2245%     }
2246%     \draw (s1) to node [rel] {$\S$} (s2);
2247%     \draw [new] (t1) to node [rel] {$\S,\L$} (t2);
2248% \end{tikzpicture}
2249% \caption{The \verb+cl_jump+ case.}
2250% \label{subfig:cl_jump}
2251% \end{subfigure}
2252% &
2253\begin{subfigure}[b]{.25\linewidth}
2254\centering
2255\begin{tikzpicture}[every join/.style={ar}, join all, thick,
2256                            every label/.style=overlay, node distance=10mm]
2257    \matrix [diag] (m) {%
2258         \node (s1) {}; & \node (t1) {};\\
2259         \node (s2) {}; & \node [newn] (t2) {}; \\
2260    };
2261    {[-stealth]
2262    \draw (s1) -- (t1);
2263    \draw [new] (s2) -- node [above] {$*$} (t2);
2264    }
2265    \draw (s1) to [bend right, anchor=mid] node [rel] {$\S$} (s2);
2266    \draw [new] (t1) to [bend left, anchor=mid] node [rel] {$\S,\L$} (t2);
2267\end{tikzpicture}
2268\caption{The \verb+cl_oher+ and \verb+cl_jump+ cases.}
2269\label{subfig:cl_other_jump}
2270\end{subfigure}
2271&
2272\begin{subfigure}[b]{.375\linewidth}
2273\centering
2274\begin{tikzpicture}[every join/.style={ar}, join all, thick,
2275                            every label/.style=overlay, node distance=10mm]
2276    \matrix [diag, small gap] (m) {%
2277         &\node (t1) {}; \\
2278         \node (s1) {}; \\
2279         && \node [newn] (l) {}; & \node [newn] (t2) {};\\
2280         \node (s2) {}; & \node [newn] (c) {};\\   
2281    };
2282    {[-stealth]
2283    \draw (s1) -- node [above left] {$f$} (t1);
2284    \draw [new] (s2) -- node [above] {$*$} (c);
2285    \draw [new] (c) -- node [below right] {$f$} (l);
2286    \draw [new] (l) -- node [above] {$*$} (t2);
2287    }
2288    \draw (s1) to [bend right] node [rel] {$\S$} (s2);
2289    \draw [new] (t1) to [bend left] node [rel] {$\S$} (t2);
2290    \draw [new] (t1) to [bend left] node [rel] {$\L$} (l);
2291    \draw [new] (s1) to [bend left] node [rel] {$\C$} (c);
2292    \end{tikzpicture}
2293\caption{The \verb+cl_call+ case.\\\vspace{3.1ex}}
2294\label{subfig:cl_call}
2295\end{subfigure}
2296&
2297\begin{subfigure}[b]{.375\linewidth}
2298\centering
2299\begin{tikzpicture}[every join/.style={ar}, join all, thick,
2300                            every label/.style=overlay, node distance=10mm]
2301    \matrix [diag, small gap] (m) {%
2302        \node (s1) {}; \\
2303        &\node (t1) {}; \\
2304        \node (s2) {}; & \node [newn] (c) {};\\
2305        && \node [newn] (r) {}; & \node [newn] (t2) {}; \\   
2306    };
2307    {[-stealth]
2308    \draw (s1) -- (t1);
2309    \draw [new] (s2) -- node [above] {$*$} (c);
2310    \draw [new] (c) -- (r);
2311    \draw [new] (r) -- node [above] {$*$} (t2);
2312    }
2313    \draw (s1) to [bend right] node [rel] {$\S$} (s2);
2314    \draw [new, overlay] (t1) to [bend left=60] node [rel] {$\S,\L$} (t2);
2315    \draw [new, overlay] (t1) to [bend left ] node [rel] {$\R$} (r);
2316\end{tikzpicture}
2317\caption{The \verb+cl_return+ case.\\\vspace{3.1ex}}
2318\label{subfig:cl_return}
2319\end{subfigure}
2320\end{tabular}
2321\caption{Mnemonic diagrams depicting the hypotheses for the preservation of structured traces.}
2322\label{fig:forwardsim'}
2323\end{figure}
2324This prolification of different types of fragments is a downside of shifting
2325labelling from steps to states.
2326The actual conditions are as follows.
2327%
2328\begin{condition}[\verb+cl_other+ and \verb+cl_jump+, \autoref{subfig:cl_other_jump}]
2329\label{cond:other}
2330 For all $s_1,s_1',s_2$ such that $s_1 \S s_1'$, and
2331 $s_1\exec s_1'$, and either $s_1 \class \verb+cl_other+$ or
2332 both $s_1\class\verb+cl_other+$ and $\ell~s_1'$,
2333 there exists an $s_2'$ and a $taaf:\verb+trace_any_any_free+~s_2~s_2'$
2334 such that $s_1' \mathrel{{\S} \cap {\L}} s_2'$ and either
2335 $taaf$ is non empty, or one among $s_1$ and $s_1'$ is not labelled.
2336 The last condition is needed to prevent the collapsing of two
2337 label-emitting consecutive states.
2338\end{condition}
2339
2340% In the above condition depicted in ,
2341% a $\verb+trace_any_any_free+~s_1~s_2$ (which from now on
2342% will be shorthanded as \verb+TAAF+) is an
2343% inductive type of structured traces that do not contain function calls or
2344% cost emission statements. Differently from a \verb+TAA+, the
2345% instruction to be executed in the lookahead state $s_2$ may be a cost emission
2346% statement.
2347%
2348% The intuition of the condition is that one step can be replaced with zero or more steps if it
2349% preserves the relation between the data and if the two final statuses are
2350% labelled in the same way. Moreover, we must take special care of the empty case
2351% to avoid collapsing two consecutive states that emit a label, missing one of the two emissions.
2352%
2353\begin{condition}[\verb+cl_call+, \autoref{subfig:cl_call}]
2354\label{cond:call}
2355 For all $s_1,s_1',s_2$ s.t. $s_1 \S s_1'$ and
2356 $s_1\exec s_1'$ and $s_1 \class \verb+cl_call+$, there exists $s_a, s_b, s_2'$, a
2357$\verb+TAA+~s_2~s_a$, and a
2358$\verb+TAAF+~s_b~s_2'$ such that:
2359$s_a\class\verb+cl_call+$, the \verb+as_call_ident+'s of
2360the two call states are the same, $s_1 \C s_a$,
2361$s_a\exec s_b$, $s_1' \L s_b$ and
2362$s_1' \S s_2'$.
2363\end{condition}
2364
2365% The condition, depicted in \autoref{subfig:cl_call} says that, to simulate a function call, we can perform a
2366% sequence of silent actions before and after the function call itself.
2367% The old and new call states must be $\C$-related, the old and new
2368% states at the beginning of the function execution must be $\L$-related
2369% and, finally, the two initial and final states must be $\S$-related
2370% as usual.
2371
2372\begin{condition}[\verb+cl_return+, \autoref{subfig:cl_return}]
2373\label{cond:return}
2374 For all $s_1,s_1',s_2$ s.t. $s_1 \S s_1'$,
2375 $s_1\exec s_1'$ and $s_1 \class \verb+cl_return+$, there exists $s_a, s_b, s_2'$, a
2376$\verb+TAA+~s_2~s_a$ and a
2377$\verb+TAAR+~s_b~s_2'$ such that:
2378$s_a\class\verb+cl_return+$,
2379$s_a\exec s_b$,
2380$s_1' \R s_b$ and
2381$s_1' \mathrel{{\S} \cap {\L}} s_2'$.
2382\end{condition}
2383
2384\paragraph{Main result.}
2385Let us assume that $\S$ and $\C$ are given such that
2386Conditions~\ref{cond:other}, \ref{cond:call} and~\ref{cond:return}
2387are satisfied. If we reword the
2388relation $\LS$ of \autoref{def:R_LS} by defining
2389$$s_1\LS s_2\iffdef s_1\L s_2\wedge \exists s_2', taa:\verb+TAA+~s_2~s_2'. s_1\S s_2',$$
2390we can prove the trace reconstruction theorem,
2391which is the analogue of \autoref{thm:main}.
2392%
2393\begin{theorem}[\verb+status_simulation_produce_tlr+]
2394\label{thm:main'}
2395For every $s_1,s_1',s_2$ s.t.
2396$s_1\LS s_2$ and there is a $tlr_1:\verb+TLR+~s_1~s_1'$,
2397then there exist $s_2'$ and $tlr_2:\verb+TLR+~s_2~s_2'$
2398with $|tlr_1|=|tlr_2|$. Moreover there are $s_2''$ and
2399a $\verb+TAAR+~s_2'~s_2''$ with $s_2'\mathrel{{\S}\cap{\L}} s_2''$.
2400\end{theorem}
2401% In particular, the \verb+status_simulation_produce_tlr+ theorem
2402% applied to the \verb+main+ function of the program and equal
2403% $s_{2_b}$ and $s_2$ states shows that, for every initial state in the
2404% source code that induces a structured trace in the source code,
2405% the compiled code produces a similar structured trace.
2406The theorem states that a \verb+trace_label_return+ in the source code
2407together with a precomputed preamble of silent states
2408(hidden in the definition of $\LS$) in the target code induces a
2409similar \verb+trace_label_return+ in the target code.
2410% Note that the statement does not
2411% require the produced \verb+trace_label_return+ to start with the
2412% precomputed preamble, even if this is likely to be the case in concrete
2413% implementations.
2414The preamble in input and the postamble in output are necessary for compositionality,
2415and follow directly from the the fact that points semantically related
2416may not correspond to points where the same observable events are fired, in particular
2417cost labels and $RET$'s that mark the borders of measurability.
2418
2419The proof proceeds by mutual structural induction on the traces involved.
2420In the actual formalisation, in place of $|tlr_1|=|tlr_2|$ we use a
2421recursively defined simulation relation between traces that implies the required
2422equality.
2423
2424\section{Conclusions and future works}
2425\label{sec:conclusions}
2426The labelling approach is a technique to implement compilers that induce on
2427the source code a non uniform cost model determined from the object code
2428produced. The cost model assigns a cost to each basic block of the program.
2429The main theorem of the approach says that there is an exact
2430correspondence between the sequence of basic blocks started in the source
2431and object code, and that no instruction in the source or object code is
2432executed outside a basic block. Thus the cost of object code execution
2433can be computed precisely on the source.
2434
2435In this paper we scaled the labelling approach to cover a programming language
2436with function calls. This introduces new difficulties when the language
2437is unstructured, i.e. it allows function calls to return anywhere in the code,
2438destroying the hope of a static prediction of the cost of basic blocks.
2439We restored static predictability by introducing a new semantics for unstructured
2440programs that single outs well structured executions. The latter are represented
2441by structured traces, a generalisation of streams of observables that capture
2442several structural invariants of the execution, like well nesting of functions
2443or the fact that every basic block must start with a code emission statement.
2444We showed that structured traces are sufficiently well behaved to statically compute a precise cost model on the object code.
2445
2446We also proved that the cost model computed on the object code is also valid
2447on the source code if the compiler respects two requirements: the weak execution
2448traces of the source and target code must be the same and the object
2449code execution fragments are structured.
2450
2451To prove that a compiler respects the requirement we extended the notion
2452of forward simulation proof for a labelled transition system to grant
2453preservation of structured fragments. If the source language of the compiler
2454is structured, all its execution fragments are, allowing to deduce from
2455preservation of structure that object code fragments are structured too.
2456
2457Finally, we identified measurable execution fragments that are those whose
2458execution time (once compiled) can be exactly computed looking at the object
2459code weak execution traces only. A final instrumentation pass on the source
2460code can then be used to turn the non functional property of having a certain
2461cost into the functional property of granting that a certain global variable
2462incremented at the beginning of every block according to the induced cost model
2463has a certain value.
2464
2465All results presented in the paper are part of a larger certification of a
2466C compiler which is based on the labelling approach. The certification, done
2467in Matita, is the main deliverable of the FET-Open Certified Complexity (CerCo).
2468
2469The short term objective consists in the completion of the certification of
2470the CerCo compiler exploiting the main theorem of this paper. An alternative approach
2471to the same problem that we would like to investigate consists in labelling
2472every instruction that follows a call. This would still require a form of structured
2473execution fragments, stating that no only calls but also returns are always followed
2474by an emission. The main downside is the pollution of the instrumented code
2475with many cost annotations.
2476
2477\paragraph{Related works.}
2478CerCo is the first project that explicitly tries to induce a
2479precise cost model on the source code in order to establish non-functional
2480properties of programs on an high level language. Traditional certifications
2481of compilers, like~\cite{compcert2,piton}, only explicitly prove preservation
2482of the functional properties.
2483
2484Usually forward simulations take the following form: for each transition
2485from $s_1$ to $s_2$ in the source code, there exists an equivalent sequence of
2486transitions in the target code of length $n$. The number $n$ of transition steps
2487in the target code can just be the witness of the existential statement.
2488An equivalent alternative when the proof of simulation is constructive consists
2489in providing an explicit function, called \emph{clock function} in the
2490literature~\cite{clockfunctions}, that computes $n$ from $s_1$. Every clock
2491function constitutes then a cost model for the source code, in the spirit of
2492what we are doing in CerCo. However, we believe our solution to be superior
2493in the following respects: 1) the machinery of the labelling approach is
2494insensible to the resource being measured. Indeed, any cost model computed on
2495the object code can be lifted to the source code (e.g. stack space used,
2496energy consumed, etc.) simply re-proving an analogue of~\autoref{thm:static}.
2497For example, in CerCo we transported to the source level not only the execution
2498time cost model, but also the amount of stack used by function calls.
2499On the contrary, clock functions only talk about
2500number of transition steps. In order to extend the approach with clock functions
2501to other resources, additional functions must be introduced. Moreover, the
2502additional functions would be handled differently in the proof.
25032) the cost models induced by the labelling approach have a simple presentation.
2504In particular, they associate a number to each basic block. More complex
2505models can be induced when the approach is scaled to cover, for instance,
2506loop optimisations~\cite{loopoptimizations}, but the costs are still meant to
2507be easy to understand and manipulate in an interactive theorem prover or
2508in Frama-C.
2509On the contrary, a clock function is a complex function of the state $s_1$
2510which, as a function, is an opaque object that is difficult to reify as
2511source code in order to reason on it.
2512
2513% e.g.
2514% because the 1-to-many forward simulation conditions allow in the
2515% case of function calls to execute a preamble of silent instructions just after
2516% the function call.
2517
2518% Similarly to the call condition, to simulate a return we can perform a
2519% sequence of silent actions before and after the return statement itself,
2520% as depicted in \autoref{subfig:cl_return}.
2521% The old and the new statements after the return must be $\R$-related,
2522% to grant that they returned to corresponding calls.
2523% The two initial and final states must be $\S$-related
2524% as usual and, moreover, they must exhibit the same labels. Finally, when
2525% the suffix is non empty we must take care of not inserting a new
2526% unmatched cost emission statement just after the return statement.
2527
2528
2529% There are three mutual structural recursive functions, one for each of
2530% \verb+TLR+, \verb+TLL+ and \verb+TAL+, for which we use the same notation
2531% $|\,.\,|$: the \emph{flattening} of the traces. These functions
2532% allow to extract from a structured trace the list of emitted cost labels.
2533%  We only show here the type of one
2534% of them:
2535% \begin{alltt}
2536% flatten_trace_label_return:
2537%  \(\forall\)S: abstract_status. \(\forall\)\(s_1,s_2\).
2538%   trace_label_return \(s_1\) \(s_2\) \(\to\) list (as_cost_label S)
2539% \end{alltt}
2540%
2541% \paragraph{Structured traces similarity and cost prediction invariance.}
2542%
2543% A compiler pass maps source to object code and initial states to initial
2544% states. The source code and initial state uniquely determine the structured
2545% trace of a program, if it exists. The structured trace fails to exists iff
2546% the structural conditions are violated by the program execution (e.g. a function
2547% body does not start with a cost emission statement). Let us assume that the
2548% target structured trace exists.
2549%
2550% What is the relation between the source and target structured traces?
2551% In general, the two traces can be arbitrarily different. However, we are
2552% interested only in those compiler passes that maps a trace $\tau_1$ to a trace
2553% $\tau_2$ such that
2554% \begin{equation}|\tau_1| = |\tau_2|.\label{th2}\end{equation}
2555% The reason is that the combination of~\eqref{th1} with~\eqref{th2} yields the
2556% corollary
2557% \begin{equation}\label{th3}
2558% \forall s_1,s_2. \forall \tau: \verb+TLR+~s_1~s_2.~
2559%   \verb+clock+~s_2 - \verb+clock+~s_1 =
2560%   \Sigma_{\alpha \in |\tau_1|}\;k(\alpha) =
2561%   \Sigma_{\alpha \in |\tau_2|}\;k(\alpha).
2562% \end{equation}
2563% This corollary states that the actual execution time of the program can be computed equally well on the source or target language. Thus it becomes possible to
2564% transfer the cost model from the target to the source code and reason on the
2565% source code only.
2566%
2567% We are therefore interested in conditions stronger than~\eqref{th2}.
2568% Therefore we introduce here a similarity relation between traces with
2569% the same structure. Theorem~\verb+tlr_rel_to_traces_same_flatten+
2570% in the Matita formalisation shows that~\eqref{th2} holds for every pair
2571% $(\tau_1,\tau_2)$ of similar traces.
2572%
2573% Intuitively, two traces are similar when one can be obtained from
2574% the other by erasing or inserting silent steps, i.e. states that are
2575% not \verb+as_costed+ and that are classified as \verb+cl_other+.
2576% Silent steps do not alter the structure of the traces.
2577% In particular,
2578% the relation maps function calls to function calls to the same function,
2579% label emission statements to emissions of the same label, concatenation of
2580% subtraces to concatenation of subtraces of the same length and starting with
2581% the same emission statement, etc.
2582%
2583% In the formalisation the three similarity relations --- one for each trace
2584% kind --- are defined by structural recursion on the first trace and pattern
2585% matching over the second. Here we turn
2586% the definition into the inference rules shown in \autoref{fig:txx_rel}
2587% for the sake of readability. We also omit from trace constructors all arguments,
2588% but those that are traces or that
2589% are used in the premises of the rules. By abuse of notation we denote all three
2590% relations by infixing $\approx$.
2591%
2592% \begin{figure}
2593% \begin{multicols}{2}
2594% \infrule
2595%  {tll_1\approx tll_2
2596%  }
2597%  {\verb+tlr_base+~tll_1 \approx \verb+tlr_base+~tll_2}
2598%
2599% \infrule
2600%  {tll_1 \approx tll_2 \andalso
2601%   tlr_1 \approx tlr_2
2602%  }
2603%  {\verb+tlr_step+~tll_1~tlr_1 \approx \verb+tlr_step+~tll_2~tlr_2}
2604% \end{multicols}
2605% \vspace{3ex}
2606% \begin{multicols}{2}
2607% \infrule
2608%  {L~s_1 = L~s_2 \andalso
2609%   tal_1\approx tal_2
2610%  }
2611%  {\verb+tll_base+~s_1~tal_1 \approx \verb+tll_base+~s_2~tal_2}
2612%
2613% \infrule
2614%  {tal_1\approx tal_2
2615%  }
2616%  {\verb+tal_step_default+~tal_1 \approx tal_2}
2617% \end{multicols}
2618% \vspace{3ex}
2619% \infrule
2620%  {}
2621%  {\verb+tal_base_not_return+\approx taa \append \verb+tal_base_not_return+}
2622% \vspace{1ex}
2623% \infrule
2624%  {}
2625%  {\verb+tal_base_return+\approx taa \append \verb+tal_base_return+}
2626% \vspace{1ex}
2627% \infrule
2628%  {tlr_1\approx tlr_2 \andalso
2629%   s_1 \uparrow f \andalso s_2\uparrow f
2630%  }
2631%  {\verb+tal_base_call+~s_1~tlr_1\approx taa \append \verb+tal_base_call+~s_2~tlr_2}
2632% \vspace{1ex}
2633% \infrule
2634%  {tlr_1\approx tlr_2 \andalso
2635%   s_1 \uparrow f \andalso s_2\uparrow f \andalso
2636%   \verb+tal_collapsable+~tal_2
2637%  }
2638%  {\verb+tal_base_call+~s_1~tlr_1 \approx taa \append \verb+tal_step_call+~s_2~tlr_2~tal_2)}
2639% \vspace{1ex}
2640% \infrule
2641%  {tlr_1\approx tlr_2 \andalso
2642%   s_1 \uparrow f \andalso s_2\uparrow f \andalso
2643%   \verb+tal_collapsable+~tal_1
2644%  }
2645%  {\verb+tal_step_call+~s_1~tlr_1~tal_1 \approx taa \append \verb+tal_base_call+~s_2~tlr_2)}
2646% \vspace{1ex}
2647% \infrule
2648%  {tlr_1 \approx tlr_2 \andalso
2649%   s_1 \uparrow f \andalso s_2\uparrow f\andalso
2650%   tal_1 \approx tal_2 \andalso
2651%  }
2652%  {\verb+tal_step_call+~s_1~tlr_1~tal_1 \approx taa \append \verb+tal_step_call+~s_2~tlr_2~tal_2}
2653% \caption{The inference rule for the relation $\approx$.}
2654% \label{fig:txx_rel}
2655% \end{figure}
2656% %
2657% \begin{comment}
2658% \begin{verbatim}
2659% let rec tlr_rel S1 st1 st1' S2 st2 st2'
2660%   (tlr1 : trace_label_return S1 st1 st1')
2661%   (tlr2 : trace_label_return S2 st2 st2') on tlr1 : Prop ≝
2662% match tlr1 with
2663%   [ tlr_base st1 st1' tll1 ⇒
2664%     match tlr2 with
2665%     [ tlr_base st2 st2' tll2 ⇒ tll_rel … tll1 tll2
2666%     | _ ⇒ False
2667%     ]
2668%   | tlr_step st1 st1' st1'' tll1 tl1 ⇒
2669%     match tlr2 with
2670%     [ tlr_step st2 st2' st2'' tll2 tl2 ⇒
2671%       tll_rel … tll1 tll2 ∧ tlr_rel … tl1 tl2
2672%     | _ ⇒ False
2673%     ]
2674%   ]
2675% and tll_rel S1 fl1 st1 st1' S2 fl2 st2 st2'
2676%  (tll1 : trace_label_label S1 fl1 st1 st1')
2677%  (tll2 : trace_label_label S2 fl2 st2 st2') on tll1 : Prop ≝
2678%   match tll1 with
2679%   [ tll_base fl1 st1 st1' tal1 H ⇒
2680%     match tll2 with
2681%     [ tll_base fl2 st2 st2 tal2 G ⇒
2682%       as_label_safe … («?, H») = as_label_safe … («?, G») ∧
2683%       tal_rel … tal1 tal2
2684%     ]
2685%   ]
2686% and tal_rel S1 fl1 st1 st1' S2 fl2 st2 st2'
2687%  (tal1 : trace_any_label S1 fl1 st1 st1')
2688%  (tal2 : trace_any_label S2 fl2 st2 st2')
2689%    on tal1 : Prop ≝
2690%   match tal1 with
2691%   [ tal_base_not_return st1 st1' _ _ _ ⇒
2692%     fl2 = doesnt_end_with_ret ∧
2693%     ∃st2mid,taa,H,G,K.
2694%     tal2 ≃ taa_append_tal ? st2 ??? taa
2695%       (tal_base_not_return ? st2mid st2' H G K)
2696%   | tal_base_return st1 st1' _ _ ⇒
2697%     fl2 = ends_with_ret ∧
2698%     ∃st2mid,taa,H,G.
2699%     tal2 ≃ taa_append_tal ? st2 ? st2mid st2' taa
2700%       (tal_base_return ? st2mid st2' H G)
2701%   | tal_base_call st1 st1' st1'' _ prf _ tlr1 _ ⇒
2702%     fl2 = doesnt_end_with_ret ∧
2703%     ∃st2mid,G.as_call_ident S2 («st2mid, G») = as_call_ident ? «st1, prf» ∧
2704%     ∃taa : trace_any_any ? st2 st2mid.∃st2mid',H.
2705%     (* we must allow a tal_base_call to be similar to a call followed
2706%       by a collapsable trace (trace_any_any followed by a base_not_return;
2707%       we cannot use trace_any_any as it disallows labels in the end as soon
2708%       as it is non-empty) *)
2709%     (∃K.∃tlr2 : trace_label_return ? st2mid' st2'.∃L.
2710%       tal2 ≃ taa @ (tal_base_call … H G K tlr2 L) ∧ tlr_rel … tlr1 tlr2) ∨
2711%     ∃st2mid'',K.∃tlr2 : trace_label_return ? st2mid' st2mid''.∃L.
2712%     ∃tl2 : trace_any_label … doesnt_end_with_ret st2mid'' st2'.
2713%       tal2 ≃ taa @ (tal_step_call … H G K tlr2 L tl2) ∧
2714%       tlr_rel … tlr1 tlr2 ∧ tal_collapsable … tl2
2715%   | tal_step_call fl1 st1 st1' st1'' st1''' _ prf _ tlr1 _ tl1 ⇒
2716%     ∃st2mid,G.as_call_ident S2 («st2mid, G») = as_call_ident ? «st1, prf» ∧
2717%     ∃taa : trace_any_any ? st2 st2mid.∃st2mid',H.
2718%     (fl2 = doesnt_end_with_ret ∧ ∃K.∃tlr2 : trace_label_return ? st2mid' st2'.∃L.
2719%       tal2 ≃ taa @ tal_base_call … H G K tlr2 L ∧
2720%       tal_collapsable … tl1 ∧ tlr_rel … tlr1 tlr2) ∨
2721%     ∃st2mid'',K.∃tlr2 : trace_label_return ? st2mid' st2mid''.∃L.
2722%     ∃tl2 : trace_any_label ? fl2 st2mid'' st2'.
2723%       tal2 ≃ taa @ (tal_step_call … H G K tlr2 L tl2) ∧
2724%       tal_rel … tl1 tl2 ∧ tlr_rel … tlr1 tlr2
2725%   | tal_step_default fl1 st1 st1' st1'' _ tl1 _ _ ⇒
2726%     tal_rel … tl1 tal2 (* <- this makes it many to many *)
2727%   ].
2728% \end{verbatim}
2729% \end{comment}
2730% %
2731% In the preceding rules, a $taa$ is an inhabitant of the
2732% $\verb+trace_any_any+~s_1~s_2$ (shorthand $\verb+TAA+~s_1~s_2$),
2733% an inductive data type whose definition
2734% is not in the paper for lack of space. It is the type of valid
2735% prefixes (even empty ones) of \verb+TAL+'s that do not contain
2736% any function call. Therefore it
2737% is possible to concatenate (using ``$\append$'') a \verb+TAA+ to the
2738% left of a \verb+TAL+. A \verb+TAA+ captures
2739% a sequence of silent moves.
2740% The \verb+tal_collapsable+ unary predicate over \verb+TAL+'s
2741% holds when the argument does not contain any function call and it ends
2742% with a label (not a return). The intuition is that after a function call we
2743% can still perform a sequence of silent actions while remaining similar.
2744%
2745% As should be expected, even though the rules are asymmetric $\approx$ is in fact
2746% an equivalence relation.
2747\bibliographystyle{splncs03}
2748\bibliography{ccexec}
2749
2750% \appendix
2751% \section{Notes for the reviewers}
2752%
2753% The results described in the paper are part of a larger formalization
2754% (the certification of the CerCo compiler). At the moment of the submission
2755% we need to single out from the CerCo formalization the results presented here.
2756% Before the 16-th of February we will submit an attachment that contains the
2757% minimal subset of the CerCo formalization that allows to prove those results.
2758% At that time it will also be possible to measure exactly the size of the
2759% formalization described here. At the moment a rough approximation suggests
2760% about 2700 lines of Matita code.
2761%
2762% We will also attach the development version of the interactive theorem
2763% prover Matita that compiles the submitted formalization. Another possibility
2764% is to backport the development to the last released version of the system
2765% to avoid having to re-compile Matita from scratch.
2766%
2767% The programming and certification style used in the formalization heavily
2768% exploit dependent types. Dependent types are used: 1) to impose invariants
2769% by construction on the data types and operations (e.g. a traces from a state
2770% $s_1$ to a state $s_2$ can be concatenad to a trace from a state
2771% $s_2'$ to a state $s_3$ only if $s_2$ is convertible with $s_2'$); 2)
2772% to state and prove the theorems by using the Russell methodology of
2773% Matthieu Sozeau\footnote{Subset Coercions in Coq in TYPES'06. Matthieu Sozeau. Thorsten Altenkirch and Conor McBride (Eds). Volume 4502 of Lecture Notes in Computer Science. Springer, 2007, pp.237-252.
2774% }, better known in the Coq world as ``\verb+Program+'' and reimplemented in a simpler way in Matita using coercion propagations\footnote{Andrea Asperti, Wilmer Ricciotti, Claudio Sacerdoti Coen, Enrico Tassi: A Bi-Directional Refinement Algorithm for the Calculus of (Co)Inductive Constructions. Logical Methods in Computer Science 8(1) (2012)}. However, no result presented depends
2775% mandatorily on dependent types: it should be easy to adapt the technique
2776% and results presented in the paper to HOL.
2777%
2778% Finally, Matita and Coq are based on minor variations of the Calculus of
2779% (Co)Inductive Constructions. These variations do not affect the CerCo
2780% formalization. Therefore a porting of the proofs and ideas to Coq would be
2781% rather straightforward.
2782
2783\end{document}
Note: See TracBrowser for help on using the repository browser.