| @@ -27,18 +27,25 @@ const PRELUDE: &str = include_str!("prelude.h"); |
| 27 | 27 | /// costs a compiler process and loses inlining across units. |
| 28 | 28 | const MIN_UNIT_BYTES: usize = 64 * 1024; |
| 29 | 29 | |
| 30 | | −/// The C of a whole program, in at most `units` translation units (one if |
| 31 | | −/// the program is small). With `sources`, the functions that have a span |
| 32 | | −/// are emitted last, under `#line` directives pointing at their source; |
| 33 | | −/// everything before them (runtime glue, constants, closure entries, |
| 34 | | −/// `main`, generated functions) keeps its own C line numbers, so no |
| 35 | | −/// directive has to point back into the generated file. |
| 30 | +/// A C translation unit: its name (empty for a program in one unit) and |
| 31 | +/// its text. |
| 32 | +pub(crate) type Unit = (String, String); |
| 33 | + |
| 34 | +/// The C of a whole program: one translation unit, or, with `units` above |
| 35 | +/// one and a program large enough, one per module (ADR 0029). With |
| 36 | +/// `sources`, the functions that have a span are emitted last in each |
| 37 | +/// unit, under `#line` directives pointing at their source; everything |
| 38 | +/// before them (runtime glue, constants, closure entries, `main`, |
| 39 | +/// generated functions) keeps its own C line numbers, so no directive has |
| 40 | +/// to point back into the generated file. |
| 36 | 41 | /// |
| 37 | | −/// Several units are compiled in parallel. Each starts with the same |
| 38 | | −/// declarations (runtime glue, externs, literals, prototypes and constant |
| 39 | | −/// dictionaries, which stay `static` copies so calls through them are |
| 40 | | −/// still direct); the first also has the closure entries and `main`; the |
| 41 | | −/// functions are split between them in order, by size. Functions are then |
| 42 | +/// A unit holds a module's functions and the entries of their closures; |
| 43 | +/// the specialiser's copies have a unit of their own, and so do `main` and |
| 44 | +/// `tl_entry`. Each starts with the declarations its functions use and no |
| 45 | +/// others: externs, literals, prototypes, and the constant dictionaries |
| 46 | +/// they read (`static` copies, so calls through them are still direct). |
| 47 | +/// Names are the functions' own (`symbol`), so a unit's C changes only |
| 48 | +/// when its module, or what it uses of others, does. Functions are |
| 42 | 49 | /// `TL_FN`: `static` with one unit, external with several. |
| 43 | 50 | pub(crate) fn emit( |
| 44 | 51 | program: &Program, |
| @@ -46,20 +53,19 @@ pub(crate) fn emit( |
| 46 | 53 | reachable: &BTreeSet<FnId>, |
| 47 | 54 | sources: Option<&SourceDb>, |
| 48 | 55 | units: usize, |
| 49 | | −) -> Result<Vec<String>, Unsupported> { |
| 56 | +) -> Result<Vec<Unit>, Unsupported> { |
| 50 | 57 | let mut e = Emitter { |
| 51 | 58 | program, |
| 52 | 59 | sources, |
| 53 | | − lits: String::new(), |
| 54 | | − lit_ids: HashMap::new(), |
| 60 | + syms: symbols(program, reachable), |
| 61 | + lits: BTreeMap::new(), |
| 55 | 62 | entries: BTreeSet::new(), |
| 56 | | − externs: BTreeMap::new(), |
| 57 | | − thunks: String::new(), |
| 58 | | − constants: BTreeSet::new(), |
| 63 | + extern_arity: BTreeMap::new(), |
| 64 | + thunks: BTreeMap::new(), |
| 65 | + constants: BTreeMap::new(), |
| 59 | 66 | never_unwinds: BTreeSet::new(), |
| 60 | | − constant_defs: String::new(), |
| 61 | | − generated: Vec::new(), |
| 62 | | − located: Vec::new(), |
| 67 | + functions: BTreeMap::new(), |
| 68 | + uses: Uses::default(), |
| 63 | 69 | labels: 0, |
| 64 | 70 | line: None, |
| 65 | 71 | written: None, |
| @@ -67,115 +73,156 @@ pub(crate) fn emit( |
| 67 | 73 | for f in reachable { |
| 68 | 74 | e.constant(*f, &program.fns[*f as usize]); |
| 69 | 75 | } |
| 70 | | − e.never_unwinds = crate::unwind::never_unwinding(program, reachable, &e.constants); |
| 76 | + let constant_ids: BTreeSet<FnId> = e.constants.keys().copied().collect(); |
| 77 | + e.never_unwinds = crate::unwind::never_unwinding(program, reachable, &constant_ids); |
| 71 | 78 | for f in reachable { |
| 72 | | − if !e.constants.contains(f) { |
| 79 | + if !e.constants.contains_key(f) { |
| 73 | 80 | e.function(*f, &program.fns[*f as usize])?; |
| 74 | 81 | } |
| 75 | 82 | } |
| 76 | | − let size: usize = e.generated.iter().chain(&e.located).map(String::len).sum(); |
| 77 | | − let units = units.min(size / MIN_UNIT_BYTES).max(1); |
| 78 | | − let mut out = String::from(PRELUDE); |
| 79 | | − let _ = writeln!( |
| 80 | | − out, |
| 81 | | − "_Static_assert(TL_XARGS == {XARGS}, \"louise and louise_rt.h disagree on TL_XARGS\");\n" |
| 82 | | − ); |
| 83 | | − let _ = writeln!( |
| 84 | | − out, |
| 85 | | − "#define TL_FN{}\n", |
| 86 | | − if units == 1 { " static" } else { "" } |
| 87 | | − ); |
| 88 | | − for (sym, arity) in &e.externs { |
| 89 | | − let params: String = (0..*arity).map(|_| ", tl_value").collect(); |
| 90 | | − let _ = writeln!(out, "tl_value {sym}(tl_ctx *ctx{params});"); |
| 91 | | − } |
| 92 | | − out.push_str(&e.thunks); |
| 93 | | − out.push_str(&e.lits); |
| 94 | | − out.push('\n'); |
| 95 | | − for f in reachable.difference(&e.constants) { |
| 96 | | − let _ = writeln!( |
| 97 | | − out, |
| 98 | | − "TL_FN tl_value f{f}(tl_ctx *ctx, tl_value a0, tl_value a1, tl_value a2, tl_value a3, tl_value a4, tl_value a5);" |
| 99 | | − ); |
| 83 | + let main = e.main(entries)?; |
| 84 | + let size: usize = e.functions.values().map(|f| f.text.len()).sum(); |
| 85 | + let split = units > 1 && size >= MIN_UNIT_BYTES; |
| 86 | + // The unit of each function: its module's, or one for all. |
| 87 | + let unit_of = |f: FnId| -> String { |
| 88 | + if !split { |
| 89 | + return String::new(); |
| 90 | + } |
| 91 | + match &program.fns[f as usize].module { |
| 92 | + Some(module) => module.replace('/', "."), |
| 93 | + None => "+specialised".into(), |
| 94 | + } |
| 95 | + }; |
| 96 | + let mut groups: BTreeMap<String, Vec<FnId>> = BTreeMap::new(); |
| 97 | + for f in e.functions.keys() { |
| 98 | + groups.entry(unit_of(*f)).or_default().push(*f); |
| 100 | 99 | } |
| 101 | | − for (f, n) in &e.entries { |
| 102 | | − let _ = writeln!( |
| 103 | | − out, |
| 104 | | − "TL_FN tl_value f{f}_c{n}(tl_ctx *ctx, tl_value a0, tl_value a1, tl_value a2, tl_value a3, tl_value a4, tl_value a5);" |
| 105 | | − ); |
| 100 | + for (f, _) in &e.entries { |
| 101 | + groups.entry(unit_of(*f)).or_default(); |
| 106 | 102 | } |
| 107 | | − out.push('\n'); |
| 108 | | − out.push_str(&e.constant_defs); |
| 109 | | − let header = out.clone(); |
| 110 | | − for (f, n) in e.entries.clone() { |
| 111 | | − e.closure_entry(&mut out, f, n); |
| 112 | | − } |
| 113 | | − // `main` (or a test) receives a root capability per label of its row: |
| 114 | | − // only `proc` can be there (checked by `louise_core::runnable`). |
| 115 | | − let mut cases = String::new(); |
| 116 | | − for (k, entry) in entries.iter().enumerate() { |
| 117 | | − let n = program.fns[*entry as usize].params.len(); |
| 118 | | − if n > REGS { |
| 119 | | − return Err(Unsupported( |
| 120 | | − "an entry function with many capabilities".into(), |
| 121 | | − )); |
| 122 | | − } |
| 123 | | − let decl = &program.fns[*entry as usize]; |
| 124 | | − let _ = writeln!(cases, " case {k}: {{"); |
| 125 | | − for i in 0..n { |
| 126 | | − let _ = writeln!( |
| 127 | | − cases, |
| 128 | | − " tl_value c{i} = tl_root_cap(ctx, {});", |
| 129 | | − PROC_OPS.len() |
| 130 | | − ); |
| 103 | + let mut result = Vec::new(); |
| 104 | + for (name, fns) in &groups { |
| 105 | + let closure_entries: Vec<(FnId, usize)> = e |
| 106 | + .entries |
| 107 | + .iter() |
| 108 | + .filter(|(f, _)| &unit_of(*f) == name) |
| 109 | + .copied() |
| 110 | + .collect(); |
| 111 | + let with_main = !split; |
| 112 | + let mut uses = Uses::default(); |
| 113 | + for f in fns { |
| 114 | + uses.add(&e.functions[f].uses); |
| 115 | + uses.fns.insert(*f); |
| 131 | 116 | } |
| 132 | | − let caps: Vec<String> = (0..n).map(|i| format!("c{i}")).collect(); |
| 133 | | − let _ = writeln!( |
| 134 | | − cases, |
| 135 | | − " tl_value r = f{entry}(ctx, {});", |
| 136 | | − register_args(&caps) |
| 137 | | − ); |
| 138 | | − // A borrowed capability is still the caller's. |
| 139 | | − for i in &decl.borrowed { |
| 140 | | − let _ = writeln!(cases, " tl_drop(ctx, c{i});"); |
| 117 | + for (f, n) in &closure_entries { |
| 118 | + uses.fns.insert(*f); |
| 119 | + uses.entries.insert((*f, *n)); |
| 120 | + } |
| 121 | + if with_main { |
| 122 | + uses.add(&main.uses); |
| 123 | + } |
| 124 | + let mut out = e.header(&uses, !split); |
| 125 | + for (f, n) in &closure_entries { |
| 126 | + e.closure_entry(&mut out, *f, *n); |
| 141 | 127 | } |
| 142 | | − let _ = writeln!(cases, " return r;\n }}"); |
| 128 | + if with_main { |
| 129 | + out.push_str(&main.text); |
| 130 | + } |
| 131 | + // Generated functions come before located ones, so no `#line` |
| 132 | + // directive applies to them; each kind in the order of names. |
| 133 | + let mut order: Vec<FnId> = fns.clone(); |
| 134 | + order.sort_by_key(|f| (e.functions[f].located, e.syms[f].clone())); |
| 135 | + for f in order { |
| 136 | + out.push_str(&e.functions[&f].text); |
| 137 | + } |
| 138 | + result.push((name.clone(), out)); |
| 143 | 139 | } |
| 144 | | − let _ = write!( |
| 145 | | − out, |
| 146 | | − r#" |
| 147 | | −static int tl_which; |
| 140 | + if split { |
| 141 | + let out = e.header(&main.uses, false) + &main.text; |
| 142 | + result.push(("+main".into(), out)); |
| 143 | + } |
| 144 | + if result.is_empty() { |
| 145 | + result.push((String::new(), e.header(&main.uses, true) + &main.text)); |
| 146 | + } |
| 147 | + Ok(result) |
| 148 | +} |
| 148 | 149 | |
| 149 | | −static tl_value tl_entry(tl_ctx *ctx) {{ |
| 150 | | − switch (tl_which) {{ |
| 151 | | −{cases} default: return TL_UNIT; |
| 152 | | − }} |
| 153 | | −}} |
| 150 | +/// What a function's C refers to, and so what a unit holding it must |
| 151 | +/// declare. |
| 152 | +#[derive(Default, Clone)] |
| 153 | +struct Uses { |
| 154 | + /// Functions called, and constants read. |
| 155 | + fns: BTreeSet<FnId>, |
| 156 | + /// Closure entries: (function, number of captures). |
| 157 | + entries: BTreeSet<(FnId, usize)>, |
| 158 | + /// Literal blocks, by name. |
| 159 | + lits: BTreeSet<String>, |
| 160 | + /// Foreign symbols (not the runtime's: `louise_rt.h` declares those). |
| 161 | + externs: BTreeSet<String>, |
| 162 | + /// Thunks running `blocking` externs on the blocking pool. |
| 163 | + thunks: BTreeSet<String>, |
| 164 | +} |
| 154 | 165 | |
| 155 | | −int main(int argc, char **argv) {{ |
| 156 | | − tl_abi_check(TL_ABI_VERSION); |
| 157 | | − tl_which = argc > 1 ? atoi(argv[1]) : 0; |
| 158 | | − int code = tl_main_program(tl_entry); |
| 159 | | − tl_report_leaks(); |
| 160 | | − return code; |
| 161 | | −}} |
| 166 | +impl Uses { |
| 167 | + fn add(&mut self, other: &Uses) { |
| 168 | + self.fns.extend(&other.fns); |
| 169 | + self.entries.extend(&other.entries); |
| 170 | + self.lits.extend(other.lits.iter().cloned()); |
| 171 | + self.externs.extend(other.externs.iter().cloned()); |
| 172 | + self.thunks.extend(other.thunks.iter().cloned()); |
| 173 | + } |
| 174 | +} |
| 162 | 175 | |
| 163 | | −"# |
| 164 | | − ); |
| 165 | | − // Generated functions come before located ones in every unit, so no |
| 166 | | − // `#line` directive applies to them. |
| 167 | | − let functions: Vec<String> = e.generated.into_iter().chain(e.located).collect(); |
| 168 | | − let mut result = vec![out]; |
| 169 | | − let mut done = 0; |
| 170 | | − for f in functions { |
| 171 | | − // Start the next unit once this one has its share. |
| 172 | | − if done >= size * result.len() / units && result.len() < units { |
| 173 | | − result.push(header.clone()); |
| 174 | | − } |
| 175 | | − done += f.len(); |
| 176 | | − result.last_mut().expect("one unit at least").push_str(&f); |
| 176 | +/// A function's C, with what it uses. |
| 177 | +struct Emitted { |
| 178 | + text: String, |
| 179 | + uses: Uses, |
| 180 | + /// Whether it has a source location (and `#line` directives). |
| 181 | + located: bool, |
| 182 | +} |
| 183 | + |
| 184 | +/// A C identifier for every function in `fns`, made from its module and |
| 185 | +/// name, so that it stays the same when other functions come and go |
| 186 | +/// (ADR 0029): `lf_` then the name with every character but letters and |
| 187 | +/// digits escaped (`_` as `__`, others as `_` and their UTF-8 bytes in |
| 188 | +/// hex), shortened with a hash past 120 characters. Two functions with |
| 189 | +/// the same name (which lowering avoids) get `_2`, `_3`... in id order. |
| 190 | +fn symbols(program: &Program, fns: &BTreeSet<FnId>) -> HashMap<FnId, String> { |
| 191 | + let mut seen: HashMap<String, usize> = HashMap::new(); |
| 192 | + let mut syms = HashMap::new(); |
| 193 | + for f in fns { |
| 194 | + let mut sym = symbol(&program.fns[*f as usize]); |
| 195 | + let n = seen.entry(sym.clone()).or_insert(0); |
| 196 | + *n += 1; |
| 197 | + if *n > 1 { |
| 198 | + let _ = write!(sym, "_{n}"); |
| 199 | + } |
| 200 | + syms.insert(*f, sym); |
| 177 | 201 | } |
| 178 | | − Ok(result) |
| 202 | + syms |
| 203 | +} |
| 204 | + |
| 205 | +/// The C name of a function, before telling apart two with the same |
| 206 | +/// module and name (see [`symbols`]). |
| 207 | +pub fn symbol(decl: &FnDecl) -> String { |
| 208 | + let full = format!("{}:{}", decl.module.as_deref().unwrap_or("*"), decl.name); |
| 209 | + let mut sym = String::from("lf_"); |
| 210 | + for b in full.bytes() { |
| 211 | + match b { |
| 212 | + b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => sym.push(b as char), |
| 213 | + b'_' => sym.push_str("__"), |
| 214 | + b => { |
| 215 | + let _ = write!(sym, "_{b:02x}"); |
| 216 | + } |
| 217 | + } |
| 218 | + } |
| 219 | + if sym.len() > 120 { |
| 220 | + let mut h = std::collections::hash_map::DefaultHasher::new(); |
| 221 | + std::hash::Hash::hash(&full, &mut h); |
| 222 | + sym.truncate(100); |
| 223 | + let _ = write!(sym, "_{:016x}", std::hash::Hasher::finish(&h)); |
| 224 | + } |
| 225 | + sym |
| 179 | 226 | } |
| 180 | 227 | |
| 181 | 228 | /// The function being emitted. |
| @@ -224,24 +271,27 @@ struct Emitter<'p> { |
| 224 | 271 | /// The source files, to point `#line` directives at (none: no |
| 225 | 272 | /// directives). |
| 226 | 273 | sources: Option<&'p SourceDb>, |
| 227 | | − /// Static literal blocks. |
| 228 | | − lits: String, |
| 229 | | − lit_ids: HashMap<String, usize>, |
| 274 | + /// The C name of every reachable function ([`symbols`]). |
| 275 | + syms: HashMap<FnId, String>, |
| 276 | + /// Static literal blocks, by name. |
| 277 | + lits: BTreeMap<String, String>, |
| 230 | 278 | /// Closure entries needed: (function, number of captures). |
| 231 | 279 | entries: BTreeSet<(FnId, usize)>, |
| 232 | | − /// Foreign symbols to declare, with their arity. |
| 233 | | − externs: BTreeMap<String, usize>, |
| 234 | | − /// Thunks for `blocking` externs. |
| 235 | | − thunks: String, |
| 280 | + /// Foreign symbols seen, with their arity. |
| 281 | + extern_arity: BTreeMap<String, usize>, |
| 282 | + /// Thunks for `blocking` externs, by name. |
| 283 | + thunks: BTreeMap<String, String>, |
| 236 | 284 | /// Functions that never unwind: calls of them need no yield check, and |
| 237 | 285 | /// they have no preemption point (`crate::unwind`). |
| 238 | 286 | never_unwinds: BTreeSet<FnId>, |
| 239 | | − /// Functions emitted as a static, immortal value (see `constant`). |
| 240 | | − constants: BTreeSet<FnId>, |
| 241 | | − constant_defs: String, |
| 242 | | − /// Functions without a source location, then those with one. |
| 243 | | − generated: Vec<String>, |
| 244 | | − located: Vec<String>, |
| 287 | + /// Functions emitted as a static, immortal value (see `constant`): |
| 288 | + /// their definitions, with what they use. |
| 289 | + constants: BTreeMap<FnId, (String, Uses)>, |
| 290 | + /// The other functions' C. |
| 291 | + functions: BTreeMap<FnId, Emitted>, |
| 292 | + /// What the function being emitted uses so far. |
| 293 | + uses: Uses, |
| 294 | + /// Block labels, numbered within each function. |
| 245 | 295 | labels: u32, |
| 246 | 296 | /// The source line of the code being emitted (none outside located |
| 247 | 297 | /// functions), and the line the last `#line` directive set. |
| @@ -274,13 +324,16 @@ impl Emitter<'_> { |
| 274 | 324 | ))); |
| 275 | 325 | } |
| 276 | 326 | let mut out = String::new(); |
| 327 | + self.uses = Uses::default(); |
| 328 | + self.labels = 0; |
| 277 | 329 | let _ = writeln!(out, "/* {} */", decl.name); |
| 278 | 330 | self.line = decl.span.and_then(|s| self.line_of(s)); |
| 279 | 331 | self.written = None; |
| 280 | 332 | self.sync_line(&mut out); |
| 281 | 333 | let _ = writeln!( |
| 282 | 334 | out, |
| 283 | | − "TL_FN tl_value f{id}(tl_ctx *ctx, tl_value a0, tl_value a1, tl_value a2, tl_value a3, tl_value a4, tl_value a5) {{" |
| 335 | + "TL_FN tl_value {}(tl_ctx *ctx, tl_value a0, tl_value a1, tl_value a2, tl_value a3, tl_value a4, tl_value a5) {{", |
| 336 | + self.syms[&id] |
| 284 | 337 | ); |
| 285 | 338 | let params: BTreeSet<VarId> = decl.params.iter().copied().collect(); |
| 286 | 339 | for (i, p) in decl.params.iter().enumerate() { |
| @@ -320,14 +373,137 @@ impl Emitter<'_> { |
| 320 | 373 | let func = Func { id, decl }; |
| 321 | 374 | self.expr(&mut out, &func, &decl.body, Dest::Return, owned, 1)?; |
| 322 | 375 | out.push_str("}\n\n"); |
| 323 | | − if self.line.is_some() { |
| 324 | | − self.located.push(pin_lines(&out)); |
| 325 | | − } else { |
| 326 | | − self.generated.push(out); |
| 327 | | − } |
| 376 | + let located = self.line.is_some(); |
| 377 | + let text = if located { pin_lines(&out) } else { out }; |
| 378 | + let uses = std::mem::take(&mut self.uses); |
| 379 | + self.functions.insert( |
| 380 | + id, |
| 381 | + Emitted { |
| 382 | + text, |
| 383 | + uses, |
| 384 | + located, |
| 385 | + }, |
| 386 | + ); |
| 328 | 387 | Ok(()) |
| 329 | 388 | } |
| 330 | 389 | |
| 390 | + /// `tl_entry` and `main`: `main` (or a test) receives a root |
| 391 | + /// capability per label of its row: only `proc` can be there (checked |
| 392 | + /// by `louise_core::runnable`). |
| 393 | + fn main(&mut self, entries: &[FnId]) -> Result<Emitted, Unsupported> { |
| 394 | + let mut uses = Uses::default(); |
| 395 | + let mut cases = String::new(); |
| 396 | + for (k, entry) in entries.iter().enumerate() { |
| 397 | + let decl = &self.program.fns[*entry as usize]; |
| 398 | + let n = decl.params.len(); |
| 399 | + if n > REGS { |
| 400 | + return Err(Unsupported( |
| 401 | + "an entry function with many capabilities".into(), |
| 402 | + )); |
| 403 | + } |
| 404 | + uses.fns.insert(*entry); |
| 405 | + let _ = writeln!(cases, " case {k}: {{"); |
| 406 | + for i in 0..n { |
| 407 | + let _ = writeln!( |
| 408 | + cases, |
| 409 | + " tl_value c{i} = tl_root_cap(ctx, {});", |
| 410 | + PROC_OPS.len() |
| 411 | + ); |
| 412 | + } |
| 413 | + let caps: Vec<String> = (0..n).map(|i| format!("c{i}")).collect(); |
| 414 | + let _ = writeln!( |
| 415 | + cases, |
| 416 | + " tl_value r = {}(ctx, {});", |
| 417 | + self.syms[entry], |
| 418 | + register_args(&caps) |
| 419 | + ); |
| 420 | + // A borrowed capability is still the caller's. |
| 421 | + for i in &decl.borrowed { |
| 422 | + let _ = writeln!(cases, " tl_drop(ctx, c{i});"); |
| 423 | + } |
| 424 | + let _ = writeln!(cases, " return r;\n }}"); |
| 425 | + } |
| 426 | + let text = format!( |
| 427 | + r#" |
| 428 | +static int tl_which; |
| 429 | + |
| 430 | +static tl_value tl_entry(tl_ctx *ctx) {{ |
| 431 | + switch (tl_which) {{ |
| 432 | +{cases} default: return TL_UNIT; |
| 433 | + }} |
| 434 | +}} |
| 435 | + |
| 436 | +int main(int argc, char **argv) {{ |
| 437 | + tl_abi_check(TL_ABI_VERSION); |
| 438 | + tl_which = argc > 1 ? atoi(argv[1]) : 0; |
| 439 | + int code = tl_main_program(tl_entry); |
| 440 | + tl_report_leaks(); |
| 441 | + return code; |
| 442 | +}} |
| 443 | + |
| 444 | +"# |
| 445 | + ); |
| 446 | + Ok(Emitted { |
| 447 | + text, |
| 448 | + uses, |
| 449 | + located: false, |
| 450 | + }) |
| 451 | + } |
| 452 | + |
| 453 | + /// The start of a unit whose code `uses` these: the runtime glue, then |
| 454 | + /// the declarations and constants it needs. With `single`, functions |
| 455 | + /// are `static` (one unit holds them all). |
| 456 | + fn header(&self, uses: &Uses, single: bool) -> String { |
| 457 | + let mut uses = uses.clone(); |
| 458 | + for c in &uses.fns.clone() { |
| 459 | + if let Some((_, used)) = self.constants.get(c) { |
| 460 | + uses.add(used); |
| 461 | + } |
| 462 | + } |
| 463 | + let mut out = String::from(PRELUDE); |
| 464 | + let _ = writeln!( |
| 465 | + out, |
| 466 | + "_Static_assert(TL_XARGS == {XARGS}, \"louise and louise_rt.h disagree on TL_XARGS\");\n" |
| 467 | + ); |
| 468 | + let _ = writeln!( |
| 469 | + out, |
| 470 | + "#define TL_FN{}\n", |
| 471 | + if single { " static" } else { "" } |
| 472 | + ); |
| 473 | + for sym in &uses.externs { |
| 474 | + let params: String = (0..self.extern_arity[sym]).map(|_| ", tl_value").collect(); |
| 475 | + let _ = writeln!(out, "tl_value {sym}(tl_ctx *ctx{params});"); |
| 476 | + } |
| 477 | + for thunk in &uses.thunks { |
| 478 | + out.push_str(&self.thunks[thunk]); |
| 479 | + } |
| 480 | + for lit in &uses.lits { |
| 481 | + out.push_str(&self.lits[lit]); |
| 482 | + } |
| 483 | + out.push('\n'); |
| 484 | + for f in uses.fns.iter().filter(|f| !self.constants.contains_key(f)) { |
| 485 | + let _ = writeln!( |
| 486 | + out, |
| 487 | + "TL_FN tl_value {}(tl_ctx *ctx, tl_value a0, tl_value a1, tl_value a2, tl_value a3, tl_value a4, tl_value a5);", |
| 488 | + self.syms[f] |
| 489 | + ); |
| 490 | + } |
| 491 | + for (f, n) in &uses.entries { |
| 492 | + let _ = writeln!( |
| 493 | + out, |
| 494 | + "TL_FN tl_value {}_c{n}(tl_ctx *ctx, tl_value a0, tl_value a1, tl_value a2, tl_value a3, tl_value a4, tl_value a5);", |
| 495 | + self.syms[f] |
| 496 | + ); |
| 497 | + } |
| 498 | + out.push('\n'); |
| 499 | + for c in uses.fns.iter() { |
| 500 | + if let Some((defs, _)) = self.constants.get(c) { |
| 501 | + out.push_str(defs); |
| 502 | + } |
| 503 | + } |
| 504 | + out |
| 505 | + } |
| 506 | + |
| 331 | 507 | /// Where `span` starts, if `#line` directives are wanted. |
| 332 | 508 | fn line_of(&self, span: Span) -> Option<Line> { |
| 333 | 509 | let file = self.sources?.get(span.file); |
| @@ -359,26 +535,28 @@ impl Emitter<'_> { |
| 359 | 535 | if !decl.params.is_empty() { |
| 360 | 536 | return; |
| 361 | 537 | } |
| 538 | + let sym = &self.syms[&id]; |
| 362 | 539 | let mut defs = String::new(); |
| 363 | 540 | let mut entries = Vec::new(); |
| 364 | 541 | let mut e = &decl.body; |
| 365 | 542 | loop { |
| 366 | 543 | match e { |
| 367 | 544 | Expr::Let(v, value, rest, _) => { |
| 368 | | − let name = format!("tl_const{id}_{v}"); |
| 545 | + let name = format!("{sym}_k{v}"); |
| 369 | 546 | match &**value { |
| 370 | 547 | Value::Closure(f, caps) if caps.is_empty() => { |
| 371 | 548 | entries.push(*f); |
| 372 | 549 | let _ = writeln!( |
| 373 | 550 | defs, |
| 374 | | − "static const struct {{ tl_header h; tl_closure_fn code; }} __attribute__((aligned(8))) {name} = {{ {{0, TL_TAG_CLOSURE, 0, 0}}, (tl_closure_fn)f{f}_c0 }};" |
| 551 | + "static const struct {{ tl_header h; tl_closure_fn code; }} __attribute__((aligned(8))) {name} = {{ {{0, TL_TAG_CLOSURE, 0, 0}}, (tl_closure_fn){}_c0 }};", |
| 552 | + self.syms[f] |
| 375 | 553 | ); |
| 376 | 554 | } |
| 377 | 555 | Value::Tuple(args) if !args.is_empty() && args.len() <= 254 => { |
| 378 | 556 | let mut fields = Vec::new(); |
| 379 | 557 | for a in args { |
| 380 | 558 | let Atom::Var(x) = a else { return }; |
| 381 | | − fields.push(format!("(tl_value)&tl_const{id}_{x}")); |
| 559 | + fields.push(format!("(tl_value)&{sym}_k{x}")); |
| 382 | 560 | } |
| 383 | 561 | let _ = writeln!( |
| 384 | 562 | defs, |
| @@ -394,7 +572,7 @@ impl Emitter<'_> { |
| 394 | 572 | Expr::Return(Atom::Var(r)) => { |
| 395 | 573 | let _ = writeln!( |
| 396 | 574 | defs, |
| 397 | | − "/* {} */\n#define tl_const{id} ((tl_value)&tl_const{id}_{r})", |
| 575 | + "/* {} */\n#define {sym}_k ((tl_value)&{sym}_k{r})", |
| 398 | 576 | decl.name |
| 399 | 577 | ); |
| 400 | 578 | break; |
| @@ -403,11 +581,12 @@ impl Emitter<'_> { |
| 403 | 581 | } |
| 404 | 582 | } |
| 405 | 583 | // Only now: a closure's entry is emitted only if it is used. |
| 584 | + let mut uses = Uses::default(); |
| 406 | 585 | for f in entries { |
| 407 | 586 | self.entries.insert((f, 0)); |
| 587 | + uses.entries.insert((f, 0)); |
| 408 | 588 | } |
| 409 | | − self.constants.insert(id); |
| 410 | | − self.constant_defs.push_str(&defs); |
| 589 | + self.constants.insert(id, (defs, uses)); |
| 411 | 590 | } |
| 412 | 591 | |
| 413 | 592 | fn atom(&mut self, a: &Atom) -> Result<String, Unsupported> { |
| @@ -437,35 +616,35 @@ impl Emitter<'_> { |
| 437 | 616 | atoms.iter().map(|a| self.atom(a)).collect() |
| 438 | 617 | } |
| 439 | 618 | |
| 619 | + /// A string literal's static block, named after its contents so the |
| 620 | + /// name doesn't depend on the literals before it. |
| 440 | 621 | fn string_lit(&mut self, s: &str) -> String { |
| 441 | | − let key = format!("s{s}"); |
| 442 | | − if let Some(id) = self.lit_ids.get(&key) { |
| 443 | | − return format!("tl_lit{id}"); |
| 622 | + let mut h = std::collections::hash_map::DefaultHasher::new(); |
| 623 | + std::hash::Hash::hash(s, &mut h); |
| 624 | + let name = format!("tl_lit_s{:016x}", std::hash::Hasher::finish(&h)); |
| 625 | + if !self.lits.contains_key(&name) { |
| 626 | + let def = format!( |
| 627 | + "static struct {{ tl_header h; int64_t len; char bytes[{}]; }} __attribute__((aligned(8))) {name} = {{ {{0, TL_TAG_STRING, 0, 0}}, {}, \"{}\" }};\n", |
| 628 | + s.len() + 1, |
| 629 | + s.len(), |
| 630 | + c_escape(s) |
| 631 | + ); |
| 632 | + self.lits.insert(name.clone(), def); |
| 444 | 633 | } |
| 445 | | − let id = self.lit_ids.len(); |
| 446 | | − self.lit_ids.insert(key, id); |
| 447 | | − let _ = writeln!( |
| 448 | | − self.lits, |
| 449 | | − "static struct {{ tl_header h; int64_t len; char bytes[{}]; }} __attribute__((aligned(8))) tl_lit{id} = {{ {{0, TL_TAG_STRING, 0, 0}}, {}, \"{}\" }};", |
| 450 | | − s.len() + 1, |
| 451 | | − s.len(), |
| 452 | | − c_escape(s) |
| 453 | | − ); |
| 454 | | − format!("tl_lit{id}") |
| 634 | + self.uses.lits.insert(name.clone()); |
| 635 | + name |
| 455 | 636 | } |
| 456 | 637 | |
| 457 | 638 | fn float_lit(&mut self, x: f64) -> String { |
| 458 | | − let key = format!("f{}", x.to_bits()); |
| 459 | | − if let Some(id) = self.lit_ids.get(&key) { |
| 460 | | − return format!("tl_lit{id}"); |
| 639 | + let name = format!("tl_lit_f{:016x}", x.to_bits()); |
| 640 | + if !self.lits.contains_key(&name) { |
| 641 | + let def = format!( |
| 642 | + "static struct {{ tl_header h; double x; }} __attribute__((aligned(8))) {name} = {{ {{0, TL_TAG_FLOAT, 0, 0}}, {x:e} }};\n" |
| 643 | + ); |
| 644 | + self.lits.insert(name.clone(), def); |
| 461 | 645 | } |
| 462 | | − let id = self.lit_ids.len(); |
| 463 | | − self.lit_ids.insert(key, id); |
| 464 | | − let _ = writeln!( |
| 465 | | − self.lits, |
| 466 | | − "static struct {{ tl_header h; double x; }} __attribute__((aligned(8))) tl_lit{id} = {{ {{0, TL_TAG_FLOAT, 0, 0}}, {x:e} }};" |
| 467 | | − ); |
| 468 | | − format!("tl_lit{id}") |
| 646 | + self.uses.lits.insert(name.clone()); |
| 647 | + name |
| 469 | 648 | } |
| 470 | 649 | |
| 471 | 650 | /// Code calling a closure value `f` (consumed) with `args`. |
| @@ -528,12 +707,14 @@ impl Emitter<'_> { |
| 528 | 707 | let _ = writeln!(out, "{ind} goto entry;\n{ind}}}"); |
| 529 | 708 | return Ok(None); |
| 530 | 709 | } |
| 531 | | − Value::CallFn(g, args) if !self.constants.contains(g) => { |
| 710 | + Value::CallFn(g, args) if !self.constants.contains_key(g) => { |
| 532 | 711 | let slots = self.atoms(args)?; |
| 533 | 712 | store_xargs(&slots, &ind, out); |
| 713 | + self.uses.fns.insert(*g); |
| 534 | 714 | let _ = writeln!( |
| 535 | 715 | out, |
| 536 | | − "{ind}TL_MUSTTAIL return f{g}(ctx, {});", |
| 716 | + "{ind}TL_MUSTTAIL return {}(ctx, {});", |
| 717 | + self.syms[g], |
| 537 | 718 | register_args(&slots) |
| 538 | 719 | ); |
| 539 | 720 | return Ok(None); |
| @@ -734,7 +915,9 @@ impl Emitter<'_> { |
| 734 | 915 | /// Whether computing `value` may start or continue unwinding. |
| 735 | 916 | fn may_unwind(&self, value: &Value) -> bool { |
| 736 | 917 | match value { |
| 737 | | − Value::CallFn(g, _) => !self.constants.contains(g) && !self.never_unwinds.contains(g), |
| 918 | + Value::CallFn(g, _) => { |
| 919 | + !self.constants.contains_key(g) && !self.never_unwinds.contains(g) |
| 920 | + } |
| 738 | 921 | value => crate::unwind::may_unwind_itself(self.program, value), |
| 739 | 922 | } |
| 740 | 923 | } |
| @@ -753,13 +936,20 @@ impl Emitter<'_> { |
| 753 | 936 | let a = self.atom(a)?; |
| 754 | 937 | let _ = writeln!(out, "{ind}v{v} = {a};"); |
| 755 | 938 | } |
| 756 | | − Value::CallFn(g, _) if self.constants.contains(g) => { |
| 757 | | − let _ = writeln!(out, "{ind}v{v} = tl_const{g};"); |
| 939 | + Value::CallFn(g, _) if self.constants.contains_key(g) => { |
| 940 | + self.uses.fns.insert(*g); |
| 941 | + let _ = writeln!(out, "{ind}v{v} = {}_k;", self.syms[g]); |
| 758 | 942 | } |
| 759 | 943 | Value::CallFn(g, args) => { |
| 760 | 944 | let slots = self.atoms(args)?; |
| 761 | 945 | store_xargs(&slots, ind, out); |
| 762 | | − let _ = writeln!(out, "{ind}v{v} = f{g}(ctx, {});", register_args(&slots)); |
| 946 | + self.uses.fns.insert(*g); |
| 947 | + let _ = writeln!( |
| 948 | + out, |
| 949 | + "{ind}v{v} = {}(ctx, {});", |
| 950 | + self.syms[g], |
| 951 | + register_args(&slots) |
| 952 | + ); |
| 763 | 953 | } |
| 764 | 954 | Value::Call(c, args) => { |
| 765 | 955 | let c = self.atom(c)?; |
| @@ -771,7 +961,7 @@ impl Emitter<'_> { |
| 771 | 961 | // `louise_rt.h` declares the runtime's externs; a binding's |
| 772 | 962 | // are declared here. |
| 773 | 963 | if runtime_extern(sym).is_none() { |
| 774 | | − match self.externs.get(sym) { |
| 964 | + match self.extern_arity.get(sym) { |
| 775 | 965 | Some(n) if *n != args.len() => { |
| 776 | 966 | return Err(Unsupported(format!( |
| 777 | 967 | "calling extern `{sym}` with {} and {n} arguments", |
| @@ -779,25 +969,27 @@ impl Emitter<'_> { |
| 779 | 969 | ))); |
| 780 | 970 | } |
| 781 | 971 | _ => { |
| 782 | | − self.externs.insert(sym.clone(), args.len()); |
| 972 | + self.extern_arity.insert(sym.clone(), args.len()); |
| 783 | 973 | } |
| 784 | 974 | } |
| 975 | + self.uses.externs.insert(sym.clone()); |
| 785 | 976 | } |
| 786 | 977 | let args = self.atoms(args)?; |
| 787 | 978 | if self.program.blocking.contains(sym) { |
| 788 | 979 | // Run it on the blocking pool (ADR 0005). |
| 789 | 980 | let thunk = format!("tl_blocking_{sym}"); |
| 790 | | − if !self.thunks.contains(&format!(" {thunk}(")) { |
| 981 | + if !self.thunks.contains_key(&thunk) { |
| 791 | 982 | let call: Vec<String> = |
| 792 | 983 | (0..args.len()).map(|i| format!("a[{i}]")).collect(); |
| 793 | 984 | let mut all = vec!["ctx".to_owned()]; |
| 794 | 985 | all.extend(call); |
| 795 | | − let _ = writeln!( |
| 796 | | − self.thunks, |
| 797 | | − "static tl_value {thunk}(tl_ctx *ctx, const tl_value *a) {{ (void)a; return {sym}({}); }}", |
| 986 | + let def = format!( |
| 987 | + "static tl_value {thunk}(tl_ctx *ctx, const tl_value *a) {{ (void)a; return {sym}({}); }}\n", |
| 798 | 988 | all.join(", ") |
| 799 | 989 | ); |
| 990 | + self.thunks.insert(thunk.clone(), def); |
| 800 | 991 | } |
| 992 | + self.uses.thunks.insert(thunk.clone()); |
| 801 | 993 | let list = if args.is_empty() { |
| 802 | 994 | "TL_UNIT".to_owned() |
| 803 | 995 | } else { |
| @@ -862,9 +1054,11 @@ impl Emitter<'_> { |
| 862 | 1054 | )); |
| 863 | 1055 | } |
| 864 | 1056 | self.entries.insert((*fid, caps.len())); |
| 1057 | + self.uses.entries.insert((*fid, caps.len())); |
| 865 | 1058 | let _ = writeln!( |
| 866 | 1059 | out, |
| 867 | | − "{ind}v{v} = tl_closure_alloc(ctx, (tl_closure_fn)f{fid}_c{}, {});", |
| 1060 | + "{ind}v{v} = tl_closure_alloc(ctx, (tl_closure_fn){}_c{}, {});", |
| 1061 | + self.syms[fid], |
| 868 | 1062 | caps.len(), |
| 869 | 1063 | caps.len() |
| 870 | 1064 | ); |
| @@ -929,7 +1123,8 @@ impl Emitter<'_> { |
| 929 | 1123 | let total = self.program.fns[f as usize].params.len(); |
| 930 | 1124 | let _ = writeln!( |
| 931 | 1125 | out, |
| 932 | | − "TL_FN tl_value f{f}_c{n}(tl_ctx *ctx, tl_value a0, tl_value a1, tl_value a2, tl_value a3, tl_value a4, tl_value a5) {{" |
| 1126 | + "TL_FN tl_value {}_c{n}(tl_ctx *ctx, tl_value a0, tl_value a1, tl_value a2, tl_value a3, tl_value a4, tl_value a5) {{", |
| 1127 | + self.syms[&f] |
| 933 | 1128 | ); |
| 934 | 1129 | // Incoming slots: the closure, then the call's arguments. |
| 935 | 1130 | let incoming = 1 + total.saturating_sub(n); |
| @@ -958,7 +1153,8 @@ impl Emitter<'_> { |
| 958 | 1153 | store_xargs(&outgoing, " ", out); |
| 959 | 1154 | let _ = writeln!( |
| 960 | 1155 | out, |
| 961 | | − " TL_MUSTTAIL return f{f}(ctx, {});\n}}\n", |
| 1156 | + " TL_MUSTTAIL return {}(ctx, {});\n}}\n", |
| 1157 | + self.syms[&f], |
| 962 | 1158 | register_args(&outgoing) |
| 963 | 1159 | ); |
| 964 | 1160 | } |