| @@ -67,6 +67,7 @@ pub(crate) fn emit( |
| 67 | 67 | sources, |
| 68 | 68 | syms: symbols(program, reachable), |
| 69 | 69 | lits: BTreeMap::new(), |
| 70 | + lit_order: Vec::new(), |
| 70 | 71 | entries: BTreeSet::new(), |
| 71 | 72 | extern_arity: BTreeMap::new(), |
| 72 | 73 | thunks: BTreeMap::new(), |
| @@ -83,6 +84,8 @@ pub(crate) fn emit( |
| 83 | 84 | worker: None, |
| 84 | 85 | functions: BTreeMap::new(), |
| 85 | 86 | uses: Uses::default(), |
| 87 | + hoist_statics: std::env::var_os("LOUISE_NO_STATIC_CTORS").is_none(), |
| 88 | + static_atoms: HashMap::new(), |
| 86 | 89 | labels: 0, |
| 87 | 90 | line: None, |
| 88 | 91 | written: None, |
| @@ -271,6 +274,12 @@ fn take(held: &mut Vec<VarId>, v: VarId) { |
| 271 | 274 | } |
| 272 | 275 | } |
| 273 | 276 | |
| 277 | +/// `tl_int(n)` as a C constant expression, for a static block's |
| 278 | +/// initializer (`tl_int` itself is a function). |
| 279 | +fn const_int(n: i64) -> String { |
| 280 | + format!("((tl_value)(((uint64_t)INT64_C({n}) << 1) | 1))") |
| 281 | +} |
| 282 | + |
| 274 | 283 | /// Unwinding out of this frame: the C statements that drop what it holds |
| 275 | 284 | /// (`held`) and return `ret`, a value of the function's return type |
| 276 | 285 | /// (`TL_UNIT`, a dummy struct for a CPR worker, `0.0`/`0` for a float/int |
| @@ -329,6 +338,10 @@ struct Emitter<'p> { |
| 329 | 338 | syms: HashMap<FnId, String>, |
| 330 | 339 | /// Static literal blocks, by name. |
| 331 | 340 | lits: BTreeMap<String, String>, |
| 341 | + /// The literals in the order they were interned: a constant |
| 342 | + /// constructor tree's block initialises with the addresses of its |
| 343 | + /// fields' blocks, so a definition may only follow what it refers to. |
| 344 | + lit_order: Vec<String>, |
| 332 | 345 | /// Closure entries needed: (function, number of captures). |
| 333 | 346 | entries: BTreeSet<(FnId, usize)>, |
| 334 | 347 | /// Foreign symbols seen, with their arity. |
| @@ -350,6 +363,14 @@ struct Emitter<'p> { |
| 350 | 363 | uses: Uses, |
| 351 | 364 | /// The function being emitted. |
| 352 | 365 | current: FnId, |
| 366 | + /// Emit constant constructor trees as static, immortal blocks (like |
| 367 | + /// string literals); `LOUISE_NO_STATIC_CTORS` rebuilds them at run |
| 368 | + /// time, as before. |
| 369 | + hoist_statics: bool, |
| 370 | + /// The function being emitted's variables bound to a constant value: |
| 371 | + /// the content key and the C constant expression of the static they |
| 372 | + /// refer to (see [`Emitter::static_construct`]). |
| 373 | + static_atoms: HashMap<VarId, (String, String)>, |
| 353 | 374 | /// Proven integer ranges (ADR 0046, piece 3; `crate::ranges`). |
| 354 | 375 | ranges: crate::ranges::Ranges, |
| 355 | 376 | /// The unboxed worker plans (ADR 0045; `crate::unbox`), and, while a |
| @@ -751,6 +772,7 @@ impl Emitter<'_> { |
| 751 | 772 | self.current = id; |
| 752 | 773 | self.raw = raw; |
| 753 | 774 | self.worker = Some(kind); |
| 775 | + self.static_atoms.clear(); |
| 754 | 776 | let _ = writeln!(out, "{} {{", self.worker_sig(id)); |
| 755 | 777 | let params_set: BTreeSet<VarId> = decl.params.iter().copied().collect(); |
| 756 | 778 | for (i, p) in decl.params.iter().enumerate() { |
| @@ -817,6 +839,7 @@ impl Emitter<'_> { |
| 817 | 839 | self.cmp_defer = cmp_defer; |
| 818 | 840 | let mut out = String::new(); |
| 819 | 841 | self.uses = Uses::default(); |
| 842 | + self.static_atoms.clear(); |
| 820 | 843 | self.labels = 0; |
| 821 | 844 | self.current = id; |
| 822 | 845 | let _ = writeln!(out, "/* {} */", decl.name); |
| @@ -1011,8 +1034,10 @@ int main(int argc, char **argv) {{ |
| 1011 | 1034 | for thunk in &uses.thunks { |
| 1012 | 1035 | out.push_str(&self.thunks[thunk]); |
| 1013 | 1036 | } |
| 1014 | | − for lit in &uses.lits { |
| 1015 | | − out.push_str(&self.lits[lit]); |
| 1037 | + for lit in &self.lit_order { |
| 1038 | + if uses.lits.contains(lit) { |
| 1039 | + out.push_str(&self.lits[lit]); |
| 1040 | + } |
| 1016 | 1041 | } |
| 1017 | 1042 | out.push('\n'); |
| 1018 | 1043 | for f in uses.fns.iter().filter(|f| !self.constants.contains_key(f)) { |
| @@ -1183,7 +1208,7 @@ int main(int argc, char **argv) {{ |
| 1183 | 1208 | s.len(), |
| 1184 | 1209 | c_escape(s) |
| 1185 | 1210 | ); |
| 1186 | | − self.lits.insert(name.clone(), def); |
| 1211 | + self.intern_lit(name.clone(), def); |
| 1187 | 1212 | } |
| 1188 | 1213 | self.uses.lits.insert(name.clone()); |
| 1189 | 1214 | name |
| @@ -1195,12 +1220,109 @@ int main(int argc, char **argv) {{ |
| 1195 | 1220 | let def = format!( |
| 1196 | 1221 | "static struct {{ tl_header h; double x; }} __attribute__((aligned(8))) {name} = {{ {{0, TL_TAG_FLOAT, 0, 0}}, {x:e} }};\n" |
| 1197 | 1222 | ); |
| 1198 | | − self.lits.insert(name.clone(), def); |
| 1223 | + self.intern_lit(name.clone(), def); |
| 1199 | 1224 | } |
| 1200 | 1225 | self.uses.lits.insert(name.clone()); |
| 1201 | 1226 | name |
| 1202 | 1227 | } |
| 1203 | 1228 | |
| 1229 | + /// Record a static literal block's definition, in interning order |
| 1230 | + /// (a constant constructor tree's block refers to its fields' blocks, |
| 1231 | + /// which were interned before it: [`Emitter::lit_order`]). |
| 1232 | + fn intern_lit(&mut self, name: String, def: String) { |
| 1233 | + self.lit_order.push(name.clone()); |
| 1234 | + self.lits.insert(name, def); |
| 1235 | + } |
| 1236 | + |
| 1237 | + /// The content key and C constant expression of `a` as the field of a |
| 1238 | + /// static block, if it is a constant: a literal (strings and floats |
| 1239 | + /// are static blocks of their own), unit, or a variable this function |
| 1240 | + /// already bound to one. |
| 1241 | + fn static_field(&mut self, a: &Atom) -> Option<(String, String)> { |
| 1242 | + match a { |
| 1243 | + Atom::Unit => Some(("u".to_owned(), "TL_UNIT".to_owned())), |
| 1244 | + Atom::Lit(Lit::Int(n)) if SMALL_INT.contains(n) => { |
| 1245 | + Some((format!("i{n}"), const_int(*n))) |
| 1246 | + } |
| 1247 | + Atom::Lit(Lit::String(s)) => { |
| 1248 | + let name = self.string_lit(s); |
| 1249 | + Some((format!("s{name}"), format!("(tl_value)&{name}"))) |
| 1250 | + } |
| 1251 | + Atom::Lit(Lit::Float(x)) => { |
| 1252 | + let name = self.float_lit(*x); |
| 1253 | + Some((format!("f{name}"), format!("(tl_value)&{name}"))) |
| 1254 | + } |
| 1255 | + Atom::Var(u) => self.static_atoms.get(u).cloned(), |
| 1256 | + _ => None, |
| 1257 | + } |
| 1258 | + } |
| 1259 | + |
| 1260 | + /// A construction of constants — an HTML literal's static subtree, a |
| 1261 | + /// template's `parts` list, a tuple of literals — is immutable, so one |
| 1262 | + /// static, immortal block (rc 0, like a string literal's: never |
| 1263 | + /// counted, never freed, never unique, so Perceus' reuse never writes |
| 1264 | + /// it) serves every evaluation. Emits (or reuses) the block and |
| 1265 | + /// returns its name; `None` — build at run time as usual — when |
| 1266 | + /// `LOUISE_NO_STATIC_CTORS` is set, a field is not constant, or the |
| 1267 | + /// block would not be well formed (the checks of |
| 1268 | + /// [`Emitter::check_block`]). |
| 1269 | + /// |
| 1270 | + /// Blocks are content-named, so equal trees share one block, in and |
| 1271 | + /// across functions. Sharing is unobservable: values are immutable |
| 1272 | + /// and every equality in the language is structural (there is no |
| 1273 | + /// pointer-identity primitive). The interpreter is unchanged: it |
| 1274 | + /// keeps building the tree per call, which the same argument covers. |
| 1275 | + fn static_construct(&mut self, v: VarId, tag: u32, args: &[Atom]) -> Option<String> { |
| 1276 | + if !self.hoist_statics { |
| 1277 | + return None; |
| 1278 | + } |
| 1279 | + if args.is_empty() { |
| 1280 | + // A nullary constructor is an immediate (`tl_int(tag)`), |
| 1281 | + // free already; record it so a constant tree holding it |
| 1282 | + // (a list's `Nil` end, a `True`) still hoists. |
| 1283 | + self.static_atoms |
| 1284 | + .insert(v, (format!("n{tag}"), const_int(tag.into()))); |
| 1285 | + return None; |
| 1286 | + } |
| 1287 | + if args.len() > 254 || tag >= 0xFF00 { |
| 1288 | + return None; |
| 1289 | + } |
| 1290 | + // Every field must be constant before any literal is interned |
| 1291 | + // (interning marks the block used, and an unused static is dead |
| 1292 | + // weight in the unit). |
| 1293 | + for a in args { |
| 1294 | + match a { |
| 1295 | + Atom::Unit | Atom::Lit(_) => {} |
| 1296 | + Atom::Var(u) if self.static_atoms.contains_key(u) => {} |
| 1297 | + _ => return None, |
| 1298 | + } |
| 1299 | + } |
| 1300 | + let mut key = format!("c{tag}"); |
| 1301 | + let mut fields = Vec::with_capacity(args.len()); |
| 1302 | + for a in args { |
| 1303 | + let (k, c) = self.static_field(a)?; |
| 1304 | + key.push(','); |
| 1305 | + key.push_str(&k); |
| 1306 | + fields.push(c); |
| 1307 | + } |
| 1308 | + let mut h = std::collections::hash_map::DefaultHasher::new(); |
| 1309 | + std::hash::Hash::hash(&key, &mut h); |
| 1310 | + let name = format!("tl_lit_c{:016x}", std::hash::Hasher::finish(&h)); |
| 1311 | + if !self.lits.contains_key(&name) { |
| 1312 | + let def = format!( |
| 1313 | + "static const struct {{ tl_header h; tl_value fields[{}]; }} __attribute__((aligned(8))) {name} = {{ {{0, {tag}, {}, 0}}, {{ {} }} }};\n", |
| 1314 | + args.len(), |
| 1315 | + args.len(), |
| 1316 | + fields.join(", ") |
| 1317 | + ); |
| 1318 | + self.intern_lit(name.clone(), def); |
| 1319 | + } |
| 1320 | + self.uses.lits.insert(name.clone()); |
| 1321 | + self.static_atoms |
| 1322 | + .insert(v, (name.clone(), format!("(tl_value)&{name}"))); |
| 1323 | + Some(name) |
| 1324 | + } |
| 1325 | + |
| 1204 | 1326 | /// Code calling a closure value `f` (consumed) with `args`. |
| 1205 | 1327 | fn closure_call(f: &str, args: &[String], indent: &str, out: &mut String) -> String { |
| 1206 | 1328 | let mut slots = vec![f.to_owned()]; |
| @@ -2287,13 +2409,20 @@ int main(int argc, char **argv) {{ |
| 2287 | 2409 | ) -> Result<(), Unsupported> { |
| 2288 | 2410 | match value { |
| 2289 | 2411 | Value::Atom(a) => { |
| 2290 | | − let s = if self.worker.is_some() && self.raw.contains(&v) { |
| 2412 | + let raw_target = self.worker.is_some() && self.raw.contains(&v); |
| 2413 | + let s = if raw_target { |
| 2291 | 2414 | // The target is raw: the literal or the unboxed local. |
| 2292 | 2415 | self.raw_atom(a)? |
| 2293 | 2416 | } else { |
| 2294 | 2417 | self.atom(a)? |
| 2295 | 2418 | }; |
| 2296 | 2419 | let _ = writeln!(out, "{ind}v{v} = {s};"); |
| 2420 | + if self.hoist_statics |
| 2421 | + && !raw_target |
| 2422 | + && let Some(f) = self.static_field(a) |
| 2423 | + { |
| 2424 | + self.static_atoms.insert(v, f); |
| 2425 | + } |
| 2297 | 2426 | } |
| 2298 | 2427 | Value::CallFn(g, _) if self.constants.contains_key(g) => { |
| 2299 | 2428 | self.uses.fns.insert(*g); |
| @@ -2435,12 +2564,20 @@ int main(int argc, char **argv) {{ |
| 2435 | 2564 | let _ = writeln!(out, "{ind}v{v} = {text};"); |
| 2436 | 2565 | } |
| 2437 | 2566 | Value::Construct { tag, args, .. } => { |
| 2438 | | − let args = self.atoms(args)?; |
| 2439 | | − self.block(out, v, *tag, &args, ind)?; |
| 2567 | + if let Some(name) = self.static_construct(v, *tag, args) { |
| 2568 | + let _ = writeln!(out, "{ind}v{v} = (tl_value)&{name};"); |
| 2569 | + } else { |
| 2570 | + let args = self.atoms(args)?; |
| 2571 | + self.block(out, v, *tag, &args, ind)?; |
| 2572 | + } |
| 2440 | 2573 | } |
| 2441 | 2574 | Value::Tuple(args) => { |
| 2442 | | − let args = self.atoms(args)?; |
| 2443 | | − self.block(out, v, 0, &args, ind)?; |
| 2575 | + if let Some(name) = self.static_construct(v, 0, args) { |
| 2576 | + let _ = writeln!(out, "{ind}v{v} = (tl_value)&{name};"); |
| 2577 | + } else { |
| 2578 | + let args = self.atoms(args)?; |
| 2579 | + self.block(out, v, 0, &args, ind)?; |
| 2580 | + } |
| 2444 | 2581 | } |
| 2445 | 2582 | Value::Field(base, i) => { |
| 2446 | 2583 | let b = self.atom(base)?; |