<html><head><meta http-equiv="Content-Type" content="text/html charset=utf-8"></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;" class="">Thanks for the feedback! Here is an updated version of the proposal:&nbsp;<a href="https://github.com/eeckstein/swift/blob/cow-proposal/docs/proposals/CopyOnWrite.rst" class="">https://github.com/eeckstein/swift/blob/cow-proposal/docs/proposals/CopyOnWrite.rst</a><div class="">(you can look at the history to see the changes compared to the previous version)<br class=""><div class=""><br class=""><div><blockquote type="cite" class=""><div class="">On Oct 11, 2016, at 7:57 PM, Michael Gottesman &lt;<a href="mailto:mgottesman@apple.com" class="">mgottesman@apple.com</a>&gt; wrote:</div><br class="Apple-interchange-newline"><div class=""><div class=""><blockquote type="cite" class="">----<br class=""><br class="">:orphan:<br class=""><br class="">.. highlight:: sil<br class=""><br class="">===================================<br class="">Copy-On-Write Representation in SIL<br class="">===================================<br class=""><br class="">.. contents::<br class=""><br class="">Overview<br class="">========<br class=""><br class="">This document proposes:<br class=""><br class="">- An ownership attribute to define copy-on-write (COW) buffers in Swift data<br class=""> &nbsp;types.<br class=""><br class="">- A representation of COW buffers in SIL so that optimizations can take benefit<br class=""> &nbsp;of it.<br class=""><br class="">The basic idea is to enable the SIL optimizer to reason about COW data types<br class="">in the same way as a programmer can do.<br class=""></blockquote><br class="">in the same way as a programmer can do =&gt; just as a programmer can.<br class=""><br class=""><blockquote type="cite" class=""><br class=""><br class="">This means: a COW buffer can only be modified by its owning SIL value, because<br class="">either it's uniquely referenced or the buffer is copied before modified.<br class=""></blockquote><br class="">modified =&gt; modification.<br class=""><br class=""><blockquote type="cite" class=""><br class="">.. note::<br class=""> &nbsp;&nbsp;&nbsp;In the following the term "buffer" refers to a Swift heap object.<br class=""> &nbsp;&nbsp;&nbsp;It can be any heap object, not necessarily a “buffer” with e.g. tail-allocated elements.<br class=""><br class="">COW Types<br class="">=========<br class=""><br class="">The basic structure of COW data types can be simplified as follows::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;class COWBuffer {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var someData: Int<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;...<br class=""> &nbsp;&nbsp;&nbsp;}<br class=""><br class=""> &nbsp;&nbsp;&nbsp;struct COWType {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var b : COWBuffer<br class=""><br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mutating func change_it() {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (!isUniquelyReferenced(b)) {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;b = copy_buffer(b)<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;b.someData = ...<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br class=""> &nbsp;&nbsp;&nbsp;}<br class=""><br class="">Currently the COW behavior of such types is just defined by their implementation.<br class="">But there is no representation of this special behavior in the SIL.<br class="">So the SIL optimizer has no clue about it and cannot take advantage of it.<br class=""><br class="">For example::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;func foo(arr : [Int]) {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;x = arr[0]<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;opaque_function()<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;y = arr[0] // can RLE replace this with y = x?<br class=""> &nbsp;&nbsp;&nbsp;}<br class=""><br class="">If opaque_function() wants to change the contents of the array buffer it first<br class="">has to copy it. But the optimizer does not know it so it has to conservatively<br class="">assume that opaque_function() will write to the location of arr[0].<br class=""><br class="">Copy-on-write Ownership Attribute<br class="">=================================<br class=""><br class="">This section proposes an ownership attribute to define a copy-on-write buffer.<br class=""><br class="">Swift Syntax<br class="">------------<br class=""><br class="">A COW buffer reference can be defined with a new ownership attribute for the<br class="">buffer variable declaration (similar to “weak” and “unowned”)::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;struct COWType {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;copy_on_write var b : COWBuffer<br class=""><br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// ...<br class=""> &nbsp;&nbsp;&nbsp;}<br class=""><br class="">The ``copy_on_write`` attribute is purely used for optimization purposes.<br class="">It does not change the semantics of the program.<br class=""><br class="">.. note::<br class=""><br class=""> &nbsp;“copy_on_write” is a &nbsp;working title. TODO: decide on the name.<br class=""> &nbsp;Maybe it should be a @-attribute, like @copy_on_write?<br class=""> &nbsp;Another question is if we should open this attribute for the public or just<br class=""> &nbsp;use it internally in the library, because violating the implied rules<br class=""> &nbsp;(see below) could break memory safety.<br class=""><br class="">Implementation<br class="">--------------<br class=""><br class="">The ``copy_on_write`` references can be represented in the AST as a special<br class=""></blockquote><br class="">"The" is not needed here I think.<br class=""><br class=""><blockquote type="cite" class="">``StorageType``, just like how ``unowned`` and ``weak`` is represented.<br class=""></blockquote><br class="">is represented =&gt; are represented.<br class=""><br class=""><blockquote type="cite" class="">The canonical type of a ``CopyOnWriteStorageType`` would be the referenced<br class="">buffer class type.<br class=""><br class="">In SIL the buffer reference will have type::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;$@sil_cow COWBuffer<br class=""><br class="">where ``COWBuffer`` is the type of the referenced heap object.<br class=""><br class="">Two conversion instructions are needed to convert from a ``@sil_cow`` reference<br class="">type to a regular reference type::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;cow_to_ref<br class=""> &nbsp;&nbsp;&nbsp;ref_to_cow<br class=""><br class="">Again, this is similar to ``ref_to_unowned`` and ``unowned_to_ref``.<br class=""><br class="">For example the SIL code for::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;var c: COWType<br class=""> &nbsp;&nbsp;&nbsp;let x = c.b.someData<br class=""><br class="">would be::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;%1 = struct_extract %1 : COWType, #COWType.b<br class=""> &nbsp;&nbsp;&nbsp;%2 = cow_to_ref %1 : $@sil_cow COWBuffer<br class=""> &nbsp;&nbsp;&nbsp;%3 = ref_element_addr %2 : $COWBuffer, #COWBuffer.someData<br class=""> &nbsp;&nbsp;&nbsp;%4 = load %3 : $*Int<br class=""><br class="">The ``ref_to_cow`` instruction is needed to store a new buffer reference into a<br class="">COW type.<br class=""><br class="">COW Buffers and the Optimizer<br class="">=============================<br class=""><br class="">A reference to a COW buffer gives the optimizer additional information:<br class=""><br class=""> &nbsp;*A buffer, referenced by a @sil_cow reference is considered to be immutable<br class=""> &nbsp;during the lifetime of the reference.*<br class=""><br class="">This means any address derived from a ``cow_to_ref`` instruction can be<br class="">considered to point to immutable memory.<br class=""><br class="">Some examples of optimizations which will benefit from copy-on-write<br class="">representation in SIL:<br class=""><br class="">- Redundant load elimination<br class=""><br class=""> &nbsp;RLE can assume that opaque code does not modify a COW buffer.<br class=""> &nbsp;Example::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%2 = cow_to_ref %1 : $@sil_cow COWBuffer<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%3 = ref_element_addr %2 : $COWBuffer, #someData<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%4 = load %3 : $*Int<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%5 = apply %foo() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// Cannot overwrite memory location %3<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%6 = load %3 : $*Int &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// Can be replaced by %4<br class=""><br class=""> &nbsp;Currently we do some ad-hoc optimizations for array, based on semantics,<br class=""> &nbsp;like array count propagation. These hacks would not be needed anymore.<br class=""><br class=""> &nbsp;Note that it’s not required to check if a ``cow_to_ref`` reference (or a<br class=""> &nbsp;projected address) escapes. Even if it escapes, it will reference immutable<br class=""> &nbsp;memory.<br class=""><br class="">- CSE, loop hoisting<br class=""><br class=""> &nbsp;Similar to RLE: the optimizer can assume that opaque code cannot modify a<br class=""> &nbsp;COW buffer<br class=""><br class="">- ARC optimization<br class=""><br class=""> &nbsp;Knowing that some opaque code cannot overwrite a reference in the COW buffer<br class=""> &nbsp;can remove retain/release pairs across such code::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%2 = cow_to_ref %1 : $@sil_cow COWBuffer<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%3 = ref_element_addr %2 : $COWBuffer, #someRef<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%4 = load_strong %3 : $*MyClass &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// Can do a load_strong [guarantee]<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%5 = apply %foo() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// Cannot overwrite someRef and dealloc the object<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// Use %4<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;destroy_value %4 : $MyClass<br class=""><br class="">Scoping instructions<br class="">--------------------<br class=""><br class="">To let the optimizer reason about the immutability of the COW buffer, it is<br class="">important to *bind* the lifetime of the buffer content to the lifetime of the<br class="">buffer reference. For example::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;%b1 = load %baddr : $@sil_cow COWBuffer &nbsp;// load the buffer reference<br class=""> &nbsp;&nbsp;&nbsp;// load something from %b1<br class=""> &nbsp;&nbsp;&nbsp;%a = apply %foo(%baddr : $@sil_cow COWBuffer)<br class=""> &nbsp;&nbsp;&nbsp;%b2 = load %baddr : $@sil_cow COWBuffer &nbsp;// load the buffer reference again<br class=""> &nbsp;&nbsp;&nbsp;// load something from %b2<br class=""><br class="">The question is: can RLE forward the load of the buffer reference and replace<br class="">``%b2`` with ``%b1``? It must not be able to do so if ``foo()`` modifies the<br class="">buffer.<br class=""><br class="">To enforce this restriction, the scope of any buffer modification must be<br class="">enclosed in a pair of SIL instructions. Those instructions define the scope<br class="">of the mutation. Both instructions take the *address* of the buffer<br class="">reference as operand and act as a potential write to the buffer reference. <br class=""><br class="">The purpose of the scoping instructions is to strictly separate the liferanges<br class="">of references to an immutable buffer and references to the mutable buffer.<br class=""><br class="">The following example shows why the scoping instructions (specifically the<br class="">end-of-scope instruction) are required to prevent loop-hoisting from<br class="">interleaving mutable and immutable liferanges::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;// there should be a begin-of-scope %baddr<br class=""> &nbsp;&nbsp;&nbsp;%mut_b = load %baddr<br class=""> &nbsp;&nbsp;&nbsp;store %x to %mut_b &nbsp;&nbsp;&nbsp;// modification of the buffer<br class=""> &nbsp;&nbsp;&nbsp;// there should be a end-of-scope %baddr<br class=""><br class=""> &nbsp;&nbsp;&nbsp;loop {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%b = load %baddr<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%y = load %b &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// load from the buffer<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;...<br class=""> &nbsp;&nbsp;&nbsp;}<br class=""><br class="">If there is no end-of-scope instruction, loop hoisting could do::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;%mut_b = load %baddr<br class=""> &nbsp;&nbsp;&nbsp;%b = load %baddr &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// moved out of the loop<br class=""> &nbsp;&nbsp;&nbsp;store %x to %mut_b<br class=""><br class=""> &nbsp;&nbsp;&nbsp;loop {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%y = load %b<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;...<br class=""> &nbsp;&nbsp;&nbsp;}<br class=""><br class="">Now the optimizer assumes that ``%b`` references an immutable buffer, so it could<br class="">also hoist the load::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;%mut_b = load %baddr<br class=""> &nbsp;&nbsp;&nbsp;%b = load %baddr<br class=""> &nbsp;&nbsp;&nbsp;%y = load %b &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// Wrong! Will be overwritten by the following store<br class=""> &nbsp;&nbsp;&nbsp;store %x to %mut_b<br class=""><br class=""> &nbsp;&nbsp;&nbsp;loop {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;...<br class=""> &nbsp;&nbsp;&nbsp;}<br class=""><br class=""><br class="">The following sections describe two alternatives to implement the scoping.<br class=""><br class="">Scoping Alternative 1: Explicit Built-ins<br class="">-----------------------------------------<br class=""><br class="">SIL instructions<br class="">^^^^^^^^^^^^^^^^<br class=""><br class="">The existing ``is_unique`` instruction is changed to a terminator instruction::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;bb0:<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;is_unique_addr_br %0 : $*@sil_cow COWBuffer, bb1, bb2 &nbsp;// %0 is the address of the COWBuffer reference<br class=""> &nbsp;&nbsp;&nbsp;bb1(%1 : $COWBuffer): // the true-block. The payload %1 is the unique reference. Physically identical to "load %0”<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// usually empty<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;br bb3(%1 : $COWBuffer)<br class=""> &nbsp;&nbsp;&nbsp;bb2: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// the false-block<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// usually contains:<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%2 = apply %copy_buffer<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%3 = cow_to_ref %2<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;store_strong %3 to %0 : $*@sil_cow COWBuffer<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;br bb3(%2 : $COWBuffer)<br class=""> &nbsp;&nbsp;&nbsp;bb3(%4 : $COWBuffer):<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// Modify the buffer referenced by %4<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// ...<br class=""><br class="">The end-of-scope instruction is::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;end_unique_addr %0 : $*COWBuffer<br class=""><br class="">It is important that the references to the unique buffers (``%1``, ``%2``) must<br class="">not outlive ``end_unique_addr``. In most cases this can be check by the SIL<br class="">verifier.<br class=""><br class="">The two instructions must be paired properly but not necessarily in the<br class="">same function.<br class=""><br class=""></blockquote><br class="">Would this require a new form of function signature?<br class=""></div></div></blockquote><div><br class=""></div><div>No</div><br class=""><blockquote type="cite" class=""><div class=""><div class=""><br class=""><blockquote type="cite" class=""><br class="">The purpose of an ``is_unique_addr_br`` - ``end_unique_addr`` pair is to<br class="">separate the lifetimes of mutable and immutable accesses to the COW buffer.<br class="">Both instructions take an address to the COW buffer reference and are<br class="">considered as potential stores to the reference.<br class="">This makes sure that the SIL optimizer cannot mix-up buffer reference lifetimes<br class="">across these instructions.<br class="">For example, RLE cannot combine two buffer loads which are interleaved with<br class="">a ``is_unique_addr_br``::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;%1 = load_strong %0 : $*@sil_cow COWBuffer<br class=""> &nbsp;&nbsp;&nbsp;// do something with %1<br class=""> &nbsp;&nbsp;&nbsp;…<br class=""> &nbsp;&nbsp;&nbsp;is_unique_addr_br %0 : $*@sil_cow COWBuffer<br class=""> &nbsp;&nbsp;&nbsp;…<br class=""> &nbsp;&nbsp;&nbsp;%2 = load_strong %0 : $*@sil_cow COWBuffer // RLE cannot replace this with %1<br class=""></blockquote><br class="">Can you make this a complete example.<br class=""></div></div></blockquote><div><br class=""></div><div>I think in this short version it’s easier to understand. But I added a comment beside the is_unique_addr_br for clarification.</div><br class=""><blockquote type="cite" class=""><div class=""><div class=""><br class=""><blockquote type="cite" class=""><br class="">Another important thing is that the COW buffer can only be mutated by using the<br class="">reference of the ``is_unique_addr_br`` true-block argument.<br class=""></blockquote><br class="">On the face this claim is incorrect. I think it is important to be clear here that you mean without any further copying done. It seems to contradict your example above of doing mutable things in bb3.<br class=""><br class=""></div></div></blockquote><div><br class=""></div><div>You are right. I rewrote this sentence.</div><br class=""><blockquote type="cite" class=""><div class=""><div class=""><blockquote type="cite" class="">The COW buffer cannot be modified by simply loading/extracting the reference<br class="">from the COWType.<br class="">Example::<br class=""><br class=""> &nbsp;%1 = load_strong %0 : $*COWBuffer<br class=""> &nbsp;%2 = cow_to_ref %1 : $@sil_cow COWBuffer<br class=""> &nbsp;%3 = ref_element_addr %2 : $COWBuffer, #someData<br class=""> &nbsp;store %7 : $Int to %3 : $*Int &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// Violation!<br class=""><br class="">Most obvious violations to this constraint can be catched by the SILVerifier.<br class=""><br class="">The ``_addr`` variants of the instructions also have a non-addr counterpart::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;is_unique_br %0 : $COWBuffer, bb1, bb2. &nbsp;// consumes %0 and produces the true-block arg as owned<br class=""><br class=""> &nbsp;&nbsp;&nbsp;%1 = end_unique %0 : $COWBuffer // consumes %0 and produces %1 as owned<br class=""><br class="">These instructions are generated by Mem2reg (or a similar optimization)<br class="">in case the COW value is stored (in a temporary alloc_stack location)<br class="">just for the sake of passing an address to ``is_unique_addr_br`` and<br class="">``end_unique_addr``.<br class="">For example in the following code, where the COW data is passed as-value and<br class="">all the mutating functions are inlined::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;func foo(arr : [Int], x: Int) {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;arr[0] = 27<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;…<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;y = arr[x]<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;…<br class=""> &nbsp;&nbsp;&nbsp;}<br class=""><br class="">Finally it’s probably a good idea to add an instruction for converting an<br class="">immutable reference to a mutable reference::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;%1 = start_unique %0 : $COWBuffer // consumes %0 and produces %1 : $COWBuffer as owned<br class=""><br class="">which is basically just a simpler representation of the following pattern::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;bb0:<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;is_unique_br %0 : $@sil_cow COWBuffer, bb1, bb2<br class=""> &nbsp;&nbsp;&nbsp;bb1(%1 : $COWBuffer):<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;… // main control flow continues here<br class=""> &nbsp;&nbsp;&nbsp;bb2:<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unreachable<br class=""><br class="">An optimizations, which eliminate uniqueness checks, would replace a<br class="">``is_unique_br`` by a ``start_unique``.<br class=""></blockquote><br class="">Question, I imagine that make_mutable is a very common case. Why not just provide such an instruction?<br class=""></div></div></blockquote><div><br class=""></div><div>What should a make_mutable instruction do? Or are you just suggesting to rename start_unique to make_mutable?</div><br class=""><blockquote type="cite" class=""><div class=""><div class=""><br class=""><blockquote type="cite" class=""><br class="">Built-ins<br class="">^^^^^^^^^<br class=""><br class="">A COW type implementor can generate the new instructions by using a set of built-ins::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;func isUnique&lt;BufferType&gt;(_ buffer: inout BufferType) -&gt; BufferType?<br class=""> &nbsp;&nbsp;&nbsp;func endUnique&lt;BufferType&gt;(_ buffer: inout BufferType) &nbsp;<br class=""><br class="">For example::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;struct COWType {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;copy_on_write var b : COWBuffer<br class=""><br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mutating func makeMutable() -&gt; COWBuffer {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if let uniqueBuffer = isUnique(&amp;self.b) {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return uniqueBuffer<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let copiedBuffer = copyBuffer(self.b)<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self.b = copiedBuffer<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return copiedBuffer<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br class=""><br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mutating func setSomeData(x: Int) {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let uniqueBuffer = makeMutable()<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;uniqueBuffer.someData = x<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;endUnique(&amp;self.b)<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br class=""> &nbsp;&nbsp;&nbsp;}<br class=""><br class="">The ``isUnique`` built-in returns an optional unique buffer reference.<br class="">Physically this is the COW buffer which is passed as the inout argument.<br class="">The result is nil if the buffer is not uniquely referenced.<br class="">In this case usually the original buffer is copied and the reference to the<br class="">copy is written back to the original buffer reference location<br class="">(``self.b = copiedBuffer``).<br class="">Starting at the point of the write-back, the reference to the copy also becomes<br class="">a unique buffer reference.<br class=""><br class="">The ``isUnique`` built-in is lowered to the ``is_unique_addr_br`` pattern which<br class="">constructs the Optional in the successor blocks. Using ``isUnique`` in an<br class="">if-let (as shown above) will end up in two consecutive CFG "diamonds".<br class="">Simplify-CFG can combine those into a single ``is_unique_addr_br`` diamond.<br class=""><br class="">.. note::<br class=""> &nbsp;This makes the definition of the unique buffer location lifetime a little bit<br class=""> &nbsp;problematic, because the false-branch of ``isUnique`` is not equivalent to<br class=""> &nbsp;the false-branch of the ``is_unique_addr_br`` instruction (before SimplifyCFG<br class=""> &nbsp;can do its job).<br class=""><br class="">The rules for using ``copy_on_write`` and the built-ins are:<br class=""><br class="">1. ``isUnique`` must be paired with ``endUnique``, but not necessarily in the<br class=""> &nbsp;&nbsp;same function.<br class=""><br class="">2. The COW buffer may only be mutated by using the unique buffer reference.<br class=""><br class="">3. The COW buffer must not be mutated outside the ``isUnique`` - ``endUnique``<br class=""> &nbsp;&nbsp;pair.<br class=""><br class="">4. During the lifetime of the unique buffer reference, the original COW buffer<br class=""> &nbsp;&nbsp;reference must not be used in any way, e.g. for reading from the buffer.<br class=""><br class=""> &nbsp;&nbsp;Note that the lifetime of the unique buffer reference does not include the<br class=""> &nbsp;&nbsp;part between the begin of the ``isUnique`` false-branch and the write-back<br class=""> &nbsp;&nbsp;of the copy. This means is okay to read from the buffer (using ``self.b``)<br class=""> &nbsp;&nbsp;for the purpose of copying.<br class=""><br class="">Examples::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;mutating func setSomeData(x: Int) {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let uniqueBuffer = makeMutable()<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;uniqueBuffer.someData = x<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// violates rule 1<br class=""> &nbsp;&nbsp;&nbsp;}<br class=""><br class=""> &nbsp;&nbsp;&nbsp;mutating func setSomeData(x: Int) {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;makeMutable()<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self.b.someData = x // violates rule 2<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;endUnique(&amp;self.b)<br class=""> &nbsp;&nbsp;&nbsp;}<br class=""><br class=""> &nbsp;&nbsp;&nbsp;mutating func setSomeData(x: Int) {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let uniqueBuffer = makeMutable()<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;uniqueBuffer.someData = x<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;endUnique(&amp;self.b)<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;uniqueBuffer.someData = 27 // violates rule 3<br class=""> &nbsp;&nbsp;&nbsp;}<br class=""><br class=""> &nbsp;&nbsp;&nbsp;mutating func incrementSomeData() {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let uniqueBuffer = makeMutable()<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;uniqueBuffer.someData = self.b.someData + 1 // violates rule 4<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;endUnique(&amp;self.b)<br class=""> &nbsp;&nbsp;&nbsp;}<br class=""><br class=""><br class="">The intention of the rules is to ensure that there is no overlap of a<br class="">"read-only" life-range with a "mutable" life-range of the buffer reference.<br class="">It’s the responsibility of the implementor to follow the rules.<br class="">But the compiler (a mandatory diagnostics pass and the SIL verifier) can<br class="">statically detect rule violations in obvious cases (with inter-procedural<br class="">analysis maybe even in most cases).<br class=""><br class="">This approach would require to change some of the internals of our<br class="">current COW data structures in the stdlib (Array, Dictionary, etc.).<br class="">For example, the Array make_mutable semantic functions currently do not return<br class="">the unique buffer.<br class=""><br class="">Scoping Alternative 2: Implicit Inout Scopes<br class="">--------------------------------------------<br class=""><br class="">There is an idea (proposal?) to change the representation of inout variables<br class="">in SIL. This is independent of this proposal, but can be helpful for the<br class="">purpose of defining the scope of a COW mutation.<br class=""><br class="">The basic idea is that SILGen inserts scoping instructions for *all* inout<br class="">variables. And those scoping instructions can be used to define the mutating<br class="">scope of a COW buffer.<br class=""><br class="">The scoping instructions which are inserted by SILGen for an inout scope are::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;begin_exclusive<br class=""> &nbsp;&nbsp;&nbsp;end_exclusive<br class=""><br class="">Simliar to ``is_unique_addr_br`` and ``end_unique_addr``, those instructions take the<br class="">address of the inout variable as argument. For the optimizer those instructions<br class="">look like potential writes to the inout variable.<br class=""><br class="">The implementor of a COW type has to follow the rule that the COW buffer may<br class="">only be modified in mutating functions of the COW type. But this is the case<br class="">anyway because any modification needs a uniqueness check and this can only be<br class="">done in mutating functions.<br class=""><br class="">Example::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;// &gt; mutating func setSomeData(x: Int) {<br class=""> &nbsp;&nbsp;&nbsp;// Accepts a unique reference to the array value (avoiding refcount operations)<br class=""> &nbsp;&nbsp;&nbsp;sil @setSomeData : $(Int, @inout Array) -&gt; () {<br class=""> &nbsp;&nbsp;&nbsp;bb_entry(%x : Int, %arrayref : $*Array&lt;T&gt;) // Begin scope #0<br class=""><br class=""> &nbsp;&nbsp;&nbsp;// &gt; &nbsp;&nbsp;makeMutable() (inlined)<br class=""> &nbsp;&nbsp;&nbsp;// Forward the unique reference to the `self` array value, still avoiding refcount operations.<br class=""> &nbsp;&nbsp;&nbsp;// Begin the inlined exclusive scope (could be trivially removed).<br class=""> &nbsp;&nbsp;&nbsp;begin_exclusive %arrayref : $*Array&lt;T&gt; // Begin scope #1<br class=""><br class=""> &nbsp;&nbsp;&nbsp;// &gt; &nbsp;&nbsp;&nbsp;if !isUnique(&amp;self._storage) {<br class=""> &nbsp;&nbsp;&nbsp;// Extract a unique inout reference to the class reference to the array storage.<br class=""> &nbsp;&nbsp;&nbsp;// This begins the isUnique() argument's exclusive scope. The memory is already exclusive<br class=""> &nbsp;&nbsp;&nbsp;// but the scope helps ensure this is the only alias to _storage.<br class=""> &nbsp;&nbsp;&nbsp;%arrayref._storageref = struct_element_addr [exclusive] %arrayref, #Array._storage<br class=""><br class=""> &nbsp;&nbsp;&nbsp;// Uniqueness checking requires an inout reference to the class reference.<br class=""> &nbsp;&nbsp;&nbsp;// The is_unique instruction does not need to create a new storage reference.<br class=""> &nbsp;&nbsp;&nbsp;// It's only purpose is to check the RC count, ensure that the checked reference<br class=""> &nbsp;&nbsp;&nbsp;// is inout, and prevent the inout scope from being optimized away.<br class=""> &nbsp;&nbsp;&nbsp;%isuniq = is_unique %arrayref._storageref : $*@sil_cow ArrayStorage&lt;T&gt;<br class=""><br class=""> &nbsp;&nbsp;&nbsp;// End the isUnique argument's exclusive scope (can also be trivially removed).<br class=""> &nbsp;&nbsp;&nbsp;end_exclusive %arrayref._storageref : $*@sil_cow ArrayStorage&lt;T&gt;<br class=""><br class=""> &nbsp;&nbsp;&nbsp;br %isuniq, bb_continue, bb_slow<br class=""><br class=""> &nbsp;&nbsp;&nbsp;bb_slow:<br class=""> &nbsp;&nbsp;&nbsp;// &gt; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self._storage = copyBuffer(self._storage)<br class=""> &nbsp;&nbsp;&nbsp;// Produce a new class reference to storage with verifiably unique RC semantics.<br class=""> &nbsp;&nbsp;&nbsp;%copied_storage_class = alloc_ref ...<br class=""> &nbsp;&nbsp;&nbsp;// A begin/end exclusive scope is implicit in store [assign].<br class=""> &nbsp;&nbsp;&nbsp;store [assign] %copied_storage_class to %arrayref._storageref<br class=""> &nbsp;&nbsp;&nbsp;br bb_continue<br class=""><br class=""> &nbsp;&nbsp;&nbsp;bb_continue:<br class=""><br class=""> &nbsp;&nbsp;&nbsp;// This marks the end of makeMutable's inout `self` scope. Because Array<br class=""> &nbsp;&nbsp;&nbsp;// contains a "copy_on_write" property, the SIL verifier needs to<br class=""> &nbsp;&nbsp;&nbsp;// prove that %arrayref.#_storage has not escaped at this point. This<br class=""> &nbsp;&nbsp;&nbsp;// is equivalent to checking that %arrayref itself is not copied, and<br class=""> &nbsp;&nbsp;&nbsp;// checking each projection of the "copy_on_write" storage property<br class=""> &nbsp;&nbsp;&nbsp;// (%arrayref._storageref) is not copied. Or, if any copies are present,<br class=""> &nbsp;&nbsp;&nbsp;// they must be consumed within this scope.<br class=""> &nbsp;&nbsp;&nbsp;end_exclusive %arrayref : $*Array&lt;T&gt; // End scope #1<br class=""><br class=""> &nbsp;&nbsp;&nbsp;// &gt; &nbsp;&nbsp;&nbsp;self._storage.someData = x<br class=""> &nbsp;&nbsp;&nbsp;// An _addr instruction with one load/store use doesn't really need its own scope.<br class=""> &nbsp;&nbsp;&nbsp;%arrayref._storageref = struct_element_addr %arrayref, #Array._storage<br class=""><br class=""> &nbsp;&nbsp;&nbsp;// ARC optimization can promote this to a borrow, replacing strong_release with end_borrow.<br class=""> &nbsp;&nbsp;&nbsp;%arrayref.cow_storage = load [copy] %arrayref._storageref : $*@sil_cow ArrayStorage<br class=""> &nbsp;&nbsp;&nbsp;%arrayref._storage = cow_to_ref %arrayref.cow_storage : $@sil_cow ArrayStorage<br class=""><br class=""> &nbsp;&nbsp;&nbsp;// Write some data into the CoW buffer.<br class=""> &nbsp;&nbsp;&nbsp;// (For simplicity, pretend ArrayStorage has a "someData" field).<br class=""> &nbsp;&nbsp;&nbsp;// A single-use _addr instruction, so no scope.<br class=""> &nbsp;&nbsp;&nbsp;%somedata_addr = ref_element_addr %arrayref._storage, #someData<br class=""> &nbsp;&nbsp;&nbsp;// A store with an implicit [exclusive] scope.<br class=""> &nbsp;&nbsp;&nbsp;store [assign] %x to %somedata_addr<br class=""><br class=""> &nbsp;&nbsp;&nbsp;strong_release %arrayref._storage : $*ArrayStorage&lt;T&gt;<br class=""><br class=""> &nbsp;&nbsp;&nbsp;// End the isUnique argument's exclusive scope.<br class=""> &nbsp;&nbsp;&nbsp;// The same verification is needed here, but the inner scope would be eliminated.<br class=""> &nbsp;&nbsp;&nbsp;end_exclusive %arrayref : $*Array&lt;T&gt; // End scope #0<br class=""><br class="">In general this approach looks more "user-friendly" than the first alternative.<br class="">But it depends on implementing the general feature to insert the inout scoping<br class="">instructions.<br class="">Also, we still have to think through all the details of this approach.<br class=""><br class="">Dependency between a buffer reference to the scope-begin<br class="">--------------------------------------------------------<br class=""><br class="">With both alternatives there is no explicit dependency from a buffer reference<br class="">to a scope-begin instruction::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;%b_cow = load %baddr<br class=""> &nbsp;&nbsp;&nbsp;%b = cow_to_ref %b_cow<br class=""> &nbsp;&nbsp;&nbsp;%x = load %b &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// No dependency between this...<br class=""> &nbsp;&nbsp;&nbsp;...<br class=""> &nbsp;&nbsp;&nbsp;begin_exclusive %baddr &nbsp;&nbsp;// ... and this instruction.<br class=""> &nbsp;&nbsp;&nbsp;...<br class=""><br class="">So in theory the optimizer is free to reschedule the instructions::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;%b_cow = load %baddr<br class=""> &nbsp;&nbsp;&nbsp;%b = cow_to_ref %b_cow<br class=""> &nbsp;&nbsp;&nbsp;...<br class=""> &nbsp;&nbsp;&nbsp;begin_exclusive %baddr<br class=""> &nbsp;&nbsp;&nbsp;%x = load %b &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// Wrong! Buffer could be modified here<br class=""> &nbsp;&nbsp;&nbsp;...<br class=""><br class="">We still have to figure out how to cope with this.<br class=""><br class="">- We could add an end-of-lifetime instruction for a COW buffer reference, which<br class=""> &nbsp;the optimizer may not move over a begin-of-scope instruction.<br class=""><br class="">- Or we just define the implicit rule for the optimizer that any use of a COW<br class=""> &nbsp;reference may not be moved over a begin-of-scope instruction.<br class=""><br class="">Preconditions<br class="">=============<br class=""><br class="">To benefit from COW optimizations in the stdlib Array, Set and Dictionary data<br class="">structures we first need eager bridging, meaning getting rid of the bridged<br class="">buffer. At least for Array this is implemented as low-level bit operations and<br class="">optimizations cannot reason about it (e.g. finding a reasonable RC-root for the<br class="">buffer reference).<br class=""><br class="">Another thing is that we currently cannot use ``copy_on_write`` for Array<br class="">because of pinning. Array pins it’s buffer when passing an element address to<br class="">an inout parameter. This allows the array buffer to be modified even if its<br class="">reference count is &gt; 1. With ``copy_on_write``, a programmer could break memory<br class="">safety when violating the inout rule. Example::<br class=""><br class=""> &nbsp;&nbsp;&nbsp;var arr = [MyClass()] &nbsp;// a global array<br class=""><br class=""> &nbsp;&nbsp;&nbsp;foo(&amp;arr[0]) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// Pins the buffer of arr during the call<br class=""><br class=""> &nbsp;&nbsp;&nbsp;func foo(_ x: inout MyClass) -&gt; Int {<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let b = arr &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// The ref-count of the buffer is not incremented, because it is pinned!<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let r = b[0] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// optimizer removes the retain of r because it thinks the following code cannot modify b<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;arr.removeAll() &nbsp;&nbsp;// does not copy the array buffer and thus de-allocates r<br class=""> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return r.i &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// use-after-free!<br class=""> &nbsp;&nbsp;&nbsp;}<br class=""></blockquote><br class="">From a quick (re-)reading, this proposal still makes sense to me. My largest comment is that I would really like to have some way that the program will assert if the constraints are violated. Otherwise it will be difficult to debug when your invariants are broken. The state machine seems simple enough that I think you could reuse the pinned buffer and (if necessary) 1 additional bit in the object header (or perhaps tagged pointer bits).<br class=""></div></div></blockquote><div><br class=""></div><div>Yeah, we could do this. I think it would just be sufficient to write a null pointer into the cow reference on at the begin-scope and restore it at the end-scope. It’s the same thing as having runtime checks for not violating borrowing rules.</div><br class=""><blockquote type="cite" class=""><div class=""><div class=""><br class="">Michael<br class=""><br class=""><blockquote type="cite" class=""><br class=""><br class=""><blockquote type="cite" class="">On Oct 11, 2016, at 4:48 PM, Erik Eckstein via swift-dev &lt;<a href="mailto:swift-dev@swift.org" class="">swift-dev@swift.org</a>&gt; wrote:<br class=""><br class="">This is a proposal for representing copy-on-write buffers in SIL. Actually it’s still a draft for a proposal. It also heavily depends on how we move forward with SIL ownership.<br class="">If you have any comments, please let me know.<br class=""><br class="">Erik<br class=""><br class=""><br class="">_______________________________________________<br class="">swift-dev mailing list<br class=""><a href="mailto:swift-dev@swift.org" class="">swift-dev@swift.org</a><br class="">https://lists.swift.org/mailman/listinfo/swift-dev<br class=""></blockquote><br class=""></blockquote></div></div></blockquote></div><br class=""></div></div></body></html>