scieee AI-readable full text Open interactive document viewer

Non-Blocking Concurrent Imperative Programming with Session Types

Miguel Eduardo Pinto da Silva

Full text

Non-Blocking Concurrent Imperative Programming with Session Types Miguel Eduardo Pinto da Silva Master’s degree in Computer Science Computer Science Department 2016 Supervisor António Mário Florido, Associate Professor, Faculty of Science, University of Porto Co-supervisor Frank Pfenning, Professor, Carnegie Mellon University All corrections determined by the jury, and only those, were incorporated. The President of the Jury, Porto, ______/______/_________ Miguel Eduardo Pinto da Silva Non-Blocking Concurrent Imperative Programming with Session Types Department of Computer Science Faculty of Sciences University of Porto June 2016 Miguel Eduardo Pinto da Silva Non-Blocking Concurrent Imperative Programming with Session Types Dissertation submitted to the Faculty of Sciences University of Porto as part of the requirements for the degree of Master in Computer Science Supervisor: Prof. Mário Florido Co-supervisor: Prof. Frank Pfenning Department of Computer Science Faculty of Sciences University of Porto June 2016 To my parents iii Acknowledgements First, I would like to thank my advisors, Professor Mário Florido and Professor Frank Pfenning, for sharing all their knowledge and experience with me. In particular, I want to thank Professor Frank Pfenning for taking me in as an undergraduate intern in Pittsburgh, which was the beginning of this thesis. I also want to commend and thank for Professor Mário Florido’s bravery for taking me as his student in a thesis he was not intimately connected with. All my Professors share a fundamental role on my graduation, as they are the basis of everything I have learned. For this dissertation, I want to thank in particular Professor Sandra Alves, who helped me with the basics of π -calculus when I struggled the most with it, and Professor Ricardo Rocha, for the help with pthreads and the initial push in the right direction when I did not know where to start implementing this thesis. To all my family, who supported me all my life. Specially, to my parents, who would not let me settle for anything less than perfection, and to my brother, who made me the geek I am. I’m fortunate to have many good friends who made this year easier: Afonso, João Vítor, Ricardo and Tiago thank you for making my Friday and Saturday nights much more cheerful; Marvin and Rafaela, my friends from Physics, who always set a (very high!) bar for me to achieve; my friends from the Computer Science department, specially, João and Patricia. Finally, to my dearest Catarina, who was always by my side in this year long journey, starting in Pittsburgh, and whose constant support and love were crucial for me to carry this dissertation through. v This work was partially funded by the FCT (Portuguese Foundation for Science and Technology) through the Carnegie Mellon Portugal Program. Miguel Eduardo Pinto da Silva Porto, 2016 vi Abstract Concurrent C0 is an imperative programming language in the C family with sessiontyped message-passing concurrency. The previously proposed semantics implements asynchronous (non-blocking) output; here, we extend it with non-blocking input. Our framework relies on one key idea: to postpone message reception as much as possible by interpreting receive commands as a request for a message. We also extend the semantics to include a cost, named work and span, on each operation. We implemented our ideas as a translation from a blocking intermediate language to a non-blocking language. Using the cost semantics and assuming correctness, we prove some important properties of the non-blocking model: • The span in the non-blocking semantics is less or equal than the span in the blocking semantics. •The work is unchanged across both semantics. Finally, we evaluate our techniques with several benchmark programs and show the results obtained. Keywords: Session Types, Concurrency, Asynchronous Communication, Message Passing, Work, Span. vii List of Tables 3.1 Operational semantics of Concurrent C0. . . . . . . . . . . . . . . . . . 21 3.2 Cost Semantics for Concurrent C0. . . . . . . . . . . . . . . . . . . . . 23 4.1 Operational and cost semantics rules for the non-blocking receive model. 29 4.2 Translation scheme from blocking to non-blocking versions. . . . . . . . 32 4.3 Readback scheme from non-blocking to blocking programs. . . . . . . . 35 5.1 CC0 benchmarking suite . . . . . . . . . . . . . . . . . . . . . . . . . . 59 5.2 Blocking and Non-blocking benchmarks . . . . . . . . . . . . . . . . . . 60 B.1 Auxiliary functions for the translation. . . . . . . . . . . . . . . . . . . 77 B.2 Definition of translation rules for while loops. . . . . . . . . . . . . . . 79 B.3 Definition of translation rules for function calls. . . . . . . . . . . . . . 79 xv List of Figures 2.1 SessionTypessyntax............................ 6 2.2 Queue, list and tree interface definition. . . . . . . . . . . . . . . . . . . 6 2.3 Linear process expressions . . . . . . . . . . . . . . . . . . . . . . . . . 8 2.4 Polarized Session Types . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.5 SSOS rules for the untyped λ-calculus. .................. 10 3.1 Communication syntax of CC0 . . . . . . . . . . . . . . . . . . . . . . . 18 3.2 Additional communication syntax for CC0’s target language . . . . . . 19 3.3 Configuration definition, using multiset notation. . . . . . . . . . . . . 19 3.4 Queue definition, filled by provider or client. . . . . . . . . . . . . . . . 20 3.5 Configuration definition, using multiset notation, in the cost semantics. 22 3.6 Queue definition, filled by provider or client, in the cost semantics. . . . 23 4.1 Non-blocking syntax for CC0’s target language . . . . . . . . . . . . . . 26 4.2 Definitions of configuration in a non-blocking environment and the requestqueue................................. 28 5.1 Blocking and Non-Blocking span benchmarks on a log scale. . . . . . . 59 5.2 Execution time speedup from Blocking to Non-Blocking Version. . . . . 59 xvii List of Code 3.1 Protocol definition of a queue. . . . . . . . . . . . . . . . . . . . . . . . 15 3.2 Protocol definition of a binary search tree. . . . . . . . . . . . . . . . . 15 3.3 Implementation of a queue with constant time enqueue and dequeue operations from the client’s perspective. . . . . . . . . . . . . . . . . . . 17 4.1 Non-blocking implementation of a queue, in CC0’s simplified target language. .................................. 27 5.1 Channelstructure. ............................. 46 5.2 Spawning a process running the empty function.............. 47 5.3 Creating a new channel in concur2. .................... 47 5.4 Structure of a message. . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 5.5 Send and receive functions of an integer, for provider and client channels. 49 5.6 Receiving a message in concur2....................... 50 5.7 Implementation of a queue, in the low-level blocking target language of CC0...................................... 51 5.8 Requeststructure. ............................. 52 5.9 Queues of requests declaration in the channel structure. . . . . . . . . . 52 5.10 Functions to create a request, exemplified by a request for an integer value...................................... 53 5.11 Functions to synchronize a channel. . . . . . . . . . . . . . . . . . . . . 53 5.12 Non-blocking implementation of a queue, in CC0’s low-level target language. .................................. 55 A.1 Implementation of an unbalanced binary search tree, in CC0. . . . . . . 69 A.2 Non-blocking implementation of an unbalanced binary search tree, in CC0’s simplified target language. . . . . . . . . . . . . . . . . . . . . . 71 xix Chapter 1 Introduction This dissertation presents a non-blocking model for receiving messages, implemented as an extension to an existing imperative programming language, which improves the performance of the previous model of reception in some examples. Our model is based on the premise that we want to halt execution to wait for a message only when the data contained in that message is necessary to continue computation. Our work is based on session types [ 16 , 17 ], a typing system for π -calculus [ 24 , 20 ], that defines communication between processes over communication channels. In recent work, session types have been linked with linear logic via a Curry-Howard interpretation of linear propositions as types, proofs as processes, and cut reduction as communication. Variations apply for both intuitionistic [ 5 , 6 ] and classical [ 29 ] linear logic. The intuitionistic variant culminated in SILL, a functional language with sessiontyped concurrency [ 27 ]. The adaptation of SILL to imperative programming gave rise to Concurrent C0 [ 30 ], a session-based extension to an imperative language. This dissertation describes our modifications to Concurrent C0 to accomplish our non-blocking model. Concurrent C0’s model for message reception, which we refer to as blocking, relies on fetching messages from a queue, a usual construct in asynchronous communication using linear channels [ 14 , 22 ]. Upon performing a receiving action, if the message is not in the queue, the execution of the program blocks, until it can retrieve the message 1 2CHAPTER 1. INTRODUCTION from the queue. On the other hand, our non-blocking model, by interpreting receives as requests, will only try to fetch the message when a synchronization is undergoing, which is only performed when the execution requires that message to proceed. As an illustrative example of the difference between these two models, consider the following simple example: x = receive(c); P; y = x+1 . We are trying to receive a value, x , from channel c , then execute a sequence of instructions, P , which do not use the variable x , and, finally, execute an operation using that variable. Under the blocking semantics, we need to stop execution until the value is ready, in spite of not needing it immediately. Under the non-blocking model, this value would only be synchronized before the instruction y = x+1. We also present a compilation function from the original version of Concurrent C0 to our non-blocking one and introduce a cost semantics that computes the span and work [ 9 ], providing an abstract analytical measure of latent parallelism in the computation. Assuming correctness, we then prove that the span always improves or remains the same under the non-blocking semantics. We also prove that work, on the other hand, is constant in both semantics. In related work, Guenot [ 15 ] has given a pure and elegant computational interpretation of classical linear logic with non-blocking input based on the solos calculus [ 19 ]. The primary notion of a process as a thread of control that pervades our work is no longer visible there and it does not immediately suggest an implementation strategy. Our work generalizes the functional notions of futures and promises [ 2 , 13 ] by supporting more complex bidirectional communication [26]. The main results presented in this dissertation were previously reported in [25]. 1.1 Dissertation Outline This dissertation is structured as follows: Chapter 2 - Background - presents the fundamental concepts that are the basis of this thesis. 1.1. DISSERTATION OUTLINE 3 Chapter 3 - Imperative Programming with Session Types - introduces the main concepts to programming with Concurrent C0, including compilation and target language, and proposes a cost semantics for the language. Chapter 4 - Non-Blocking Receive - describes an extension to CC0, by changing how input is handled by each process. Introduces an intermediate language, new operational and cost semantics, a translation from CC0’s target language to this intermediate language and some theoretical results. Chapter 5 - Implementation and Experimental Evaluation - details how the concepts from Chapters 3 and 4 are implemented and presents some experimental comparison between the two receiving models. Chapter 6 - Conclusion - concludes the dissertation and presents some hints for further work. 10 CHAPTER 2. BACKGROUND part is being evaluated, app2v1 , which contains the evaluated function and waits for the argument to be evaluated, or call , a frame without arguments that is not operationally meaningful, but used to mark a point where a function returns. Each state is represented by a context carrying linear propositions: comp ( f ), where f is a frame, followed by either a eval ( e ), representing an expression to be evaluated, return ( v ), which represents a value being returned, and bind X Y , that can either be used to associate the parameter X with argument Y or to look up the associated value of a parameter in the course of an evaluation. These linear propositions can be made persistent by prefixing the proposition with a !. Figure 2.5 presents the rules for this case. More comprehensive examples are presented by Pfenning and Simmons [23] , in their original formulation. eval(X D)⊗!bind X V ({return(V D)} eval((λx.e x)D)({return((λx.e x)D)} eval((app e1e2)D)({∃d1.comp((app1e2)D d1)⊗eval(e1d1)} comp((app1e2)D D1)⊗return(v1D1)({∃d2.comp((app2v1)D d2)⊗eval(e2d2)} comp((app2(λx.e x)) D D2⊗return(v2D2)({∃y.∃d0.comp(call D d0)⊗ eval((e y)d0)⊗!bind y v2} comp(call D D0)⊗return(V0D0)({return(V0D)} Figure 2.5: SSOS rules for the untyped λ-calculus. We use Ω → Ω 0 to refer to a single rewrite, from state Ωto state Ω 0 . We write →n to denote a sequence of nsteps and →+as the transitive closure of →. 2.4 Performance Measures in Parallel Algorithms Throughout this document we analyze the time complexity of implemented algorithms using the work-span model [ 9 ]. As the name suggests, this model uses the concepts of work and span, also dubbed depth [ 4 ] in some literature, to characterize the time complexity of an algorithm as a function of the number of processes used to run it. In simple terms, work measures the time used to run the computation on a single 2.4. PERFORMANCE MEASURES IN PARALLEL ALGORITHMS 11 processor, whereas span is defined as the time required to run the program on a theoretical machine with an unbounded number of processors. In a more detailed explanation of this model, we can view a multithreaded computation as a directed acyclic graph, called a computational dag. The vertices of the dag represent instructions and the edges encode dependencies between instructions. Chains of one or more instructions without parallel control are grouped in strands. Parallel control is represented in the structure of the graph, for example, a strand with multiple successors indicates that new threads have been spawned. Taking this definition of computation, we can describe work as the sum of the time taken by each strand and span as the longest time to execute the strands along any path in the graph. In other words, span can be seen as the critical path in graph. During the experimental evaluation of the algorithms, we also use the speedup measure. Although usually defined as the ratio between the running time using 1 processor and P processors, we use it as a comparison between the two implemented models, blocking and non-blocking. Chapter 3 Imperative Programming with Sessions Types 3.1 Introduction This chapter introduces the main concepts of programming with Concurrent C0 (CC0). For a more in-depth description of CC0, we refer the reader to the original paper [ 30 ]. C0 [ 21 ] is an imperative programming language, closely resembling C, with the goal of having fully specified semantics that avoid C’s undefined behaviour [ 1 ]. It is used in Carnegie Mellon University to learn the basics of imperative algorithms and data structures and compiler design. Its main features are: dynamically checked contracts (for example, @requires,@ensures,@asserts and @loop_invariant); complete memory distinction by separating pointers from arrays; and a garbage collector, which eliminates the need to free memory. C0 is compiled to C, generating human-readable code that is sent to a C compiler. CC0 is a session-typed concurrent extension of C0. Its typing system is derived from the Curry-Howard interpretation of linear propositions as types, proofs as processes, and cut reduction as computation, which we mentioned in Section 2.2. 13 14 CHAPTER 3. IMPERATIVE PROGRAMMING WITH SESSIONS TYPES 3.2 Concurrent C0 A program in CC0 is a collection of processes exchanging messages through channels. These processes are spawned by functions that return channels. The process that calls these spawning functions is called the client. The new process at the other end of the channel is called the provider, who is said to offer a session over the channel. A process is the provider of only one channel, but may be the client of multiple ones. CC0’s channels have a linear semantics: there is exactly one reference to the channel besides the provider’s. This captures the behavior described in the previous paragraph: the process we called the client has the unique reference to the provided channel. Messages are sent asynchronously: processes advance in parallel without waiting for acknowledgement of the sent message being received. Programmers must specify the protocol of message exchange using session types and the linear type system enforces concordance with this protocol [22]. 3.2.1 Type Definition Session type declaration in CC0 is done using the choice keyword, in a syntax inspired by structs in C. The actual session is enclosed by <...> and we distinguish input from output by using a ? for input and a ! for output. Internal and external choices are also discriminated by prefixing the keyword choice with ? for external choice and ! for internal. An empty < > indicates the end of a session. Programs 3.1 and 3.2 illustrate how session types are defined in CC0. In the example of the queue, the choice named queue is a choice between labels Enq , Deq , IsEmpty and Dealloc . It is only used after an output prefix ( ? ), which means it always represents an external choice, made by the client and sent to the provider of the queue interface. In contrast, the choice queue_elem is an internal choice (always prefixed by ! ), which means the provider has to send label None (no element in the queue) or Some (some element in the queue). The example of the binary search tree is similar, the choice tree is an external choice, expecting to receive the labels Insert , Find , Reduce and ToList . Receiving one of 3.2. CONCURRENT C0 15 choice queue { <?int ; ?choice queue> Enq ; <!choice queue_elem> Deq ; <! boo l ; ?choice queue> IsEmpty ; < > Dealloc ; }; choice queue_elem { <?choice queue> None ; <!int ; ?choice queue> Some ; }; typedef <?choice queue> queue ; Code 3.1: Protocol definition of a queue. choice l i s t { <!int ; ! choice l i s t > Cons ; < > Nil ; }; typedef <!choice l i s t > l i s t ; typedef int key ; typedef int reduce_fn ( int x , key k , int y ) ; choice t r e e { <?key ; ?choice tree > I n s e r t ; <?key ; ! bool ; ?choice tr ee > Find ; <?int ; ? reduce_fn ∗; ! int ; > Reduce ; <! l i s t ; > ToList ; }; typedef <?choice tr ee > t r e e ; Code 3.2: Protocol definition of a binary search tree. these labels induces a sequence of actions encoded by the session: an Insert is followed by receiving a key, which is simply an integer, and continuing as a tree ; a Find is trailed by receiving a key, sending a boolean value and continuing as a tree ; a Reduce is pursued by receiving an integer and a pointer, sending another integer and terminating; finally, receiving the label ToList leads to sending a list and terminating. On the other hand, the choice list is an internal choice, either sending the label Cons , if there is an element in the list, or Nil, otherwise. The protocols exchange messages in two directions, from the client process to the provider process and vice-versa, resulting in each direction being conveyed independently through an external (queue and tree) and internal choice (queue_element and list). 16 CHAPTER 3. IMPERATIVE PROGRAMMING WITH SESSIONS TYPES The session type is given from the provider’s perspective, the client adhere’s to the dual of the type: if the provider executes a receiving action, the client executes a sending one. The compiler determines statically if the operations indicated in the protocol are fulfilled in the correct order with the fitting type akin to the channel’s session type. 3.2.2 Protocol Implementation CC0 offers two distinct categories of functions: ones that return a basic type ( int , etc.) and others that return a channel typed by a session type. The latter implements the interfaces, which could be any session type, as explained in the previous section. Programs 3.3 and A.1 show the functions that implement the types defined in Programs 3.1 and 3.2. To improve readability, we only present the code for binary search trees in Appendix A. The function empty implements the behaviour of the process that represents the end of the queue, which does not hold any element. The instruction switch ($q) implements the behaviour of an external choice, making $q wait on the reception of a label. Each label has its own case, implementing the behaviour expected of an empty queue: • When receiving the label Enq , which adds a new element to the queue, a new empty queue process is spawned, through the instruction queue $e = empty() . The new element to the queue is received using the instruction int y = recv($q) . The former empty queue now continues as a process holding one element, through the instruction $q = elem(y, $e). • If a dequeue is requested (label Deq ), it sends the label None (using the instruction $q.None), stating that the queue is empty. • When queried if it is empty (label IsEmpty ), the process returns the value true (through the instruction send($q, true)). • Upon receiving the label Dealloc , which requests the destruction of the queue, it simply closes the channel (close($q)). The function that implements a process holding an element, elem(x,$r) , has similar behaviour so we do not go into so much detail. We just point out how dequeueing 3.2. CONCURRENT C0 17 queue $q elem ( in t x , queue $r ) { switch ( $q ) { case Enq : in t y = recv ( $q ) ; $r . Enq ; send ( $r , y ) ; $q = elem (x , $r ) ; case Deq : $q . Some ; send ( $q , x ) ; $q = $r ; // forward requ es t case IsEmpty : send ( $q , f a l s e ) ; $q = elem (x , $r ) ; case Dealloc : $r . Dealloc ; wait ( $r ) ; c l o s e ( $q ) ; } } queue $q empty () { switch ( $q ) { case Enq : in t y = recv ( $q ) ; queue $e = empty ( ) ; $q = elem (y , $e ) ; case Deq : $q . None ; $q = empty ( ) ; case IsEmpty : send ( $q , true ) ; $q = empty ( ) ; case Dealloc : c l o s e ( $q ) ; } } Code 3.3: Implementation of a queue with constant time enqueue and dequeue operations from the client’s perspective. 18 CHAPTER 3. IMPERATIVE PROGRAMMING WITH SESSIONS TYPES an element works in this implementation: after receiving the label Deq , the process sends the label Some , stating that there is at least one element in the queue, followed by that element (instruction send($q, x) ). It then executes a forward ( $q = $r ), terminating the process. Linearity ensures that a parent process cannot terminate while it has running children, all references must be completely consumed. CC0 introduces the operation called forwarding [ 30 ], which allows a process to terminate before its children. In cases where a given node has exactly one child and it is offering a channel with the same session type as its child, if this node has no more work to do, it can be terminated and contracted in a way that the parent node and the child node can communicate between themselves without the node in the middle. CC0 has the usual features of an imperative programming language, such as conditionals, loops, assignments and functions, extended by communication primitives. Figure 3.1 presents the core communication syntax. P, Q ::= $c=spawn(P) ; Qspawn |$c= $dforward |close($c)send end and terminate |wait($c) ; Qreceive end |send($c, e) ; Qsend data (including channels) |x=recv($c) ; Qreceive data (including channels) |$c.lab ;Qsend label |switch($c){labi→Pi}ireceive label Figure 3.1: Communication syntax of CC0 3.2.3 Target Language CC0 is compiled to a target language and linked with a runtime system, both written in C, responsible for implementing communication. The compiler checks if messages are being exchanged in the correct order, in agreement with the session type, and enforces linear use of channels. 3.3. OPERATIONAL SEMANTICS 19 Recall from Section 2.2.1, the session typing from CC0 uses polarised logic to maintain the direction of the communication. Positive polarity indicates that information is streaming from the provider and negative to the provider. A shift is used to swap polarities. The runtime system explicitly tracks the polarity of each channel and the compiler infers and inserts the minimal amount of shifts into the target language. This inference allows programmers to use CC0 without knowing about shifts at all. The target language adds two new instructions to the communication syntax of CC0, used to change the direction of communication. Figure 3.2 delineates the new instructions. P, Q ::= . . . |send($c, shift) ; Qsend a shift |shift =recv($c) ; Qreceive a shift Figure 3.2: Additional communication syntax for CC0’s target language 3.3 Operational Semantics The operational semantics for CC0 is expressed using a Substructural Operational Semantics (SSOS), first presented by Pfenning and Griffith [22] for an asynchronous version of SILL [ 27 ], a functional language. We here repurpose it for an imperative language, which requires us to extend it with variable state, using memory cells, local to each process. Refer to Section 2.2.1 for a very brief explanation of the theory behind the queue concept in the configuration, as well as the original sources for this theory. Configurations (Figure 3.3) describe executing processes, message queues connecting processes (one for each channel), and local storage cells. In this definition, proc ($ c, P ) Configurations Ω ::= · |queue($c, q, $d),Ω |proc($c, P),Ω |cell($c, x, v),Ω Figure 3.3: Configuration definition, using multiset notation. 26 CHAPTER 4. NON-BLOCKING RECEIVE Our alternative follows two principles. One, the difference should be invisible to the programmer who should not need to know exactly when a message is received. Second, the implementation still needs to adhere to the protocol defined by the session type, which forces the order of sends and receives. Our model involves postponing reception as much as possible, by interpreting receives as a request for a message. The request is saved on the channel until a synchronization is necessary. A synchronization is triggered when some data contained on any of the requests is required to continue execution. For example, if a process requested a shift from a channel, a synchronization is required to correct the polarity of the channel, that is, drain the message queue in order to change the direction of communication using the same queue. The requests are handled in the order they were made, which guarantees that the session type is still being respected. Furthermore, all these changes only occur in an intermediate language, allowing CC0 to keep the same source-level syntax. Figure 4.1 presents the new constructs used to introduce this non-blocking model into the target language. P, Q ::= . . . |async_wait($c); Qrequest an end |x=async_recv($c); Qrequest data |shift =async_recv($c); Qrequest a shift |sync($c, x); Qsynchronize variable |sync($c, shift); Qsynchronize shift |sync($c, end); Qsynchronize end Figure 4.1: Non-blocking syntax for CC0’s target language Programs 4.1 and A.2 present the non-blocking versions of a queue and a binary search tree (in appendix A), respectively. They are presented in a simplified version target language, where shifts are included but without the heavy syntax introduced by the compilation to C. More details on this difference can be found in Chapter 5, where we present the implementation of this system, using the actual low level syntax of the target language. 4.2. NON-BLOCKING RECEIVE 27 queue $q elem ( int x , queue $r ) { switch ( $q ) { case Enq : int y = async_recv($q ); $r . Enq ; sync ( $q , y ) ; send ( $r , y ) ; $q = elem (x , $r ) ; case Deq : s h i f t = async_recv ( $q ) ; sync ( $q , s h i f t ) ; $q . Some ; send ( $q , x ) ; send ( $q , s h i f t ) ; $q = $r ; // forward re q u e st case IsEmpty : s h i f t = async_recv ( $q ) ; sync ( $q , s h i f t ) ; send ( $q , f a l s e ) ; send ( $q , s h i f t ) ; $q = elem (x , $r ) ; case Dealloc : s h i f t = async_recv ( $q ) ; $r . Dealloc ; send ( $r , s h i f t ) ; async_wait($r ); sync ( $r , end ) ; sync ( $q , s h i f t ) ; c l o s e ( $q ) ; } } queue $q empty ( ) { switch ( $q ) { case Enq : int y = async_recv($q ); queue $e = empty ( ) ; sync ( $q , y ) ; $q = elem (y , $e ) ; case Deq : s h i f t = async_recv ( $q ) ; sync ( $q , s h i f t ) ; $q . None ; send ( $q , s h i f t ) ; $q = empty ( ) ; case IsEmpty : s h i f t = async_recv ( $q ) ; sync ( $q , s h i f t ) ; send ( $q , true ) ; send ( $q , s h i f t ) ; $q = empty ( ) ; case Dealloc : s h i f t = async_recv ( $q ) ; sync ( $q , s h i f t ) ; c l o s e ( $q ) ; } } Code 4.1: Non-blocking implementation of a queue, in CC0’s simplified target language. 28 CHAPTER 4. NON-BLOCKING RECEIVE 4.3 Cost Semantics The new non-blocking model introduces changes in both operational semantics and cost semantics. We present only the latter, which includes the changes to the former. Recall from Section 3.3.1, our definition of configuration has three predicates: proc ($ c, P, s, w ) represents a process offering along channel $ c , executing program P , with span s and work w ; queue represents the message queue, connecting two processes; and cell ($ c, x, v ) holds the state of variable xwith value v, in the process offering along channel $c. This definition of configuration needs to be updated, modifying the queue predicate to include the queue of requests. The new configuration and the definition of queue of requests are shown in Figure 4.2. Configurations Ω ::= · |queue($c, q, $d, r),Ω |proc($c, P, s, w),Ω |cell($c, x, v),Ω Request queue r::= · | x·r|end |shift Figure 4.2: Definitions of configuration in a non-blocking environment and the request queue. We define a receive request to increase both span and work by one unit. Upon synchronising any request, the span must also be synchronized with the value carried by the message. As before, during the synchronization, any end or fwd message requires the addition of the work contained in the message to the work of the receiving process. Table 4.1 presents the rules for the new instructions added with the non-blocking receive model. The rules for the other instructions remain unchanged. label_r:proc($e, switch($c){labi→Pi}, s, w)⊗queue($c, ←−−−−−−−−−−− (labj, s1, w1)·q, $d, ·) ({proc($e, Pj,max(s, s1)+1, w + 1) ⊗queue($c, ←− q , $d, ·)} data_async_r:proc($e, x =async_recv($c) ; Q, s, w)⊗queue($c, ←− q , $d, r) ({∃x. proc($e, Q, s + 1, w + 1) ⊗queue($c, ←− q , $d, r ·x)} shift_async_r:proc($e, shift =async_recv($c) ; Q, s, w)⊗queue($c, ←− q , $d, r) ({proc($e, Q, s, w)⊗queue($c, ←− q , $d, r ·shift)} wait_async :proc($e, async_wait($c) ; Q, s, w)⊗queue($c, ←− q , $d, r) ({proc($e, Q, s + 1, w + 1) ⊗queue($c, ←− q , $d, r ·end)} 4.3. COST SEMANTICS 29 sync_data 1 :proc($e, sync($c, x) ; Q, s, w)⊗queue($c, ←−−−−−−−−− (v, s1, w1)·q, $d, y ·r) ({proc($e, sync($c, x) ; Q, max(s, s1), w)⊗queue($c, ←− q , $d, r)⊗cell($e, y, v)} sync_data 2 :proc($e, sync($c, x) ; Q, s, w)⊗queue($c, ←−−−−−−−−− (v, s1, w1)·q, $d, x ·r) ({proc($e, Q, max(s, s1), w)⊗queue($c, ←− q , $d, r)⊗cell($e, x, v))} sync_shift 1 :proc($e, sync($c, shift) ; Q, s, w)⊗queue($c, ←−−−−−−−−− (v, s1, w1)·q, $d, y ·r) ({proc($e, sync($c, shift) ; Q, max(s, s1), w)⊗queue($c, ←− q , $d, r)⊗cell($e, y, v)} sync_shift 2 :proc($e, sync($c, shift) ; Q, s, w)⊗queue($c, ←−−−−−−−−− (shift, s1, w1),$d, shift) ({proc($e, Q, max(s, s1), w)⊗queue($c, −→ ·,$d, ·)} sync_wait 1 :proc($e, sync($c, end) ; Q, s, w)⊗queue($c, ←−−−−−−−−− (v, s1, w1)·q, $d, y ·r) ({proc($e, sync($c, end) ; Q, max(s, s1), w)⊗queue($c, ←− q , $d, r)⊗cell($e, y, v)} sync_wait 2 :proc($e, sync($c, end) ; Q, s, w)⊗queue($c, ←−−−−−−−− (end, s1, w1),$d, end) ({proc($e, Q, max(s, s1), w +w1)} sync_fwd :proc($e, sync($c, X) ; Q($c), s, w)⊗queue($c, ←−−−−−−−− (fwd, s1, w1),$d, r)⊗queue($d, ←− q , $f, ·) ({proc($e, sync($d, X) ; Q($d),max(s, s1), w +w1)⊗queue($d, ←− q , $f, r)} Table 4.1: Operational and cost semantics rules for the non-blocking receive model. The non-blocking receiving rules, data_async_r , shift_async_r and wait_async , simply add a new request to the request queue, independently of what is currently in the message queue. The rule data_async_r , which is receiving data on a variable, also needs to bind this variable, through the existential quantifier ∃. From a cost point of view, these rules only induce an increase of one unit in both span and work, except shift_async_r who deals with a shift so does not change these metrics, as discussed previously. The synchronization rules possess two cases each. Since the requests are stored in the queue, and to preserve the order of messages, if we are synchronizing a variable but there are other requests before that variable, these need to be handled first. A synchronization is only successful when the message is present in the message queue, and the type of this message must match the type of the request. This means that, if, for example, we are synchronizing a variable, we cannot get a message with a shift , end or a label. Synchronizing a shift or end empties the request queue completely, due to the nature of these operation: if we synchronize a shift , then we will start sending; if we synchronize a end , then we will close that client channel. This matches the behavior of the rules shift_rand wait from Table 3.1. 30 CHAPTER 4. NON-BLOCKING RECEIVE Looking at synchronization from the perspective of the cost semantics, synchronizing always requires us to also synchronize the span of the process with the one from message. If a process is synchronizing a end request, the work carried by the message is added to the process’ work, otherwise the work of the process is unchanged. When synchronizing, it is possible that a fwd message is received from the queue. When this happens, the queue of requests is moved to the queue predicate of the new client channel. The cost of this operation is equal, in both work and span, to the cost of synchronizing a end. We also repeated the rule to receive a label, which, operationally, does not suffer any change, but we want to emphasize that this rule requires an empty queue of requests to be successful. Receiving a label induces a change in the instructions to be executed, so we opted to keep it as a blocking function. Alternatively, we could have changed it to a non-blocking functions, but it would need to always follow this sequence of instructions: label = async_recv($c); sync($c, label) . As a consequence of receiving a label using a blocking function, to preserve the order of messages received, we need to completely synchronize the channel before receiving a label. 4.4 Translation Previously in this chapter, we have mentioned that, to accomplish our non-blocking model, we introduced a new set of instructions. To establish the connection between CC0’s target language and our modified one, we developed a translation from the former to the latter. We represent this translation using the [[]] notation. The translation is applied independently to each function in the whole program. Our translation uses an auxiliary table of requests, σ , to determine where to include the synchronization functions. This table is local to each process, it is a list of pairs, [( X, $ d )], where $ d is the channel to which the request was done and X is either a variable, shift or end . The way this table is built is clarified by the rules in Table 4.2, but consider the example of the non-blocking reception of a value, through the instruction x = async_recv($d) . This instruction would add the pair ( x, $ d )to the end of the table of requests, which conceptually works as a queue, similar to the request queue of the operational semantics. 4.4. TRANSLATION 31 Our translation function, [[]] , takes as an argument a pair, ( Instruction, σ ), and returns a new sequence of instructions and a new table of requests. Instruction represents not only communication syntax but also flow control directives and an artificial no operation instruction, which is simply skipped by the runtime environment. The rules for the translation are included in Table 4.2. The definitions of all the auxiliary functions are presented in Appendix B. We use the operator ∪, borrowed from set notation, to represent union of two lists of requests. The list on the right side of the operator is appended to the list on left and repeated tuples are removed. We also use the set difference operator, \ , to remove the pairs of the list of requests on the right from the list on left. receive-shift: [[(shift =recv($d), σ)]]=(shift =async_recv($d), σ ∪[(shift,$d)]) receive-value: [[(x=recv($d), σ)]]=(x=async_recv($d), σ ∪[(x, $d)]) wait: [[(wait($d), σ)]]=(async_wait($d), σ ∪[(end,$d)]) receive-label: [[(switch($d){labi→Pi}, σ)]]=(sync_instructions ;switch($d){labi→P0 i},S i∈I σi) wherel=check_shift σ$d (sync_instructions, σ0) = generate_sync l σ (P0 i, σi)=[[(Pi, σ0)]] spawn: [[($d=f(args), σ)]]=(sync_instructions ; $d=f(args), σ0) whereli=check_arg σargi (sync_instructions, σ0) = generate_sync (S i∈I li)σ close: [[(close($d), σ)]]=(sync_instructions ;close($d),[]) wherel=sync_all σ (sync_instructions, σ0) = generate_sync l σ send-exp: [[(send($d, e), σ)]]=(sync_instructions ;send($d, e), σ0) wherel1=check_shift σ$d l2=check_exp σ e (sync_instructions, σ0) = generate_sync (l1∪l2)σ send-shift: [[(send($d, shift), σ)]]=(sync_instructions ;send($d, shift), σ0) wherel=check_shift σ$d (sync_instructions, σ0) = generate_sync l σ send-label: [[($d.lab, σ)]]=(sync_instructions ; $d.lab, σ0) wherel=check_shift σ$d (sync_instructions, σ0) = generate_sync l σ forward: [[($d= $e, σ)]]=(sync_instructions ; $d= $e, []) wherel=sync_all σ (sync_instructions, σ0) = generate_sync l σ 32 CHAPTER 4. NON-BLOCKING RECEIVE sequence: [[(P;Q, σ)]]=(P0;Q0, σ00) where(P0, σ0) = [[(P, σ)]] (Q0, σ00) = [[(Q, σ0)]] assignment: [[(x=e, σ)]]=(sync_instructions ;x=e, σ) wherel1=check_exp σ x l2=check_exp σ e (sync_instructions, σ0) = generate_sync (l1∪l2)σ if: [[(if (b)then Pelse Q, σ)]]=(sync_instructions ;if (b)then Pelse Q, σ1∪σ2) wherel=check_exp σ b (sync_instructions, σ0) = generate_sync l σ (P0, σ1) = [[(P, σ0)]] (Q0, σ2) = [[(Q, σ0)]] while : [[(while (b)do P, σ)]]=(sync_instructions ;while (b)do P0, σ2) wherel=check_exp σ b (sync_instructions, σ0) = generate_sync l σ σ1=loop_carried_req P σ0 (P0, σ2) = [[(P, σ0∪σ1)]] func: [[(f(args), σ)]]=(sync_instructions ;f(args), σ0) whereli=check_arg σ argi l0=check_waits σ (sync_instructions, σ0) = generate_sync (S i∈I li)∪l0σ if σ06={} then recurse f σ0 Table 4.2: Translation scheme from blocking to non-blocking versions. To translate a receive-value, a receive-shift or a wait, there is no synchronization needed, the first is a consequence of defining the receive rule to bind a new variable. The functions async_recv and async_wait produce a request so we have to include a pair in the table of requests, indicating both the variable or message type and the channel tied to the request. In contrast to the other receives, receiving a label requires us to check first if the channel is ready (through check_shift ), to ensure that messages arrive in the order specified by the session type. It recursively calls the translation function to each case and returns a request table that is the union of the tables returned by each case , which is relevant for recursive session types that may carry requests from one iteration to the next. 4.4. TRANSLATION 33 The translations for close and forward are equal. To close a channel we need to synchronize it and all its clients, so sync_all generates a list with a number of pairs equal to the number of requests in σ . The auxiliary function generate_sync takes this list and returns the minimum sequence of instructions needed to synchronize the channel. If there is no need to perform any synchronization, generate_sync produces the no operation instruction we mentioned as part of the definition of Instruction. The translation of a spawn instruction simply needs to check if any argument needs to be synchronized, by applying the auxiliary function check_arg to each argument. The sending functions are all similar, they need to check if the channel is in the correct direction and, in the case of send-expression, the variables in the expression are all synchronized. There are two cases for the translation of an assignment, we presented only the most general one. An assignment can either be bounding or not, the rule presented in Table 4.2 is relative to the non-bounding case. Since x may not be a new variable, it might have a request pending on its value, thus we need to check it for requests, in addition to the expression. On flow control instructions, the translation is applied recursively. If it is a while loop, we need to be mindful of loop carried requests, which requires us to go over the body of the loop twice. The function loop_carried_req determines the table of requests after the execution of P, which is then passed as argument for the recursive translation of P. Recall that CC0 possesses two types of functions: one that returns a basic data type, such as int , and others that return a channel. The translation of the former is a special case of the assignment, the latter can also be divided in two cases. The first is spawning a new process, which we already mentioned, and the second is changing the context of the current process by entering a new function that returns a channel of the same type, corresponding to the rule func in Table 4.2. Changing the context of the function, requires that all the arguments are synchronized, because references to variables declared locally are lost when swapping to a new procedure. This is also the case for client channels that are waiting to be terminated. This is handled by the auxiliary function check_waits , that sifts through the requests to find a wait request. Any open client channels are passed on to the new function, including ones with pending requests, which do not need to be synchronized beforehand. 34 CHAPTER 4. NON-BLOCKING RECEIVE If there is any pending request, the translation is applied recursively to this new function, with the non-empty table of requests given as argument, through the auxiliary function recurse . This auxiliary function calls another translation function with rules very similar to the ones presented in this section but with the difference that it only consumes requests and does not generate them, stopping when the table of requests is empty. The recursive call is applied to the already-translated version of the other function. 4.5 Impact of Non-Blocking Receive In this section, we discuss some properties about our non-blocking model. We argue that the span of any process in a blocking configuration is greater or equal than the correspondent process in the non-blocking configuration. We also claim that the total work of a blocking configuration is equal to the work of the non-blocking configuration. Both these results are included in Theorem 1. Throughout this section, we will assume that all computations are terminating, satisfying both global and local progress. As a general rule, when we want to note explicitly that we are referring to a process in a non-blocking context, we use the translation notation, [[]] . So, for example, when writing non-blocking operational semantics’ transitions, we use proc ( [[$c]],[[P]], s, w )to contrast with the blocking operational semantics, which would be written as proc($c, P, s, w). We define the operator ∈ for processes and configurations as: $ c∈ Ω = ⇒ ∃proc ($ d, P, s, w)∈Ω.$c= $d. Definition 1 We define a predicate, messages (Ω), which, given a configuration, returns a list of all messages inside a queue of messages, in each queue predicate in the configuration Ω. Definition 2 Given a configuration Ω, we define work (Ω) as the sum of the work of all processes in the configuration and the sum of the work carried by each message whose data is end or fwd: work(Ω) = P proc($c,P,w$c)∈Ω w$c+P m∈messages(Ω) work(m)if data(m) = end ∨data(m) = fwd 0otherwise 4.5. IMPACT OF NON-BLOCKING RECEIVE 35 Definition 3 Given a blocking configuration, Ω, and its non-blocking correspondent, [[Ω]] , we define: span ( [[Ω]] ) ≤span (Ω) if and only if ∀proc ($ c, P, s$c, w$c ) ∈ Ω.∃proc([[$c]],[[P]], s[[$c]], w[[$c]])∈[[Ω]]. s[[$c]] ≤s$c. We define an inverse function of the translation, called pgr_readback , that compiles a non-blocking program to a blocking one. The rules of this inverse compilation are presented in Table 4.3. They are, mostly, the identity function, with the exception of requests, which are compiled to the blocking counterparts, and synchronizations, who are replaced by a new skip rule. We extend the blocking semantics with an artificial skip rule, used only on the following proofs. Executing a skip changes neither the span nor the work of a process, and the process does not interact with any message queues. receive-shift: pgr_readback(shift =asyncrecv($d))=shift =recv($d) receive-value: pgr_readback(x=async_recv($d))=x=recv($d) wait: pgr_readback(async_wait($d))=wait($d) receive-label: pgr_readback(switch($d){labi→Pi)=switch($d){labi→P0 i} whereP0 i=pgr_readback(Pi) spawn: pgr_readback($d=f(args))=$d=f(args) close: pgr_readback(close($d))=close($d) send-expression:pgr_readback(send($d, e))=send($d, e) send-shift: pgr_readback(send($d, shift))=send($d, shift) send-label: pgr_readback($d.lab)=$d.lab forward: pgr_readback($d= $e)=$d= $e sequence: pgr_readback(P;Q)=P0;Q0 whereP0=pgr_readback(P) Q0=pgr_readback(Q) assignment: pgr_readback(x=e)=x=e if: pgr_readback(if (b)then Pelse Q)=if (b)then P0else Q0 whereP0=pgr_readback(P) Q0=pgr_readback(Q) while : pgr_readback(while (b)do P)=while (b)do P0 whereP0=pgr_readback(P) func: pgr_readback(f(args))=f(args) sync: pgr_readback(sync($c, X))=skip Table 4.3: Readback scheme from non-blocking to blocking programs. 42 CHAPTER 4. NON-BLOCKING RECEIVE 2. s0 [[$c]] = max ( span ( [[m]] ) , s[[$c]] ), s0 $c = max ( span ( m ) , s$c ). By theorem hypothesis, span ( [[Ω1]] ) ≤span (Ω 2 ), so s[[$c]] ≤s$c and span ( [[m]] ) ≤span ( m ). It follows that s0 [[$c]] ≤s0 $cand span([[Ω0 1]]) ≤span(Ω0 2). •Case: Synchronization-value: proc([[$c]],sync([[$d]], x) ; Q, s[[$c]], w[[$c]])⊗queue([[$d]],←−−−− [[m]] ·q, [[$e]], x ·r) ({proc([[$c]], Q, s0 [[$c]], w0 [[$c]])⊗queue([[$d]],←− q , [[$e]], r)⊗cell([[$c]], x, data([[m]]))} is the transition in the non-blocking operational semantics, proc($c, skip ;pgr_readback(Q), s$c, w$c)⊗queue($d, q0,$e) ({proc($c, pgr_readback(Q), s0 $c, w0 $c)⊗queue($d, q0,$e)} is the transition in the blocking operational semantics. 1. w0 [[$c]] = w[[$c]] , so work ( [[Ω0 1]] ) = work ( [[Ω1]] ). w0 $c = w$c , so work (Ω 0 2 ) = work (Ω 2 ). By theorem hypothesis, work ( [[Ω1]] ) = work (Ω 2 ), so it follows that work([[Ω0 1]]) = work(Ω0 2). 2. s0 [[$c]] = max ( span ( [[m]] ) , s[[$c]] ), s0 $c = s$c . By theorem hypothesis, span ( [[Ω1]] ) ≤ span (Ω 2 ), so s[[$c]] ≤s$c , span ( [[m]] ) ≤span ( m ), m who was previously received by a blocking function, and s$c≥span ( m ). It follows that s0 [[$c]] ≤s0 $c and span([[Ω0 1]]) ≤span(Ω0 2). •Case: Synchronization-shift: proc([[$c]],sync([[$d]],shift) ; Q, s[[$c]], w[[$c]])⊗queue([[$d]],←−− [[m]],[[$e]],shift) ({proc([[$c]], Q, s0 [[$c]], w0 [[$c]])⊗queue([[$d]],−→ ·,[[$e]],·)} is the transition in the non-blocking operational semantics, proc($c, skip ;pgr_readback(Q), s$c, w$c)⊗queue($d, q0,$e) ({proc($c, pgr_readback(Q), s0 $c, w0 $c)⊗queue($d, q0,$e)} is the transition in the blocking operational semantics. 1. w0 [[$c]] = w[[$c]] , so work ( [[Ω0 1]] ) = work ( [[Ω1]] ). w0 $c = w$c , so work (Ω 0 2 ) = work (Ω 2 ). By theorem hypothesis, work ( [[Ω1]] ) = work (Ω 2 ), so it follows that work([[Ω0 1]]) = work(Ω0 2). 4.5. IMPACT OF NON-BLOCKING RECEIVE 43 2. s0 [[$c]] = max ( span ( [[m]] ) , s[[$c]] ), s0 $c = s$c . By theorem hypothesis, span ( [[Ω1]] ) ≤ span (Ω 2 ), so s[[$c]] ≤s$c , span ( [[m]] ) ≤span ( m ), m who was previously received by a blocking function, and s$c≥span ( m ). It follows that s0 [[$c]] ≤s0 $c and span([[Ω0 1]]) ≤span(Ω0 2). •Case: Synchronization-wait: proc([[$c]],sync([[$d]],end) ; Q, s[[$c]], w[[$c]])⊗queue([[$d]],←−− [[m]],[[$e]],end) ({proc([[$c]], Q, s0 [[$c]], w0 [[$c]])} is the transition in the non-blocking operational semantics, proc($c, skip ;pgr_readback(Q), s$c, w$c)⊗queue($d, q0,$e) ({proc($c, pgr_readback(Q), s0 $c, w0 $c)⊗queue($d, q0,$e)} is the transition in the blocking operational semantics. 1. w0 [[$c]] = w[[$c]] + work ( [[m]] )and data ( [[m]] ) = end , so work ( [[Ω0 1]] ) = work ( [[Ω1]] )+ work ( [[m]] ) −work ( [[m]] ) = work ( [[Ω1]] ). w0 $c = w$c , so work (Ω 0 2 ) = work (Ω 2 ). By theorem hypothesis, work ( [[Ω1]] ) = work (Ω 2 ), so it follows that work ( [[Ω0 1]] ) = work(Ω0 2). 2. s0 [[$c]] = max ( span ( [[m]] ) , s[[$c]] ), s0 $c = s$c . By theorem hypothesis, span ( [[Ω1]] ) ≤ span (Ω 2 ), so s[[$c]] ≤s$c , span ( [[m]] ) ≤span ( m ), m who was previously received by a blocking function, and s$c≥span ( m ). It follows that s0 [[$c]] ≤s0 $c and span([[Ω0 1]]) ≤span(Ω0 2). • There are three missing cases, assignments, conditionals and loops, whose operational rules we did not detail in this thesis. By assuming correctness, the evaluation of expressions will always yield the same value, so these rules will not change work nor span. Chapter 5 Implementation and Experimental Evaluation In this chapter, we discuss the low-level implementation of the concepts we presented in the previous chapters. Specifically, we delve into the real target language of CC0 and the runtime system that enables the session typed channels, as well as the changes to this runtime system to allow non-blocking reception. CC0’s target language is C and the runtime system is also written in C. Finally, we present some experimental results with the blocking and non-blocking semantics that were the basis for the ideas in Section 4.5. 5.1 Implementation We divide the implementation section in two parts, one for the existing blocking runtime and the other for our non-blocking one. In the first, we give an overview of how the existing blocking version of CC0 is implemented, presenting code of the most crucial functions and the ones we had to change to implement the non-blocking runtime. We also show how span and work are calculated in the runtime environment. The second part focuses on describing the modifications to the functions and structures on the first part to accomplish the non-blocking model. 45 46 CHAPTER 5. IMPLEMENTATION AND EXPERIMENTAL EVALUATION 5.1.1 Blocking Runtime The first functional runtime environment for CC0 was called concur2 [ 30 ]. This runtime has been optimized in more recent versions, but our work predates these newer, more efficient, implementations. The runtime uses the pthread library to enable parallelism in multi-core machines and each process in CC0 is mapped 1-to-1 to a pthread thread. Each process has a channel associated to it, which is the channel they provide, their unique identifier. This channel is represented by a struct , containing information about the message queue’s direction, the actual message queue and a pthread mutex and condition variable. These two are used to obtain mutual exclusivity on the queue: only one of the processes at the two end of the channel may write to the queue at a given time. Code 5.1 shows the declaration of this struct. struct channel { channel_dir_e queue_dir ; channel_dir_e provider_dir ; channel_dir_e c l i e n t _ d i r ; queue_t∗msgs ; pthread_mutex_t m; pthread_cond_t c ; }; Code 5.1: Channel structure. The direction of the queue is simply an enum structure in C, with the options TO_PROVIDER and TO_CLIENT. Spawning a process is done in the target language, each function that returns a channel has an associated spawning procedure that returns the reference of the channel to the client. Code 5.2 shows how a process running the empty function that implements the end of a queue is spawned. This function takes an argument n_clock *c , which is a structure used to track the span, work and number of processes spawned of a process, in this case, the client’s. We refer to this structure as clock in the rest of this chapter. The new process initialises the last two metrics start as 0, but span inherits the client’s span. This is done in lines 6 to 10 of Code 5.2. The function new_channel_negative is used to create a channel with a queue with negative polarity, but it simply calls the function new_channel 5.1. IMPLEMENTATION 47 1 queue empty_spawn( n_clock ∗c ) { 2 channel_t∗cid = new_channel_negative ( −1); 3 queue_p $q = provider_handle ( ci d ) ; 4 empty_args_t ∗empty_args = ( empty_args_t ∗) malloc ( sizeof(struct empty_args ) ) ; 5 empty_args−>$q = $q ; 6 n_clock ∗nc = ( n_clock ∗) malloc ( sizeof( n_clock ) ) ; 7 nc−>span = c−>span ; 8 nc−>work = 0 ; 9 nc−>nprocs_spawned = 0; 10 empty_args−>c = nc ; 11 spawn_process(&empty_unpack , ( void ∗) empty_args ) ; 12 c−>nprocs_spawned = ( c−>nprocs_spawned )+1; 13 return client_handle ( cid ) ; 14 } Code 5.2: Spawning a process running the empty function. (Code 5.3) with the correct capacity. This capacity is determined by the compiler, which calculates the type width of the session type of the channel. Type width is a property of certain session types that allow us to infer how many values may be buffered at any given time. Willsey et al. [30] offers a complete explanation on how type width is calculated in CC0. To summarize, a session type may be seen as a colored directed graph, with receiving nodes colored differently than sending ones. A walk in this graph is a possible sequence of sent or received types and the width of the type is the longest walk in the graph. If the graph possesses a cycle, then the width is infinite, represented by -1 . If this succeeds, the message queue is started with a minimum size and doubles its size every time the capacity is reached. 1static i n l i n e channel_t∗new_channel ( channel_dir_e dir , int capacity) { 2 channel_t∗chan = malloc ( sizeof( channel_t ) ) ; 3 a s s e r t ( chan ) ; 4 chan−>msgs = new_queue ( ca pacity ) ; 5 a s s e r t ( chan−>msgs ) ; 6 pthread_mutex_init(&chan−>m, NULL) ; 7 pthread_cond_init(&chan−>c , NULL) ; 8return chan ; 9 } Code 5.3: Creating a new channel in concur2. Messages in CC0 are also a C struct (Code 5.4), containing the type of the message, the clock and the value carried by the message, given by a union of several possible basic types. 48 CHAPTER 5. IMPLEMENTATION AND EXPERIMENTAL EVALUATION typedef struct { msg_type_e type ; n_clock ∗c ; union { int l a b e l ; int n ; bool b ; void∗p ; channel_t∗forward ; client_handle_t∗handle ; }; } channel_msg_t ; Code 5.4: Structure of a message. The procedure of swapping messages happens in four stages: the message is sent, packed, unpacked and, finally, received. The runtime concur2 provides a set of functions that discriminate both the channel to which the message is being sent or received (if it is the provider or a client) and the type of the message. These functions are similar to each other, so we only present the example of an integer, implemented by functions client_send_int , provider_send_int , client_recv_int and provider_recv_int . Code 5.5 clears the similarity between provider and client functions, so, in the rest of this chapter, we only show the examples for provider functions. The functions from Code 5.5 simply call more generic functions with the correct message type and update the clock. The actual sending and receiving are done by the function provider_send_msg and provider_recv_msg . Sending a message requires packing and enqueueing it, the implementation of which is orthogonal to our work. Receiving a message is presented in Code 5.6, where it is also shown an extract of the function used to unpack the message, demonstrating how span and work are synchronized. Referring to Code 5.6, lines 7 to 9 are responsible for blocking the program if the message we want to receive was not queued yet. The function queue_dequeue , in line 11, fetches the message from the queue. The function unpack_msg verifies if the expected type is equal to the type of the message and changes the return location (ret_loc) to point to the value carried by the message. Returning to our example of the queue, Program 5.7 presents the implementation of this data structure in the low-level blocking target language of CC0. We omit details 5.1. IMPLEMENTATION 49 int cli ent_ recv _int ( client_handle_t ∗c l i e n t , n_clock ∗c ){ int n ; client_recv_msg ( c l i e n t , INT , ( void∗ ∗ ) &n , c ) ; c−>work = ( c−>work )+1; c−>span = ( c−>span )+1; return n ; } int client_send_int(int n, client_handle_t∗c l i e n t , n_clock ∗c ){ c−>work = ( c−>work )+1; c−>span = ( c−>span )+1; return client_send_msg ( c l i e n t , INT , ( void∗) ( intptr_t ) n , c ) ; } int provi der_r ecv_i nt ( provider_handle_t ∗provider , n_clock ∗c ){ int n ; provider_recv_msg ( p ro vi de r , INT , ( void∗ ∗ ) &n , c ) ; c−>work = ( c−>work )+1; c−>span = ( c−>span )+1; return n ; } int provider_send_int(int n, provider_handle_t∗provider , n_clock ∗c ){ c−>work = ( c−>work )+1; c−>span = ( c−>span )+1; return provider_send_msg ( prov id er , INT , ( void∗) ( intptr_t ) n , c ) ; } Code 5.5: Send and receive functions of an integer, for provider and client channels. such as the spawn functions, which are all similar to Code 5.2, and pthread specific syntax needed to pass arguments to the functions that each process executes. 5.1.2 Non-blocking Runtime The main object of our non-blocking model is the request. It is represented by a struct , containing the type of the message requested, the return location and a boolean value indicating if the request has already been processed. This structure is realized in Code 5.8. The queue of requests discussed in Chapter 4 is stored in the channel structure. Each channel possesses a queue filled by the provider and another filled by the client, as well as variables to control the capacity and the next request to be handled. The queue of requests is not polarized like the queue of messages, so it requires this distinction between client and provider. The reason for this is the case when a process finishes sending and starts requesting right after. The process on the other end of the channel 50 CHAPTER 5. IMPLEMENTATION AND EXPERIMENTAL EVALUATION 1st a ti c int provider_recv_msg ( provider_handle_t ∗handle , 2 msg_type_e expected_type , void∗∗ ret_loc , n_clock ∗c ) { 3 channel_t∗chan = handle−>chan ; 4 pthread_mutex_lock(&chan−>m) ; 5 6 a s s e r t ( chan−>provider_dir == TO_PROVIDER) ; 7while (chan−>queue_dir != TO_PROVIDER | | queue_size ( chan−>msgs ) == 0) { 8 pthread_cond_wait(&chan−>c , &chan−>m) ; 9 } 10 channel_msg_t∗msg ; 11 a s s e r t ( queue_dequeue ( chan−>msgs , ( void∗∗)&msg ) == 0 ) ; 12 channel_t∗forward = unpack_msg(msg , expected_type , ret_loc , c ) ; 13 i f ( forward ) { 14 a s s e r t ( queue_size ( chan−>msgs ) == 0 ) ; 15 pthread_mutex_unlock(&chan−>m) ; 16 free_channel ( chan ) ; 17 handle−>chan = forward ; 18 return provider_recv_msg ( handle , expected_type , ret_loc , c ) ; 19 } 20 i f ( expected_type == SHIFT) { 21 a s s e r t ( queue_size ( chan−>msgs ) == 0 ) ; 22 chan−>provider_dir = TO_CLIENT; 23 } 24 pthread_mutex_unlock(&chan−>m) ; 25 return SUCCESS; 26 } 27 28 channel_t∗unpack_msg ( channel_msg_t∗msg , msg_type_e expected_type , 29 void ∗∗ ret_loc , n_clock ∗c ) { 30 a s s e r t (msg != NULL) ; 31 n_clock ∗c_recv = msg−>c ; 32 c−>span = ( c−>span ) > ( c_recv−>span )? ( c−>span ) : ( c_recv−>span ) ; 33 i f (msg−>type == FORWARD | | msg−>type == DONE) { 34 c−>work = ( c−>work ) + ( c_recv−>work ) ; 35 c−>nprocs_spawned = ( c−>nprocs_spawned ) + ( c_recv−>nprocs_spawned ); 36 } 37 // . . . . 38 } Code 5.6: Receiving a message in concur2. 5.1. IMPLEMENTATION 51 void empty ( queue_p $q , n_clock ∗c ) { switch ( p ro vi de r_ re cv _l ab el ( $q , c ) ) { case Enq : { int y = pro vider_r ecv_int ( $q , c ) ; queue $e = empty_spawn( c ) ; elem ( $q , y , $e , c ) ; } case Deq : { pr ov ider _r ecv _s hift ( $q , c ) ; provider_send_label (None , $q , c ) ; provider_send_shift($q, c); empty ( $q , c ) ; } case IsEmpty : { pr ov ider _r ecv _s hift ( $q , c ) ; provider_send_int ( true , $q , c ) ; provider_send_shift($q, c); empty ( $q , c ) ; } case Dealloc : { pr ov ider _r ecv _s hift ( $q , c ) ; provider_send_done ( $q , c ) ; } } } void elem ( queue_p $q , int x , queue $r , n_clock ∗c ) { switch ( p ro vi de r_ re cv _l ab el ( $q , c ) ) { case Enq : { int y = pro vider_r ecv_int ( $q , c ) ; client_send_label (Enq , $r , c ) ; client_send_int(y, $r , c); elem ( $q , x , $r , c ) ; } case Deq : { pr ov ider _r ecv _s hift ( $q , c ) ; provider_send_label (Some , $q , c ) ; provider_send_int(x, $q , c ); provider_send_shift($q, c); forward ( $q , $r , c ) ; } case IsEmpty : { pr ov ider _r ecv _s hift ( $q , c ) ; provider_send_int ( f a l s e , $q , c ) ; provider_send_shift($q, c); elem ( $q , x , $r , c ) ; } case Dealloc : { pr ov ider _r ecv _s hift ( $q , c ) ; client_send_label ( Dealloc , $r , c ) ; client_send_shift ( $r , c ) ; client_recv_done($r , c ); provider_send_done ( $q , c ) ; } } } Code 5.7: Implementation of a queue, in the low-level blocking target language of CC0. 58 CHAPTER 5. IMPLEMENTATION AND EXPERIMENTAL EVALUATION •bst implements an unbalanced binary search tree, used to sort an array of 7 elements. •insert-sort sorts an array of 6 elements, using insertion sort. •mergesort1 sorts an array of 6 elements using Fibonacci trees. •mergesort3 sorts an array of 6 elements using a bottom up strategy and binary trees. •mergesort4 sorts an array of 6 elements using traditional merge sort. •odd-even-sort1 sorts an array of 6 elements using original odd-even-sort. •odd-even-sort4 sorts an array of 6 elements, only the tail element counts down to 0 and each element swaps between right and left while the network is being built. •odd-even-sort6 sorts an array of 6 elements emphazising message swapping. •parfib calculates the eighth number of Fibonacci, using message swapping. •primes calculates the first 500 primes using a sequential prime sieve. •queue-notail , a queue of 3000 elements, with looping processes instead of tail recursion. •queue, a queue with 3000 elements, with processes executing tail recursion. •reduce executes a reduce operation on a tree with 1024 elements and each element is a leaf. •seg places 1000 elements in a segmented list and calculates their sum. •siege-eager is the implementation of an eager sieve of Erastothenes, calculates the 500th prime. •sieve-lazy implements a lazy version of the sieve of Erastothenes, calculating the 500th prime. •stack implements a stack of 2000 elements. 5.3. EXPERIMENTAL EVALUATION 59 bitstring1 bitstrings with external choice parfib parallel naive Fibonacci, simulating fork/join bitstring3 bitstrings with internal choice primes prime sieve (sequential) bst binary search trees, tree sort queue-notail queues without tail calls insert-sort insertion sort using a queue queue queues written naturally mergesort1 mergesort with Fibonacci trees reduce reduce and scan on parallel sequences mergesort3 mergesort with binary trees seg list segments mergesort4 mergesort with binary trees, sequential merge sieve-eager eager prime sieve merge odd-even-sort1 odd/even sort, v1 sieve-lazy lazy prime sieve odd-even-sort4 odd/even sort, v4 stack a simple stack odd-even-sort6 odd/even sort, v6 Table 5.1: CC0 benchmarking suite All benchmarks were run on a 2015 Macbook Pro, with a 2.7 GHz Intel Core I5 (2 cores) processor and 8 GB RAM. The detailed results are presented in Table 5.2. Figures 5.1 and 5.2 aggregate these results in a more friendly outlook, comparing span in the two models and the speedup when going from the blocking to the non-blocking model. Figure 5.1: Blocking and Non-Blocking span benchmarks on a log scale. Figure 5.2: Execution time speedup from Blocking to Non-Blocking Version. 60 CHAPTER 5. IMPLEMENTATION AND EXPERIMENTAL EVALUATION Program Version Span Work Number of Processes Execution time (ms) Speedup (Blocking Execution Time Non−Blocking Execution Time ) bitstring1 Blocking 3096 8084 11 12.69 0.96 Non Blocking 3072 8084 11 13.17 bitstring3 Blocking 1525 4016 501 9.39 0.78 Non Blocking 1525 4016 501 12.10 bst Blocking 109 259 37 0.76 0.80 Non Blocking 97 259 37 0.95 reduce Blocking 8191 12282 2047 239.80 1.87 Non Blocking 56 12282 2047 128.17 insertion-sort Blocking 54 96 7 0.24 0.89 Non Blocking 54 96 7 0.27 mergesort1 Blocking 73 215 53 0.93 0.76 Non Blocking 73 215 53 1.22 mergesort3 Blocking 46 155 15 0.33 0.83 Non Blocking 46 155 15 0.40 mergesort4 Blocking 11 30 15 0.25 0.83 Non Blocking 5 30 15 0.30 odd-even-sort1 Blocking 72 214 15 0.44 0.96 Non Blocking 70 214 15 0.46 odd-even-sort4 Blocking 76 280 15 0.46 0.96 Non Blocking 74 280 15 0.48 odd-even-sort6 Blocking 65 196 21 0.42 0.81 Non Blocking 62 196 21 0.52 parfib Blocking 26 268 67 1.20 1.04 Non Blocking 12 268 67 1.15 stack Blocking 14011 20012 2002 208.75 0.73 Non Blocking 14011 20012 2002 284.30 queue Blocking 27010 18024012 3001 9021.79 0.34 Non Blocking 27007 18024012 3001 26734.11 queue-notail Blocking 27010 18024012 3001 9161.20 0.36 Non Blocking 27007 18024012 3001 25184.28 seg Blocking 6007 12010 3004 252.43 0.79 Non Blocking 5005 12010 3004 319.15 prime Blocking 532192 532192 502 1376.44 0.73 Non Blocking 399144 532192 502 1894.44 sieve-lazy Blocking 60189 909998 7137 732.68 0.74 Non Blocking 59692 909998 7137 987.29 sieve-eager Blocking 2286 157738 26464 693.71 0.75 Non Blocking 2286 157738 26464 919.53 Table 5.2: Blocking and Non-blocking benchmarks 5.3. EXPERIMENTAL EVALUATION 61 Most of the examples across our benchmark suite bring about a small improvement to span, where reduce , mergesort4 , and parfib see the most noticeable ones. In the case of reduce , some of the difference could be recovered by fine-tuning the CC0 source program; it is interesting that our generic technique can make up for a performance bug (when considered under the blocking semantics) introduced by the programmer. This shows that, at the very least, our implementation can help identify some performance issues in the given code. As Figure 5.2 shows, the overhead of maintaining the request queue is considerable in some examples. Only in reduce and parfib do we realize an actual performance improvement. The queue examples show the most dire decrease in performance, which can be partially explained by the overhead on increasing the capacity of the request queues. Another possible explanation is the high amount of processes created for these two examples, which, with the overhead of the heavy requests queues, may not fit in memory, requiring data to be stored in the disk. As expected, both the number of processes spawned and the work is constant when going from the blocking to the non-blocking version. Chapter 6 Conclusion In this dissertation, we implemented a non-blocking model of receiving messages in Concurrent C0, a language based on a Curry-Howard correspondence between session types and linear logic. This model led to a new semantics of the language, a non-blocking semantics, opposed to the existing blocking one. We instrumented both these semantics to include costs on each operation, using the span and work model, which provide an abstract analytical measure of parallelism in the computation. We also defined a translation function from the original Concurrent C0 to our nonblocking extension and demonstrated some properties about our model, assuming correctness: • Span in a non-blocking configuration is always less or equal than the span on a blocking configuration. •Work is the same across both models. Finally, we executed an experimental evaluation of both models on a set of representative examples. We found that it is hard to reap the practical benefit of span’s improvement, as the overhead of the implementation of the data structures that support our model is too great to gain an increase in execution time. 63 64 CHAPTER 6. CONCLUSION 6.1 Future Work We would like to point out some possible future continuation to the work presented in this thesis: • A rigorous proof of Conjecture 1 to confirm correctness of our non-blocking model was not included in this thesis, although we presented a sketch of a possible proof. • Since recipient behavior on input is opaque to the sender, we may be able to craft an optimization, which avoids the slowdown in the common case where no improvement in the span is available. For this purpose, we would likely combine our fully dynamic technique with static dependency analysis to use non-blocking input only where promising. • Our cost semantics could be adapted as a tool in performance debugging, which may be helpful in particular to novice programmers with little experience in concurrency. • Our translation function has a working version, implemented in Haskell. However, it was not incorporated into the CC0 compiler, which is written in ML. • Finally, just as there is a connection between session types and intuitionistic linear logic and asynchronous communication and polarised logic, we suspect that there might be a connection between non-blocking asynchronous communication and some branch of logic. Bibliography [1] Arnold, R. (2010). C0, an imperative programming language for novice computer scientists. [2] Baker, Jr., H. C. and Hewitt, C. (1977). The incremental garbage collection of processes. In Proceedings of the 1977 Symposium on Artificial Intelligence and Programming Languages, pages 55–59, New York, NY, USA. ACM. [3] Balzer, S. and Pfenning, F. (2015). Objects as session-typed processes. In Proceedings of the 5th International Workshop on Programming Based on Actors, Agents, and Decentralized Control, AGERE! 2015, pages 13–24, New York, NY, USA. ACM. [4] Blelloch, G. E. (1996). Programming parallel algorithms. Commun. ACM, 39(3):85– 97. [5] Caires, L. and Pfenning, F. (2010). Session types as intuitionistic linear propositions. In Proceedings of the 21st International Conference on Concurrency Theory (CONCUR 2010), pages 222–236, Paris, France. Springer LNCS 6269. [6] Caires, L., Pfenning, F., and Toninho, B. (2016). Linear logic propositions as session types. Mathematical Structures in Computer Science, 26:367–423. [7] Cardelli, L. and Gordon, A. D. (2000). Mobile ambients. Theor. Comput. Sci., 240(1):177–213. [8] Cervesato, I. and Scedrov, A. (2009). Relating state-based and process-based concurrency through linear logic (full-version). Information and Computation, 207(10):1044 – 1077. Special issue: 13th Workshop on Logic, Language, Information and Computation (WoLLIC 2006). 65 66 BIBLIOGRAPHY [9] Cormen, T. H., Stein, C., Rivest, R. L., and Leiserson, C. E. (2001). Introduction to Algorithms, chapter 27. McGraw-Hill Higher Education, 2nd edition. [10] Curry, H. B., Feys, R., Craig, W., and Craig, W. (1958). Combinatory logic, vol. 1. North-Holland Publ. [11] DeYoung, H., Caires, L., Pfenning, F., and Toninho, B. (2012). Cut reduction in linear logic as asynchronous session-typed communication. [12] Dezani-Ciancaglini, M., de’Liguoro, U., and Yoshida, N. (2008). On Progress for Structured Communications, pages 257–275. Springer Berlin Heidelberg, Berlin, Heidelberg. [13] Friedman, D. P., David, and Wise, S. (1978). Aspects of applicative programming for parallel processing. IEEE Transactions on Computers, pages 289–296. [14] Gay, S. J. and Vasconcelos, V. T. (2010). Linear type theory for asynchronous session types. Journal of Functional Programming, 20(01):19–50. [15] Guenot, N. (2014). Session types, solos, and the computational contents of the sequent calculus. Talk at the Types Meeting. [16] Honda, K. (1993). Types for dyadic interaction. In 4th International Conference on Concurrency Theory, CONCUR’93, pages 509–523. Springer LNCS 715. [17] Honda, K., Vasconcelos, V. T., and Kubo, M. (1998). Language primitives and type discipline for structured communication-based programming. In 7th European Symposium on Programming Languages and Systems, ESOP’98, pages 122–138. Springer LNCS 1381. [18] Howard, W. A. (1995). The formulae-as-types notion of construction. [19] Laneve, C. and Victor, B. (2003). Solos in concert. Mathematical Structures in Computer Science, 13(5):657–683. [20] Milner, R. (1999). Communicating and Mobile Systems: the π -Calculus. Cambridge University Press. [21] Pfenning, F. and Arnold, R. (2010). C0 language. BIBLIOGRAPHY 67 [22] Pfenning, F. and Griffith, D. (2015). Polarized substructural session types. In Pitts, A., editor, Proceedings of the 18th International Conference on Foundations of Software Science and Computation Structures (FoSSaCS 2015), pages 3–22, London, England. Springer LNCS 9034. Invited talk. [23] Pfenning, F. and Simmons, R. J. (2009). Substructural operational semantics as ordered logic programming. In Logic In Computer Science, 2009. LICS ’09. 24th Annual IEEE Symposium on, pages 101–110. [24] Sangiorgi, D. and Walker, D. (2001). The π -Calculus: A Theory of Mobile Processes. Cambridge University Press. [25] Silva, M., Florido, M., and Pfenning, F. (2016). Non-blocking concurrent imperative programming with session types. In Proceedings of the 4th International Workshop on Linearity (LINEARITY’16). [26] Toninho, B., Caires, L., and Pfenning, F. (2012). Functions as session-typed processes. In Birkedal, L., editor, 15th International Conference on Foundations of Software Science and Computation Structures, FoSSaCS’12, pages 346–360, Tallinn, Estonia. Springer LNCS. [27] Toninho, B., Caires, L., and Pfenning, F. (2013). Higher-order processes, functions, and sessions: A monadic integration. In Proceedings of the 22Nd European Conference on Programming Languages and Systems, ESOP’13, pages 350–369, Berlin, Heidelberg. Springer-Verlag. [28] Wadler, P. (2012). Propositions as sessions. In ACM SIGPLAN Notices, volume 47, pages 273–286. ACM. [29] Wadler, P. (2015). Propositions as types. Commun. ACM, 58(12):75–84. [30] Willsey, M., Prabhu, R., and Pfenning, F. (2016). Design and implementation of concurrent c0. In Proceedings of the 4th International Workshop on Linearity (LINEARITY’16). 74 APPENDIX A. BINARY SEARCH TREE IMPLEMENTATIONS 139 } 140 } Code A.2: Non-blocking implementation of an unbalanced binary search tree, in CC0’s simplified target language. Appendix B Translation auxiliary functions We present three set of definitions. In Table B.1, we show the definitions of the auxiliary functions used in Table 4.2. Table B.2 showcases the rules to ascertain the loop-carried requests in a while cycle. Finally, Table B.3 handles the rules from recursive calls or calls to other functions. The rules in Tables 4.2, B.2 and B.3 are very similar. Table B.2 differs from the other two by not generating any instruction, simply updates and returns a new table. Table B.3 differs from Table 4.2 in the receive functions, who do not add a request to the table, and adds extra rules for synchronization functions, who remove requests from the table. The declaration of each function will appear with a type defined in Haskell style. For example, the translation function in Table 4.2 would be declared as: [[]] :: ( Instruction, [( String,Channel )]) → ( Instruction, [( String,Channel )]). To abbreviate, we define Table = [(String,Channel)]. check_exp :: Table →Exp →Table check_exp σ n =[] check_exp σ b =[] check_exp [] x=[] check_exp ((y, $c) : σ)x=if x=y then [(y, $c)] else check_exp σ x check_exp σ e1+e2=(check_exp σ e1)∪(check_exp σ e2) 75 76 APPENDIX B. TRANSLATION AUXILIARY FUNCTIONS check_shift :: Table →Channel →Table check_shift [] $d=[] check_shift ((y, $c) : σ) $d=if $c= $d∧y=shift then [(y, $c)] else check_shift σ$d check_wait :: Table →Channel →Table check_wait [] $d=[] check_wait ((y, $c) : σ) $d=if $c= $d∧y=end then [(y, $c)] else check_wait σ$d check_waits :: Table →Table check_waits [] =[] check_waits ((y, $c) : σ)=if y=end then [(y, $c)] ∪(check_waits σ) else check_waits σ check_arg :: Table →Exp →Table check_arg σ A=check_exp σ A check_arg :: Table →Channel →Table check_arg σ$d=check_wait σ$d sync_all :: Table →Table sync_all σ=σ aggr_reqs :: Channel →Table →Table aggr_reqs $c[] =[] aggr_reqs $c((x, $d) : l)=if $c= $d then (aggr_reqs $c l)∪[(x, $d)] else (aggr_reqs $c l) gen_instr :: Table →Instruction gen_instr ((x, $c) : l)=sync($c, x) gen_instr ((shift,$c) : l)=sync($c, shift) gen_instr ((end,$c) : l)=sync($c, end) rem_sync :: Table →Table →Table 77 rem_sync ((x, $c) : l) ((y, $d) : σ)=if $c6= $d then ((y, $d):(rem_sync ((x, $c) : l)σ)) else if y=x thenσ else rem_sync ((x, $c) : l)σ update_table :: Table →Table →Table update_table [] σ=σ update_table ((x, $c) : l)σ=σ0 wherel1=aggr_reqs $c((x, $c) : l) σ1=rem_sync l1σ σ0=update_table l\l1σ1 generate_sync :: Table →Table →(Instruction,Table) generate_sync [] σ=(NULL, σ) generate_sync ((x, $c) : l)σ=(sync1;syncr, σ0) wherel1=aggr_reqs $c((x, $c) : l) sync1=gen_instr l1 σ1=rem_sync l1σ (syncr, σ0)=generate_sync l\l1σ1 Table B.1: Auxiliary functions for the translation. In the check_exp function, we omitted the rules for every type of expression, there would be a case for each arithmetic and boolean operator. The generate_sync function requires some explanation. It receives as input a list of requests to be synchronized at that point, as well as the table of requests. Each channel in this list of requests is handled separately. First, we aggregate all the requests using a specific channel ( aggr_reqs function), putting the most recent request, which is the last to be handled, in the front of this new list, which contains requests only from one channel. We then generate a synchronization instruction ( gen_instr ) based on the first request of this list, note that, by synchronizing on the most recent request, all other earlier requests will also be synchronized. The table of requests is updated to remove these synchronized requests, and generate_sync is called recursively until there are no more requests to synchronize. 78 APPENDIX B. TRANSLATION AUXILIARY FUNCTIONS The update_table function behaves similarly to generate_sync but does not generate any instruction. It will be used as an auxiliary function on Table B.2. loop_carried_req :: Instruction →Table →Table loop_carried_req (shift =recv($d)) σ=σ∪[(shift,$d)] loop_carried_req (x=recv($d)) σ=σ∪[(x, $d)] loop_carried_req (wait($d)) σ=σ∪[(end,$d)] loop_carried_req (switch($d){labi→Pi})σ=S i∈I σi wherel=check_shift σ$d σ0=update_table l σ σi=loop_carried_req Piσ0 loop_carried_req ($d=f(args)) σ=σ0 whereli=check_arg σargi σ0=update_table (S i∈I li)σ loop_carried_req (close($d)) σ=[] loop_carried_req (send($d, e)) σ=σ0 wherel1=check_shift σ$d l2=check_exp σ e σ0=update_table (l1∪2)σ loop_carried_req (send($d, shift)) σ=σ0 wherel=check_shift σ$d σ0=update_table l σ loop_carried_req ($d.lab)σ=σ0 wherel=check_shift σ$d σ0=update_table l σ loop_carried_req ($d= $e)σ=[] loop_carried_req (P;Q)σ=σ00 whereσ0=loop_carried_req P σ σ00 =loop_carried_req Q σ0 loop_carried_req (x=e)σ=σ0 wherel1=check_exp σ x l2=check_exp σ e σ0=update_table (l1∪l2)σ loop_carried_req (if (b)then Pelse Q)σ=σ1∪σ2 wherel=check_exp σ b σ0=update_table l σ σ1=loop_carried_req P σ0 σ2=loop_carried_req Q σ0 79 loop_carried_req (while (b)do P)σ=σ1 wherel=check_exp σ b σ0=update_table l σ σ1=loop_carried_req P σ0 loop_carried_req (f(args)) σ=[] Table B.2: Definition of translation rules for while loops. We now present the rules for the recursive call of translation to a new function. We will only present the rules that suffer any change from their original definition. recurse :: Instruction →Table →(Instruction,Table) recurse (shift =recv($d)) σ=(shift =recv($d), σ) recurse (x=recv($d)) σ=(x=recv($d), σ) recurse (wait($d)) σ=(wait($d), σ) recurse (sync($d, x)) σ=(sync($d, x), σ1) where σ1=rem_sync [(x, $d)] σ recurse (sync($d, shift)) σ=(sync($d, shift), σ1) where σ1=rem_sync [(shift,$d)] σ recurse (sync($d, end)) σ=(sync($d, end), σ1) where σ1=rem_sync [(end,$d)] σ recurse (P;Q)σ=(P0;Q0, σ00) where(P0, σ0)=recurse P σ if σ0= [] then (Q0, σ00)=(Q, σ0) else (Q0, σ00)=recurse Q σ0 Table B.3: Definition of translation rules for function calls.