expand post title
[web.git] / ralf / _posts / 2018-08-07-stacked-borrows.md
1 ---
2 title: "Stacked Borrows: An Aliasing Model For Rust"
3 categories: internship rust
4 forum: https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153
5 ---
6
7 In this post, I am proposing "Stacked Borrows": A set of rules defining which kinds of aliasing are allowed in Rust.
8 This is intended to answer the question which pointer may be used when to perform which kinds of memory accesses.
9
10 This is a long-standing open question of many unsafe code authors, and also by compiler authors who want to add more optimizations.
11 The model I am proposing here is by far not the first attempt at giving a definition: The model is heavily based on ideas by [@arielb1](https://github.com/nikomatsakis/rust-memory-model/issues/26) and [@ubsan](https://github.com/nikomatsakis/rust-memory-model/issues/28), and of course taking into account the lessons I [learned last year]({% post_url 2017-08-11-types-as-contracts-evaluation %}) when I took my first stab at defining such a model, dubbed ["Types as Contracts"]({% post_url 2017-07-17-types-as-contracts %}).
12
13 <!-- MORE -->
14
15 But before I delve into my latest proposal, I want to briefly discuss a key difference between my previous model and this one:
16 "Types as Contracts" was a fully "validity"-based model, while "Stacked Borrows" is (to some extent) "access"-based.
17
18 ## 1 Validity-based vs. Access-based
19
20 An "access"-based model is one where certain properties -- in this case, mutable references being unique and shared references pointing to read-only memory -- are only enforced when the reference is actually used to *access* memory.
21 In contrast, a "validity"-based model requires these properties to always hold for all references that *could* be used.
22 In both cases, violating a property that the model requires to hold is undefined behavior..
23
24 Essentially, with a validity-based model like "Types as Contracts", the basic idea is that all data is always valid according to the type it is given.
25 Enforcing the restrictions of such a model (e.g., when checking whether a program has undefined behavior) amounts to eagerly checking all reachable data for validity.
26 An access-based model, on the other hand, only requires data to be valid when used.
27 Enforcing it amounts to lazily checking the bare minimum at each operation.
28
29 Validity-based models have several advantages: Eager checking means we can typically identify which code is actually responsible for producing the "bad" value.
30 "All data must always be valid" is also easier to explain than a long list of operations and the kind of restrictions they place upon the data.
31
32 However, in Rust, we cannot talk about references and whether the are valid at their given type without talking about lifetimes.
33 With "Types as Contracts", the exact place where a lifetime ended turned out to be really important.
34 Not only did this make the specification complex and hard to understand; the implementation in Miri also had to actively work against the compiler's general intention to forget about lifetimes as early as possible.
35 With non-lexical lifetimes, the "end" of a lifetime is not even so clearly defined any more.
36
37 ## 2 Stacking Borrows
38
39 For these reasons, my second proposal makes lifetimes in general and the result of lifetime inference in particular completely irrelevant for whether a program has undefined behavior (UB).
40 This is one of the core design goals.
41
42 If you need some more context on undefined behavior and how it relates to compiler optimizations, I suggest you read [my blog post on this topic]({% post_url 2017-07-14-undefined-behavior %}) first.
43 It's not a long post, and I cannot repeat everything again here. :)
44
45 The central idea of this model (and its precursors by @arielb1 and @ubsan) is that, for every location, we keep track of the references that are allowed to access this location.
46 (I will discuss later just how we keep track of this; for now, let's just assume it can be done.)
47 This forms a stack: When we have an `&mut i32`, we can *reborrow* it to obtain a new reference.
48 That new reference is now the one that must be used for this location, but the old reference it was created from cannot be forgotten: At some point, the reborrow will expire and the old reference will be "active" again.
49 We will have other items on that stack as well, so we will write `Uniq(x)` to indicate that `x` is the unique reference permitted to access this location.
50
51 Let us look at an example:
52 {% highlight rust %}
53 fn demo0(x: &mut i32) -> i32 {
54   // At the beginning of the function, `x` must be the "active" reference
55   // for the 4 locations it points to, meaning `Uniq(x)` is at the top of the stack.
56   // (It's 4 locations because `i32` has size 4.)
57   let y = &mut *x; // Now `Uniq(y)` is pushed onto the stack, as new active reference.
58   // The stack now contains: Uniq(y), Uniq(x), ...
59   *y = 5; // Okay because `y` is active.
60   *x = 3; // This "activates" `x` by popping the stack.
61   // The stack now contains: Uniq(x), ...
62   *y // This is UB! `Uniq(y)` is not on the stack of borrows, so `y` must not be used.
63 }
64 {% endhighlight %}
65 Of course, this example would not compile because the borrow checker would complain.
66 However, in my interpretation, the *reason* it complains is that if it accepted the program, we would have UB in safe code!
67
68 This is worth pondering a bit: The model defines program semantics without taking lifetimes into account, so we can run programs and ask whether they have UB without
69 ever doing lifetime inference or borrow checking (very much unlike "Types as Contracts").
70 One important property, then, is that *if* the program has UB and does not use any unsafe code, the borrow checker must detect this.
71 In some sense, my model defines a dynamic version of the borrow checker *that works without lifetimes*.
72 It turns out that even with non-lexical lifetimes, the borrow structure for a given location is still well-nested, which is why we can arrange borrows in a stack.
73
74 ### 2.1 Raw Pointers
75
76 Let us bypass the borrow checker by adding some unsafe code to our program:
77 {% highlight rust %}
78 fn demo1(x: &mut i32) -> i32 {
79   // At the beginning of the function, `x` must be the "active" reference.
80   let raw = x as *mut _; // Create raw pointer
81   // The stack now contains: Raw, Uniq(x), ...
82   let y = unsafe { &mut *raw }; // Now `y` is pushed onto the stack, as new active reference.
83   // The stack now contains: Uniq(y), Raw, Uniq(x), ...
84   *y = 5; // Okay because `y` is active.
85   *x = 3; // This "activates" `x` by popping the stack twice.
86   *y // This is UB! `Uniq(y)` is not on the stack of borrows, so `y` must not be used.
87 }
88 {% endhighlight %}
89
90 What happens here is that we are casting `x` to a raw pointer.
91 For raw pointers, we cannot really keep track of where and how they have been created -- raw pointers can be safely cast to and from integers, and data could flow arbitrarily.
92 So, when a `&mut` is cast to `*mut` like above, we instead push `Raw` onto the stack, indicating that *any* raw pointer may be used to access this location.
93 (The usual restrictions about address arithmetic across allocations still apply, I am just talking about the borrow checking here.)
94
95 In the next line, we use a raw pointer to create `y`.
96 That is okay because `Raw` is active.
97 As usual when a reference is created, we push it onto the stack.
98 This makes `y` the active reference, so we can use it in the next line.
99 And again, using `x` pops the stack until `x` is active -- in this case, this removes both the `Uniq(y)` and the `Raw`, making `y` unusable and causing UB in the last line.
100
101 Let us look at another example involving raw pointers:
102 {% highlight rust %}
103 fn demo2(x: &mut i32) -> i32 {
104   // At the beginning of the function, `x` must be the "active" reference.
105   let raw = x as *mut _; // Create raw pointer
106   // The stack now contains: Raw, Uniq(x), ...
107   let y = unsafe { &mut *raw }; // Now `y` is pushed onto the stack, as new active reference.
108   // The stack now contains: Uniq(y), Raw, Uniq(x), ...
109   *y = 5; // Okay because `y` is active.
110   unsafe { *raw = 5 }; // Using a raw pointer, so `Raw` gets activated by popping the stack!
111   // The stack now contains: Raw, Uniq(x), ...
112   *y // This is UB! `Uniq(y)` is not on the stack of borrows, so `y` must not be used.
113 }
114 {% endhighlight %}
115 Because raw pointers are tracked on the stack, they have to follow the well-nested structure.
116 `y` was "created from" `raw`, so using `raw` again invalidates `y`!
117 This is exactly in symmetry with the first example where `y` was "created from" `x`, so using `x` again invalidated `y`.
118
119 ### 2.2 Shared References
120
121 For shared references, of course, we do not have a single reference which is the only one with permission to access.
122 The key property we have to model is that shared references point to memory that does not change (assuming no interior mutability is involved).
123 The memory is, so to speak, *frozen*.
124
125 For this purpose, we tag shared references with some kind of "timestamp" indicating *when* it was created.
126 We also have an extra flag for each location storing *since when* the location is frozen.
127 Using a shared reference to access memory is okay if memory has been frozen continuously since the reference was created.
128
129 We can see this in action in the following example:
130 {% highlight rust %}
131 fn demo3(x: &mut i32) -> i32 {
132   // At the beginning of the function, `x` must be the "active" reference.
133   let raw = x as *mut _; // Create raw pointer
134   // The stack now contains: Raw, Uniq(x), ...
135   let y = unsafe { & *raw }; // Now memory gets frozen (recording the timestamp)
136   let _val = *y; // Okay because memory was frozen since `y` was created
137   *x = 3; // This "activates" `x` by unfreezing and popping the stack.
138   let z = unsafe { & *raw }; // Now memory gets frozen *again*
139   *y // This is UB! Memory has been frozen strictly after `y` got created.
140 }
141 {% endhighlight %}
142
143 Shared references with interior mutability do not really have any restrictions in terms of what can happen to memory, so we treat them basically like raw pointers.
144
145 ### 2.3 Recap
146
147 For every location in memory, we keep track of a stack of borrows (`Uniq(_)` or `Raw`), and potentially "top off" this stack by freezing the location.
148 A frozen location is never written to, and no `Uniq` is pushed.
149
150 Whenever a mutable reference is created, a matching `Uniq` is pushed onto the stack for every location "covered by" the reference -- i.e., the locations that would be accessed when the reference is used (starting at where it points to, and going on for `size_of_val` many bytes).
151 Whenever a shared reference is created, if there is no interior mutability, we freeze the locations if they are not already frozen.
152 If there is interior mutability, we just push a `Raw`.
153 Whenever a raw pointer is created from a mutable reference, we push a `Raw`.
154 (Nothing happens when a raw pointer is created from a shared reference.)
155
156 A mutable reference `x` is "active" for a location if that location is not frozen and `Uniq(x)` is on top of the stack.
157 A shared reference without interior mutability is active if the location is frozen at least since the location was created.
158 A shared reference with interior mutability is active is `Raw` is on top of the stack.
159
160 Whenever a reference is used to do something (anything), we make sure that it is active for all locations that it covers; this can involve unfreezing and popping the stack.
161 If it is not possible to activate the reference this way, we have UB.
162
163 ## 3 Tracking Borrows
164
165 So far, I have just been assuming that we can somehow keep a connection between a reference like `x` in the code above, and an item `Uniq(x)` on the stack.
166 I also said we are keeping track of when a shared reference was created.
167 To realize this, we need to somehow have information "tagged" to the reference.
168 In particular, notice that `x` and `y` in the first example have the same address.
169 If we compared them as raw pointers, they would turn out equal.
170 And yet, it makes a huge difference if we use `x` or `y`!
171
172 If you read my previous post on [why pointers are complicated]({% post_url 2018-07-24-pointers-and-bytes %}), this should not come as too much of a surprise.
173 There is more to a pointer, or a reference (I am using these terms mostly interchangeably), than the address in memory that it points to.
174
175 For the purpose of this model, we assume that a value of reference type consists of two parts: An address in memory, and a tag used to store the time when the reference was created.
176 "Time" here is a rather abstract notion, we really just need some counter that we bump up every time a new reference is created.
177 This gives us a unique ID for each mutable reference -- and, as we have seen, for shared references we actually exploit the fact that IDs are handed out in increasing order
178 (so that we can test if a reference was created before or after a location was frozen).
179 So, we can actually treat mutable and shard references uniformly in that both just record, in their tag, the time at which they were created.
180
181 Whenever I said above that we have `Uniq(x)` on the stack, what I really meant is that we have `Uniq(t_x)` on the stack, where `t_x` is some clock value, and that the "tag" of `x` is `t_x`.
182 For the sake of readability, I will continue to use the `Uniq(x)` notation below.
183
184 Since raw pointers are not tracked, we can erase the tag when casting a reference to a raw pointer.
185 This means our tag does not interfere with pointer-integer casts, which means there are a whole bunch of complicated questions we do not have to worry about. :)
186
187 Of course, these tags do not exist on real hardware.
188 But that is besides the point.
189 When *specifying* program behavior, we can work with an ["instrumented machine"]({% post_url 2017-06-06-MIR-semantics %}) that has extra state which is not present on the real machine, as long as we only use that extra state to define whether a program is UB or not:
190 On real hardware, we can ignore programs that are UB (they may just do whatever), so the extra state does not matter.
191
192 Tags are something I wanted to avoid in "Types as Contracts" -- that was one of the initial design constraints I had put upon myself, in the hope of avoiding the trouble coming with "complicated pointers".
193 However, I now came to the conclusion that tagging pointers is a price worth paying if it means we can make lifetimes irrelevant.
194
195 ## 4 Retagging and Barriers
196
197 I hope you now have a clear idea of the basic structure of the model I am proposing: The stack of borrows, the freeze flag, and references tagged with the time at which they got created.
198 The full model is not quite as simple, but it is not much more complicated either.
199 We need two add just two more concepts: Retagging and barriers.
200
201 ### 4.1 Retagging
202
203 Remember that every time we create a mutable borrow, we assign it the current
204 clock values as its tag.  Since the tag can never be changed, this means two
205 different variables can never have the same tag -- right?  Well, unfortunately,
206 things are not so simple: Using
207 e.g. [`transmute_copy`](https://doc.rust-lang.org/stable/std/mem/fn.transmute_copy.html)
208 or a `union`, one can make a copy of a reference in a way that Rust does not
209 even notice.
210
211 Still, we would like to make statements about code like this:
212 {% highlight rust %}
213 fn demo4(x: &mut i32, y: &mut i32) -> i32 {
214   *x = 42;
215   *y = 7;
216   *x // Will load 42! We can optimize away the load.
217 }
218 {% endhighlight %}
219 The trouble is, we cannot prevent the outside world from passing bogus `&mut` that have the same tag.
220 Does this mean we are back to square one in terms of making aliased mutable references UB?
221 Lucky enough, we are not! We have a lot of machinery at our disposal, we just have to tweak it a little.
222
223 What we will do is, every time a reference comes "into" our function (this can be a function argument, but also loading it from memory or getting it as the return value of some other function), we perform "retagging":
224 We change the tags of the mutable references to the current clock value, bumping up the clock after every tag we assign, and then we push those new tags on top of the borrow stack.
225 This way, we can know -- without making any assumptions about foreign code -- that all references have distinct IDs.
226 In particular, two different references can never be both "active" for the same location at the same time.
227
228 With this additional step, it is now easy to argue that `demo4` above is UB when `x` and `y` alias, no matter their initial tag:
229 After using `x`, we know it is active.
230 Next we use and activate `y`, which has to pop `Uniq(x)` as they have distinct tags.
231 Finally, we use `x` again even though it is no longer in the stack, triggering UB.
232 (A `Uniq` is only ever pushed when it is created, so it is never in the stack more than once.)
233
234 ### 4.2 Barriers
235
236 There is one more concept I would like to add: Barriers.
237 The model would make a lot of sense even without barriers -- but adding barriers rules out some more behavior that I do not think we want to allow.
238 It is also needed to explain why we can put the [`noalias` parameter attribute](https://llvm.org/docs/LangRef.html#parameter-attributes) on our functions when generating LLVM IR.
239
240 Consider the following code:
241 {% highlight rust %}
242 fn demo5(x: &mut i32, y: usize) {
243   *x = 42;
244   foo(y);
245 }
246
247 fn foo(y: usize) {
248   let y = unsafe { &mut *(y as *mut i32) };
249   *y = 7;
250 }
251 {% endhighlight %}
252 The question is: Can we reorder the `*x = 42;` down to the end of `demo5`?
253 Notice that we are *not* using `x` again, so we cannot assume that `x` is active at the end of `demo5`!
254 This is the usual trouble with access-based models.
255
256 However, someone might conceivably call `demo5` with `y` being `x as *mut _ as usize`, which means reordering could change program behavior.
257 To fix this, we have to make sure that if someone actually calls `demo5` this way, we have UB *even though* `x` is not used again.
258
259 To this end, I propose to turn the dial a little more towards a validity-based model by imposing some extra constraints.
260 We want to ensure that turning the integer `y` into a reference does not pop `x` from the stack and continue executing the program (we want UB instead).
261 This could happen if the stack contained, somewhere, a `Raw`.
262 Remember that we do not tag raw pointers, so when a raw pointer was involved in creating `x`, that `Raw` item will still be on the stack, enabling any raw pointer to be used to access this location.
263 This is sometimes crucial, but in this case, `demo5` should be able to prevent those old historic borrows involved in creating `x` from being activated.
264
265 The idea is to put a "barrier" into the stack of all function arguments when `demo5` gets called, and to make it UB to pop that barrier from the stack before `demo5` returns.
266 This way, all the borrows further down in the stack (below `Uniq(x)`) are temporarily disabled and cannot be activated while `demo5` runs.
267 This means that even if `y` happens to be the memory address `x` points to, it is UB to cast `y` to a reference because the `Raw` item cannot be activated.
268
269 Another way to think about barriers is as follows:
270 The model generally ignores lifetimes and does not know how long they last.
271 All we know is that when a reference is used, its lifetime must be ongoing, so we say that is when we activate the borrow.
272 On top of this, barriers encode the fact that, when a reference is passed as an argument to a function, then its lifetime (whatever it is) extends beyond the current function call.
273 In our example, this means that no borrow further up the stack (these are the borrows with even longer lifetimes) can be used while `demo5` is running.
274
275 A nice side-effect of barriers in combination with renumbering is that even if `demo4` from the previous subsection would not use its arguments at all, it would *still* be UB to call it with two aliasing references:
276 When renumbering `x`, we are pushing a barrier. Renumbering `y` would attempt to activate `Uniq(y)`, but that can only be behind the barrier, so it cannot be activated.
277
278 ## 5 The Model in Code
279
280 Now we have everything together.
281 Instead of giving another recap, I will try to give an alternative, more precise description of the model in the form of pseudo Rust code.
282 This is essentially a draft of the code that will hopefully be in Miri soon, to actually dynamically track the borrow stack and enforce the rules.
283 This is also how I go about developing such models -- I use some form of pseudo-Rust, which I find it easier to be precise in than pure English.
284 Some details have been omitted in the high-level description so far, they should all be in this code.
285
286 If you are only interested in the high-level picture, feel free to skip to the end.
287 The rest of this is more like a specification than an explanatory blog post.
288 The nice thing is that even with the spec, this post is still shorter than the one introducing "Types as Contracts". :)
289
290 ### 5.1 Per-Location Operations
291
292 Imagine we have a type `MemoryByte` storing the per-location information in memory.
293 This is where we put the borrow stack and the information about freezing:
294
295 {% highlight rust %}
296 /// Information about a potentially mutable borrow
297 enum Mut {
298   /// A unique, mutable reference
299   Uniq(Timestamp),
300   /// Any raw pointer, or a shared borrow with interior mutability
301   Raw,
302 }
303 /// Information about any kind of borrow
304 enum Borrow {
305   /// A mutable borrow, a raw pointer, or a shared borrow with interior mutability
306   Mut(Mut),
307   /// A shared borrow without interior mutability
308   Frz(Timestamp)
309 }
310 /// An item in the borrow stack
311 enum BorStackItem {
312   /// Defines which references are permitted to mutate *if* the location is not frozen
313   Mut(Mut),
314   /// A barrier, tracking the function it belongs to by its index on the call stack
315   FnBarrier(usize)
316 }
317
318 struct MemoryByte {
319   borrows: Vec<BorStackItem>, // used as a stack
320   frz_since: Option<Timestamp>,
321   /* More fields, to store the actual value and what else might be needed */
322 }
323 {% endhighlight %}
324
325 Next, we define some per-location operations that we will use later to define what happens when working with references.
326 Below, `assert!` is used for things that should always be true because of interpreter invariants (i.e., Miri will ICE if they fail to hold), and `bail!` is used to indicate that the program has UB.
327
328 {% highlight rust %}
329 impl MemoryByte {
330
331   /// Check if the given borrow may be used on this location.
332   fn check(&self, bor: Borrow) → bool {
333     match bor {
334       Frz(acc_t) =>
335         // Must be frozen at least as long as the `acc_t` says.
336         self.frz_since.map_or(false, |loc_t| loc_t <= acc_t),
337       Mut(acc_m) =>
338         // Raw pointers are fine with frozen locations. This is important because &Cell is raw!
339         (acc_m.is_raw() && self.frozen_since.is_some()) ||
340         self.borrows.last().map_or(false, |loc_itm| loc_itm == Mut(acc_m)),
341     }
342   }
343
344   /// Activate the given existing borrow for this location, fail if that is not possible.
345   fn activate(&mut self, bor: Borrow) {
346     // Do NOT change anything if `bor` is already active -- in particular, if
347     // it is a `Mut(Raw)` and we are frozen.
348     if self.check(bor) { return; }
349     let acc_m = match bor {
350       Frz(acc_t) => bail!("Location should be frozen but it is not"),
351       Mut(acc_m) => acc_m,
352     };
353     // We definitely have to unfreeze this, even if we use the topmost item.
354     self.frozen_since = None;
355     // Pop until we see the one we are looking for.
356     while let Some(itm) = self.borrows.last() {
357       match itm {
358         FnBarrier(_) => {
359           bail!("Trying to activate a borrow that lives behind a barrier");
360         }
361         Mut(loc_m) => {
362           if loc_m == acc_m { return; }
363           self.borrows.pop();
364         }
365       }
366     }
367     bail!("Borrow-to-activate does not exist on the stack");
368   }
369
370   /// Initiate the given (new) borrow for the location.
371   /// This is "pushing to the stack", except that it also handles initiating a `Frz`.
372   fn initiate(&mut self, bor: Borrow) {
373     match bor {
374       Frz(t) => {
375         if self.frozen_since.is_none() {
376           self.frozen_since = Some(t);
377         }
378       }
379       Mut(m) => {
380         if m.is_uniq() && self.frozen_since.is_some() {
381           bail!("Must not initiate Uniq when frozen!");
382         }
383         self.borrows.push(Mut(m));
384       }
385     }
386   }
387
388   /// Reset the borrow tracking for this location.
389   fn reset(&mut self) {
390     if self.borrows.iter().any(|itm| if let FnBarrier(_) = item { true } else { false }) {
391       assert!("Cannot reset while there are barriers");
392     }
393     self.frozen_since = None;
394     self.borrows.clear();
395   }
396   
397 }
398 {% endhighlight %}
399
400 ### 5.2 MIR operations
401
402 Finally, we enhance some MIR operations with bookkeeping, following the model I described above.
403 This is where the code gets more "pseudo" and less Rust. ;)
404
405 For each of these operation, we iterate over all affected locations; let us call the loop variable `loc` of type `MemoryByte`.
406 We also have a variable `tag` with the tag of the pointer we are operating on (loading, or storing, or casting to a raw pointer, ...).
407
408 Moreover, we have a boolean variable `in_unsafe_cell` indicating whether, according to the type of the pointer, the location we are currently working on is covered by an [`UnsafeCell`](https://doc.rust-lang.org/stable/std/cell/struct.UnsafeCell.html).
409 (This realizes the conditions checking whether we have interior mutability or not.)
410 For example, in `&Cell<i32>`, all 4 locations are inside an `UnsafeCell`.
411 However, in `&(i32, Cell<i32>)`, only the last 4 of the 8 covered locations are inside an `UnsafeCell`.
412
413 Finally, given a reference type, a tag, and whether we are inside an `UnsafeCell`, we can compute the matching `Borrow`:
414 Mutable references use `Mut(Uniq(tag))`, shared references in an `UnsafeCell` use `Mut(Raw)` and other shared references use `Frz(tag)`.
415 We use `bor` to refer to the `Borrow` of the pointer we are working on.
416
417 Now we can look at what happens for each operation.
418
419 * Using a raw pointer directly is desugared to creating a shared reference (when reading) or a mutable reference (when writing), and using that. The appropriate steps below apply.
420 * Any time we use a (mutable or shared) reference to access memory, and any time we pass a reference to "the outside world" (passing it to a function, storing it in memory, returning it to our caller; also below structs or enums but not below unions or pointer indirectons), we activate.
421   - `loc.activate(borrow)`.
422 * Any time a *new* reference is created (any time we run an expression `&mut foo` or `&foo`), we (re)borrow.
423   - Bump up the clock, and remember the old time as `new_tag`.
424   - Compute `new_bor` from `new_tag` and the type of the reference being created.
425   - `if loc.check(new_bor) {`
426     * The new borrow is already active! This can happen because a mutable reference can be shared multiple times. We do not do anything else.
427       As a special exception, we do *not* activate `bor` even though it is "used", because that would unfreeze the location!
428
429     `} else {`
430     * We might be creating a reference to a local variable. In that case, `loc.reset()`. Otherwise, `activate(bor)`.
431     * `initiate(new_bor)`
432
433     `}`
434   - Use `new_tag` for the new reference.
435 * Any time a reference is passed to us from "the outside world" (as function argument, loaded from memory, or returned from a callee; also below structs or enums but not below unions or pointer indirectons), we retag.
436   - Bump up the clock, and remember the old time as `new_tag`.
437   - Compute `new_bor` from `new_tag` and the type of the reference being created.
438   - `activate(bor)`.
439   - If this is a function argument coming in: `loc.borrows.push(FnBarrier(stack_height))`.
440   - `initiate(new_bor)`. Note that this is a NOP if `new_bor` is already active -- in particular, if the location is frozen and this is a shared reference with interior mutability, we do *not* push anything on top of the barrier. This is important, because we do not want to push that might unfreeze the location when being activated.
441   - Change reference tag to `new_tag`.
442 * Any time a raw pointer is created from a reference, we might have to do a raw reborrow.
443   - `activate(bor)`.
444   - `initiate(Mut(Raw))`. This is a NOP when coming from a shared reference.
445 * Any time a function returns, we have to clean up the barriers.
446   - Iterate over all of memory and remove the matching `FnBarrier`. This is where the "stack" becomes a bit of a lie, because we also remove barriers from the middle of a stack.<br>
447     This could be optimized by adding an indirection, so we just have to record somewhere that this function call has ended.
448
449
450 If you want to test your own understanding of "Stacked Borrows", I invite you to go back to [Section 2.2 of "Types as Contracts"]({% post_url 2017-07-17-types-as-contracts %}#22-examples) and look at the three examples here.
451 Ignore the `Validate` calls, that part is no longer relevant.
452 These are examples of optimizations we would like to be valid, and in fact all three of them are still valid with "Stacked Borrows".
453 Can you argue why that is the case?
454
455 ## Summary
456
457 I have described (yet) another Rust memory model that defines when a reference may be used to perform which memory operations.
458 The main design constraint of this model is that lifetimes should not matter for program execution.
459 To my own surprise, the model actually ended up being fairly simple, all things considered.
460
461 I think I covered most of the relevant features, though I will have to take a closer look at two-phase borrows and see if they need some further changes to the model.
462
463 Of course, now the big question is whether this model actually "works" -- does it permit all the code we want to permit (does it even permit all safe code), and does it rule out enough code such that we can get useful optimizations?
464 I hope to explore this question further in the following weeks by implementing a dynamic checker to test the model on real code.
465 It is just easier to answer these questions when you do not have to *manually* reevaluate all examples after every tiny change.
466 However, I can always use more examples, so if you think you found some interesting or surprising corner case, please let me know!
467
468 As always, if you have any questions or comments, feel free to [ask in the forums](https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153).