Appearance
| 1 | namespace IR.Values is | |
| 2 | use TypeTyped = Semantic.Types.Typed | |
| 3 | use Semantic.Types.Type | |
| 4 | ||
| 5 | // Wraps the creation of a stateless delegate (a zero-capture, | |
| 6 | // ground function literal) so it is built at most once and reused. | |
| 7 | // The first evaluation allocates the delegate and stores it into a | |
| 8 | // static cache field; every later evaluation loads the cached one. | |
| 9 | // Behaviour matches `inner` exactly because the wrapped literal | |
| 10 | // captures nothing and carries no type arguments, so a single | |
| 11 | // instance is interchangeable everywhere it is used. | |
| 12 | // | |
| 13 | // `function` is the literal's function where nothing it is built over | |
| 14 | // is needed to call it, so a back end free to place a constant can | |
| 15 | // hold one function value rather than fill the cache. | |
| 16 | class MEMOIZED_DELEGATE: Composite, TypeTyped is | |
| 17 | _inner: Value | |
| 18 | _cache_field: Semantic.Symbols.Field | |
| 19 | _type: Type | |
| 20 | ||
| 21 | type: Type => _type | |
| 22 | ||
| 23 | function: Semantic.Symbols.Function? | |
| 24 | ||
| 25 | inner: Value => _inner | |
| 26 | ||
| 27 | init( | |
| 28 | inner: Value, | |
| 29 | cache_field: Semantic.Symbols.Field, | |
| 30 | type: Type, | |
| 31 | function: Semantic.Symbols.Function? | |
| 32 | ) is | |
| 33 | super.init() | |
| 34 | ||
| 35 | self.function = function | |
| 36 | ||
| 37 | _inner = inner | |
| 38 | _cache_field = cache_field | |
| 39 | _type = type | |
| 40 | si | |
| 41 | ||
| 42 | referenced_function: Semantic.Symbols.Function? => _inner.referenced_function | |
| 43 | ||
| 44 | // Stay live rather than freezing to a pre-rendered RAW: gen() | |
| 45 | // mints a fresh cache-hoist label per emit site, so a delegate | |
| 46 | // emitted from more than one place gets distinct labels instead | |
| 47 | // of one baked into a RAW and duplicated. | |
| 48 | freeze() -> Value => self | |
| 49 | ||
| 50 | // The cached delegate, or, the first time, the inner value, | |
| 51 | // cached. | |
| 52 | expand() -> BLOCK is | |
| 53 | let expansion = IR.EXPANSION(_type) | |
| 54 | let result = expansion.temp("memoized", _type) | |
| 55 | ||
| 56 | expansion.store(result, Load.STATIC_FIELD(_cache_field)) | |
| 57 | ||
| 58 | let cached = expansion.region() | |
| 59 | ||
| 60 | expansion.exit_if(cached, IR.BRANCH.NZ, result.load()) | |
| 61 | expansion.store(result, _inner) | |
| 62 | expansion.add(Store.STATIC_FIELD(_cache_field, result.load())) | |
| 63 | expansion.close(cached) | |
| 64 | ||
| 65 | expansion.add(result.load()) | |
| 66 | ||
| 67 | return expansion.result | |
| 68 | si | |
| 69 | ||
| 70 | to_string() -> string => | |
| 71 | "memoized-delegate:[{_type}]({_inner})" | |
| 72 | si | |
| 73 | si |