mu/037abandon.cc

247 lines
9.2 KiB
C++
Raw Normal View History

//: Reclaiming memory when it's no longer used.
2016-05-15 16:27:03 +00:00
//: The top of the address layer has the complete life cycle of memory.
:(scenario new_reclaim)
def main [
1:address:num <- new number:type
2:num <- copy 1:address:num # because 1 will get reset during abandon below
1:address:num <- copy 0 # abandon
3:address:num <- new number:type # must be same size as abandoned memory to reuse
4:num <- copy 3:address:num
2016-09-17 07:46:03 +00:00
5:bool <- equal 2:num, 4:num
]
# both allocations should have returned the same address
2016-05-05 23:58:46 +00:00
+mem: storing 1 in location 5
2016-08-17 18:54:28 +00:00
:(before "End Decrement Refcount(old_address, payload_type, payload_size)")
if (old_refcount == 0) {
trace("mem") << "automatically abandoning " << old_address << end();
2016-05-18 01:32:41 +00:00
abandon(old_address, payload_type, payload_size);
}
//: When abandoning addresses we'll save them to a 'free list', segregated by size.
:(before "End routine Fields")
map<int, int> free_list;
:(code)
2016-05-18 01:32:41 +00:00
void abandon(int address, const type_tree* payload_type, int payload_size) {
trace("abandon") << "updating refcounts inside " << address << ": " << to_string(payload_type) << end();
//? Total_free += size;
//? ++Num_free;
//? cerr << "abandon: " << size << '\n';
2016-05-18 01:32:41 +00:00
// decrement any contained refcounts
3309 Rip out everything to fix one failing unit test (commit 3290; type abbreviations). This commit does several things at once that I couldn't come up with a clean way to unpack: A. It moves to a new representation for type trees without changing the actual definition of the `type_tree` struct. B. It adds unit tests for our type metadata precomputation, so that errors there show up early and in a simpler setting rather than dying when we try to load Mu code. C. It fixes a bug, guarding against infinite loops when precomputing metadata for recursive shape-shifting containers. To do this it uses a dumb way of comparing type_trees, comparing their string representations instead. That is likely incredibly inefficient. Perhaps due to C, this commit has made Mu incredibly slow. Running all tests for the core and the edit/ app now takes 6.5 minutes rather than 3.5 minutes. == more notes and details I've been struggling for the past week now to back out of a bad design decision, a premature optimization from the early days: storing atoms directly in the 'value' slot of a cons cell rather than creating a special 'atom' cons cell and storing it on the 'left' slot. In other words, if a cons cell looks like this: o / | \ left val right ..then the type_tree (a b c) used to look like this (before this commit): o | \ a o | \ b o | \ c null ..rather than like this 'classic' approach to s-expressions which never mixes val and right (which is what we now have): o / \ o o | / \ a o o | / \ b o null | c The old approach made several operations more complicated, most recently the act of replacing a (possibly atom/leaf) sub-tree with another. That was the final straw that got me to realize the contortions I was going through to save a few type_tree nodes (cons cells). Switching to the new approach was hard partly because I've been using the old approach for so long and type_tree manipulations had pervaded everything. Another issue I ran into was the realization that my layers were not cleanly separated. Key parts of early layers (precomputing type metadata) existed purely for far later ones (shape-shifting types). Layers I got repeatedly stuck at: 1. the transform for precomputing type sizes (layer 30) 2. type-checks on merge instructions (layer 31) 3. the transform for precomputing address offsets in types (layer 36) 4. replace operations in supporting shape-shifting recipes (layer 55) After much thrashing I finally noticed that it wasn't the entirety of these layers that was giving me trouble, but just the type metadata precomputation, which had bugs that weren't manifesting until 30 layers later. Or, worse, when loading .mu files before any tests had had a chance to run. A common failure mode was running into types at run time that I hadn't precomputed metadata for at transform time. Digging into these bugs got me to realize that what I had before wasn't really very good, but a half-assed heuristic approach that did a whole lot of extra work precomputing metadata for utterly meaningless types like `((address number) 3)` which just happened to be part of a larger type like `(array (address number) 3)`. So, I redid it all. I switched the representation of types (because the old representation made unit tests difficult to retrofit) and added unit tests to the metadata precomputation. I also made layer 30 only do the minimal metadata precomputation it needs for the concepts introduced until then. In the process, I also made the precomputation more correct than before, and added hooks in the right place so that I could augment the logic when I introduced shape-shifting containers. == lessons learned There's several levels of hygiene when it comes to layers: 1. Every layer introduces precisely what it needs and in the simplest way possible. If I was building an app until just that layer, nothing would seem over-engineered. 2. Some layers are fore-shadowing features in future layers. Sometimes this is ok. For example, layer 10 foreshadows containers and arrays and so on without actually supporting them. That is a net win because it lets me lay out the core of Mu's data structures out in one place. But if the fore-shadowing gets too complex things get nasty. Not least because it can be hard to write unit tests for features before you provide the plumbing to visualize and manipulate them. 3. A layer is introducing features that are tested only in later layers. 4. A layer is introducing features with tests that are invalidated in later layers. (This I knew from early on to be an obviously horrendous idea.) Summary: avoid Level 2 (foreshadowing layers) as much as possible. Tolerate it indefinitely for small things where the code stays simple over time, but become strict again when things start to get more complex. Level 3 is mostly a net lose, but sometimes it can be expedient (a real case of the usually grossly over-applied term "technical debt"), and it's better than the conventional baseline of no layers and no scenarios. Just clean it up as soon as possible. Definitely avoid layer 4 at any time. == minor lessons Avoid unit tests for trivial things, write scenarios in context as much as possible. But within those margins unit tests are fine. Just introduce them before any scenarios (commit 3297). Reorganizing layers can be easy. Just merge layers for starters! Punt on resplitting them in some new way until you've gotten them to work. This is the wisdom of Refactoring: small steps. What made it hard was not wanting to merge *everything* between layer 30 and 55. The eventual insight was realizing I just need to move those two full-strength transforms and nothing else.
2016-09-10 01:32:52 +00:00
if (is_mu_array(payload_type)) {
reagent/*local*/ element;
2016-05-18 01:32:41 +00:00
element.type = copy_array_element(payload_type);
int array_length = get_or_insert(Memory, address+/*skip refcount*/1);
assert(element.type->name != "array");
int element_size = size_of(element);
2016-10-20 05:10:35 +00:00
for (int i = 0; i < array_length; ++i) {
2016-08-21 15:38:20 +00:00
element.set_value(address + /*skip refcount and length*/2 + i*element_size);
decrement_any_refcounts(element);
2016-05-18 01:32:41 +00:00
}
}
else if (is_mu_container(payload_type) || is_mu_exclusive_container(payload_type)) {
reagent tmp;
tmp.type = new type_tree(*payload_type);
tmp.set_value(address + /*skip refcount*/1);
decrement_any_refcounts(tmp);
2016-05-18 01:32:41 +00:00
}
// clear memory
2016-10-20 05:10:35 +00:00
for (int curr = address; curr < address+payload_size; ++curr)
put(Memory, curr, 0);
// append existing free list to address
trace("abandon") << "saving " << address << " in free-list of size " << payload_size << end();
2016-05-18 01:32:41 +00:00
put(Memory, address, get_or_insert(Current_routine->free_list, payload_size));
put(Current_routine->free_list, payload_size, address);
}
:(after "Allocate Special-cases")
if (get_or_insert(Current_routine->free_list, size)) {
trace("abandon") << "picking up space from free-list of size " << size << end();
int result = get_or_insert(Current_routine->free_list, size);
trace("mem") << "new alloc from free list: " << result << end();
put(Current_routine->free_list, size, get_or_insert(Memory, result));
put(Memory, result, 0);
2016-10-20 05:10:35 +00:00
for (int curr = result; curr < result+size; ++curr) {
if (get_or_insert(Memory, curr) != 0) {
raise << maybe(current_recipe_name()) << "memory in free list was not zeroed out: " << curr << '/' << result << "; somebody wrote to us after free!!!\n" << end();
break; // always fatal
}
}
return result;
}
:(scenario new_differing_size_no_reclaim)
def main [
1:address:num <- new number:type
2:num <- copy 1:address:num
1:address:num <- copy 0 # abandon
3:address:array:num <- new number:type, 2 # different size
4:num <- copy 3:address:array:num
2016-09-17 07:46:03 +00:00
5:bool <- equal 2:num, 4:num
]
# no reuse
2016-05-05 23:58:46 +00:00
+mem: storing 0 in location 5
:(scenario new_reclaim_array)
def main [
1:address:array:num <- new number:type, 2
2:num <- copy 1:address:array:num
1:address:array:num <- copy 0 # abandon
3:address:array:num <- new number:type, 2 # same size
4:num <- copy 3:address:array:num
2016-09-17 07:46:03 +00:00
5:bool <- equal 2:num, 4:num
]
2016-05-18 00:26:55 +00:00
# both calls to new returned identical addresses
2016-05-05 23:58:46 +00:00
+mem: storing 1 in location 5
2016-05-18 00:26:55 +00:00
:(scenario abandon_on_overwrite)
def main [
1:address:num <- new number:type
# over-writing one allocation with another
1:address:num <- new number:type
1:address:num <- copy 0
]
+run: {1: ("address" "number")} <- new {number: "type"}
+mem: incrementing refcount of 1000: 0 -> 1
+run: {1: ("address" "number")} <- new {number: "type"}
+mem: automatically abandoning 1000
2016-05-18 00:26:55 +00:00
:(scenario abandon_after_call)
def main [
1:address:num <- new number:type
# passing in addresses to recipes increments refcount
foo 1:address:num
1:address:num <- copy 0
]
def foo [
2:address:num <- next-ingredient
# return does NOT yet decrement refcount; memory must be explicitly managed
2:address:num <- copy 0
]
+run: {1: ("address" "number")} <- new {number: "type"}
+mem: incrementing refcount of 1000: 0 -> 1
+run: foo {1: ("address" "number")}
# leave ambiguous precisely when the next increment happens
+mem: incrementing refcount of 1000: 1 -> 2
+run: {2: ("address" "number")} <- copy {0: "literal"}
+mem: decrementing refcount of 1000: 2 -> 1
+run: {1: ("address" "number")} <- copy {0: "literal"}
+mem: decrementing refcount of 1000: 1 -> 0
+mem: automatically abandoning 1000
2016-05-18 00:26:55 +00:00
:(scenario abandon_on_overwrite_array)
def main [
1:num <- copy 30
# allocate an array
10:address:array:num <- new number:type, 20
11:num <- copy 10:address:array:num # doesn't increment refcount
# allocate another array in its place, implicitly freeing the previous allocation
10:address:array:num <- new number:type, 25
]
+run: {10: ("address" "array" "number")} <- new {number: "type"}, {25: "literal"}
# abandoned array is of old size (20, not 25)
2016-05-18 01:32:41 +00:00
+abandon: saving 1000 in free-list of size 22
:(scenario refcounts_abandon_address_in_container)
# container containing an address
container foo [
x:address:num
2016-05-18 01:32:41 +00:00
]
def main [
1:address:num <- new number:type
2016-05-18 01:32:41 +00:00
2:address:foo <- new foo:type
*2:address:foo <- put *2:address:foo, x:offset, 1:address:num
1:address:num <- copy 0
2016-05-18 01:32:41 +00:00
2:address:foo <- copy 0
]
+run: {1: ("address" "number")} <- new {number: "type"}
+mem: incrementing refcount of 1000: 0 -> 1
+run: {2: ("address" "foo")} <- new {foo: "type"}
+mem: incrementing refcount of 1002: 0 -> 1
+run: {2: ("address" "foo"), "lookup": ()} <- put {2: ("address" "foo"), "lookup": ()}, {x: "offset"}, {1: ("address" "number")}
+mem: incrementing refcount of 1000: 1 -> 2
+run: {1: ("address" "number")} <- copy {0: "literal"}
+mem: decrementing refcount of 1000: 2 -> 1
+run: {2: ("address" "foo")} <- copy {0: "literal"}
# start abandoning container containing address
+mem: decrementing refcount of 1002: 1 -> 0
# nested abandon
+mem: decrementing refcount of 1000: 1 -> 0
+abandon: saving 1000 in free-list of size 2
# actually abandon the container containing address
+abandon: saving 1002 in free-list of size 2
# todo: move past dilated reagent
:(scenario refcounts_abandon_address_in_array)
def main [
1:address:num <- new number:type
2:address:array:address:num <- new {(address number): type}, 3
*2:address:array:address:num <- put-index *2:address:array:address:num, 1, 1:address:num
1:address:num <- copy 0
2:address:array:address:num <- copy 0
2016-05-18 01:32:41 +00:00
]
+run: {1: ("address" "number")} <- new {number: "type"}
+mem: incrementing refcount of 1000: 0 -> 1
+run: {2: ("address" "array" "address" "number"), "lookup": ()} <- put-index {2: ("address" "array" "address" "number"), "lookup": ()}, {1: "literal"}, {1: ("address" "number")}
+mem: incrementing refcount of 1000: 1 -> 2
+run: {1: ("address" "number")} <- copy {0: "literal"}
+mem: decrementing refcount of 1000: 2 -> 1
+run: {2: ("address" "array" "address" "number")} <- copy {0: "literal"}
# nested abandon
+mem: decrementing refcount of 1000: 1 -> 0
+abandon: saving 1000 in free-list of size 2
:(scenario refcounts_abandon_address_in_container_in_array)
# container containing an address
container foo [
x:address:num
2016-05-18 01:32:41 +00:00
]
def main [
1:address:num <- new number:type
2016-05-18 01:32:41 +00:00
2:address:array:foo <- new foo:type, 3
3:foo <- merge 1:address:num
2016-05-18 01:32:41 +00:00
*2:address:array:foo <- put-index *2:address:array:foo, 1, 3:foo
1:address:num <- copy 0
2016-05-18 01:32:41 +00:00
3:foo <- merge 0
2:address:array:foo <- copy 0
]
+run: {1: ("address" "number")} <- new {number: "type"}
+mem: incrementing refcount of 1000: 0 -> 1
+run: {3: "foo"} <- merge {1: ("address" "number")}
+mem: incrementing refcount of 1000: 1 -> 2
+run: {2: ("address" "array" "foo"), "lookup": ()} <- put-index {2: ("address" "array" "foo"), "lookup": ()}, {1: "literal"}, {3: "foo"}
+mem: incrementing refcount of 1000: 2 -> 3
+run: {1: ("address" "number")} <- copy {0: "literal"}
+mem: decrementing refcount of 1000: 3 -> 2
+run: {3: "foo"} <- merge {0: "literal"}
+mem: decrementing refcount of 1000: 2 -> 1
+run: {2: ("address" "array" "foo")} <- copy {0: "literal"}
# nested abandon
+mem: decrementing refcount of 1000: 1 -> 0
+abandon: saving 1000 in free-list of size 2
:(scenario refcounts_abandon_array_within_container)
container foo [
x:address:array:num
]
def main [
1:address:array:num <- new number:type, 3
2:foo <- merge 1:address:array:num
1:address:array:num <- copy 0
2:foo <- copy 0
]
+run: {1: ("address" "array" "number")} <- new {number: "type"}, {3: "literal"}
+mem: incrementing refcount of 1000: 0 -> 1
+run: {2: "foo"} <- merge {1: ("address" "array" "number")}
+mem: incrementing refcount of 1000: 1 -> 2
+run: {1: ("address" "array" "number")} <- copy {0: "literal"}
+mem: decrementing refcount of 1000: 2 -> 1
+run: {2: "foo"} <- copy {0: "literal"}
+mem: decrementing refcount of 1000: 1 -> 0
+mem: automatically abandoning 1000
# make sure we save it in a free-list of the appropriate size
+abandon: saving 1000 in free-list of size 5