| @@ -0,0 +1,503 @@ |
| 1 | +//! Specialisation of known trait evidence (issue #61, ADR 0013). |
| 2 | +//! |
| 3 | +//! Lowering passes trait dictionaries as values: `x + 1` on `Int` builds |
| 4 | +//! (or, natively, reads) the `Num<Int>` dictionary, projects its `add` |
| 5 | +//! closure and calls it. When the dictionary is a *constant* one (an impl |
| 6 | +//! without constraints, such as `Num<Int>`), everything is known at |
| 7 | +//! compile time. This pass, run on Core before Perceus by the C backend: |
| 8 | +//! |
| 9 | +//! 1. **Devirtualises:** a call of a closure projected from a known |
| 10 | +//! dictionary becomes a direct call of the method (`CallFn`). |
| 11 | +//! 2. **Inlines trivial methods:** a direct call of a function whose body |
| 12 | +//! is one extern call or primitive on its parameters (`impl |
| 13 | +//! Num<Int>.add` is `extern tl_int_add(a, b)`) becomes that call. |
| 14 | +//! 3. **Specialises functions on constant dictionary arguments:** a call |
| 15 | +//! `f(Num<Int>, ...)` of a constrained function calls a copy of `f` |
| 16 | +//! made for that dictionary, in which the dictionary is known, so 1 |
| 17 | +//! and 2 apply inside it (and to its own calls, recursively). Values |
| 18 | +//! keep their uniform representation: this specialises dictionary |
| 19 | +//! passing, not data layout. |
| 20 | +//! 4. **Removes** the `let`s left unused (projections, dictionary reads). |
| 21 | +//! |
| 22 | +//! The interpreter runs Core as lowered, so the differential tests check |
| 23 | +//! this pass against the unspecialised program. |
| 24 | +//! |
| 25 | +//! Variables are unique within a function (Core is in A-normal form with |
| 26 | +//! fresh names), so what is known about a variable holds wherever it is |
| 27 | +//! in scope. |
| 28 | + |
| 29 | +use std::collections::{BTreeSet, HashMap}; |
| 30 | + |
| 31 | +use crate::ir::{Atom, Expr, FnDecl, FnId, Program, Value, VarId}; |
| 32 | + |
| 33 | +/// The pass makes at most this many specialised copies per function of |
| 34 | +/// the program (in total, not each), to bound code growth (each copy is keyed by the function and the constant |
| 35 | +/// dictionaries it receives, so recursion reuses its copy). |
| 36 | +const COPIES_PER_FUNCTION: usize = 1; |
| 37 | + |
| 38 | +/// Disables the pass (to compare, or to bisect a miscompilation). |
| 39 | +const DISABLE_VAR: &str = "TILC_NO_SPECIALISE"; |
| 40 | + |
| 41 | +/// What is known at compile time about a variable's value. |
| 42 | +#[derive(Clone, Debug, PartialEq)] |
| 43 | +enum Known { |
| 44 | + /// The dictionary a constant dictionary function returns. |
| 45 | + Dict(FnId), |
| 46 | + /// A tuple of known values (a dictionary, or part of one). |
| 47 | + Tuple(Vec<Known>), |
| 48 | + /// A closure without captures of this function. |
| 49 | + Closure(FnId), |
| 50 | +} |
| 51 | + |
| 52 | +/// Specialise `program`'s known evidence (see the module documentation). |
| 53 | +pub fn run(program: &mut Program) { |
| 54 | + if std::env::var_os(DISABLE_VAR).is_some() { |
| 55 | + return; |
| 56 | + } |
| 57 | + let dicts = constant_dicts(program); |
| 58 | + let trivial = trivial_bodies(program); |
| 59 | + let mut pass = Pass { |
| 60 | + dicts, |
| 61 | + trivial, |
| 62 | + copies: HashMap::new(), |
| 63 | + origin: HashMap::new(), |
| 64 | + budget: program.fns.len() * COPIES_PER_FUNCTION, |
| 65 | + queue: Vec::new(), |
| 66 | + }; |
| 67 | + for id in 0..program.fns.len() { |
| 68 | + pass.function(program, id as FnId, HashMap::new()); |
| 69 | + } |
| 70 | + // Every original function is done: a copy starts from its original's |
| 71 | + // final body (an original may still be in progress when a copy of it |
| 72 | + // is made, during polymorphic recursion). |
| 73 | + while let Some((id, original, known)) = pass.queue.pop() { |
| 74 | + program.fns[id as usize].body = program.fns[original as usize].body.clone(); |
| 75 | + pass.function(program, id, known); |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +/// The constant dictionary functions: no parameters, a body of closures |
| 80 | +/// without captures and tuples of them, returning one (as the C backend |
| 81 | +/// emits as static data). |
| 82 | +fn constant_dicts(program: &Program) -> HashMap<FnId, Known> { |
| 83 | + let mut dicts = HashMap::new(); |
| 84 | + 'fns: for (id, f) in program.fns.iter().enumerate() { |
| 85 | + if !f.params.is_empty() { |
| 86 | + continue; |
| 87 | + } |
| 88 | + let mut vars: HashMap<VarId, Known> = HashMap::new(); |
| 89 | + let mut e = &f.body; |
| 90 | + loop { |
| 91 | + match e { |
| 92 | + Expr::Let(v, value, rest, _) => { |
| 93 | + let known = match &**value { |
| 94 | + Value::Closure(g, caps) if caps.is_empty() => Known::Closure(*g), |
| 95 | + Value::Tuple(args) if !args.is_empty() => { |
| 96 | + let mut parts = Vec::new(); |
| 97 | + for a in args { |
| 98 | + match a { |
| 99 | + Atom::Var(x) if vars.contains_key(x) => { |
| 100 | + parts.push(vars[x].clone()); |
| 101 | + } |
| 102 | + _ => continue 'fns, |
| 103 | + } |
| 104 | + } |
| 105 | + Known::Tuple(parts) |
| 106 | + } |
| 107 | + _ => continue 'fns, |
| 108 | + }; |
| 109 | + vars.insert(*v, known); |
| 110 | + e = rest; |
| 111 | + } |
| 112 | + Expr::Return(Atom::Var(r)) if matches!(vars.get(r), Some(Known::Tuple(_))) => { |
| 113 | + dicts.insert(id as FnId, vars[r].clone()); |
| 114 | + break; |
| 115 | + } |
| 116 | + _ => continue 'fns, |
| 117 | + } |
| 118 | + } |
| 119 | + } |
| 120 | + dicts |
| 121 | +} |
| 122 | + |
| 123 | +/// Functions whose body is a single extern call or primitive on their |
| 124 | +/// parameters and literals, returned: the value, to inline with the |
| 125 | +/// parameters replaced by the arguments. |
| 126 | +fn trivial_bodies(program: &Program) -> HashMap<FnId, Value> { |
| 127 | + let mut out = HashMap::new(); |
| 128 | + for (id, f) in program.fns.iter().enumerate() { |
| 129 | + let Expr::Let(v, value, rest, _) = &f.body else { |
| 130 | + continue; |
| 131 | + }; |
| 132 | + if **rest != Expr::Return(Atom::Var(*v)) { |
| 133 | + continue; |
| 134 | + } |
| 135 | + let args = match &**value { |
| 136 | + Value::CallExtern(_, args) | Value::Prim(_, args) => args, |
| 137 | + _ => continue, |
| 138 | + }; |
| 139 | + let on_params = args.iter().all(|a| match a { |
| 140 | + Atom::Var(x) => f.params.contains(x), |
| 141 | + Atom::Lit(_) | Atom::Unit => true, |
| 142 | + }); |
| 143 | + if on_params { |
| 144 | + out.insert(id as FnId, (**value).clone()); |
| 145 | + } |
| 146 | + } |
| 147 | + out |
| 148 | +} |
| 149 | + |
| 150 | +struct Pass { |
| 151 | + dicts: HashMap<FnId, Known>, |
| 152 | + trivial: HashMap<FnId, Value>, |
| 153 | + /// Specialised copies: (function, the constant dictionary each |
| 154 | + /// parameter receives, if any) to the copy. |
| 155 | + copies: HashMap<(FnId, Vec<Option<FnId>>), FnId>, |
| 156 | + /// Each copy's key in `copies`. |
| 157 | + origin: HashMap<FnId, (FnId, Vec<Option<FnId>>)>, |
| 158 | + /// Copies that may still be made. |
| 159 | + budget: usize, |
| 160 | + /// Copies whose bodies are still to be made and specialised: the copy, |
| 161 | + /// its original, and what the copy's parameters are known to be. |
| 162 | + queue: Vec<(FnId, FnId, HashMap<VarId, Known>)>, |
| 163 | +} |
| 164 | + |
| 165 | +impl Pass { |
| 166 | + /// Specialise the body of `id`, whose variables `known` are known. |
| 167 | + fn function(&mut self, program: &mut Program, id: FnId, mut known: HashMap<VarId, Known>) { |
| 168 | + if self.dicts.contains_key(&id) { |
| 169 | + return; |
| 170 | + } |
| 171 | + let body = std::mem::replace(&mut program.fns[id as usize].body, Expr::Return(Atom::Unit)); |
| 172 | + let body = self.expr(program, body, &mut known); |
| 173 | + program.fns[id as usize].body = remove_unused(body, &self.dicts); |
| 174 | + } |
| 175 | + |
| 176 | + fn expr(&mut self, program: &mut Program, e: Expr, known: &mut HashMap<VarId, Known>) -> Expr { |
| 177 | + // A chain of `let`s is rewritten in a loop (it can be long), then |
| 178 | + // rebuilt from the end. |
| 179 | + let mut lets = Vec::new(); |
| 180 | + let mut end = e; |
| 181 | + while let Expr::Let(v, value, rest, span) = end { |
| 182 | + let value = self.value(program, v, *value, known); |
| 183 | + lets.push((v, value, span)); |
| 184 | + end = *rest; |
| 185 | + } |
| 186 | + let mut out = match end { |
| 187 | + Expr::Switch { on, cases, default } => Expr::Switch { |
| 188 | + on, |
| 189 | + cases: cases |
| 190 | + .into_iter() |
| 191 | + .map(|(t, b)| (t, self.expr(program, b, known))) |
| 192 | + .collect(), |
| 193 | + default: default.map(|d| Box::new(self.expr(program, *d, known))), |
| 194 | + }, |
| 195 | + Expr::SwitchLit { on, cases, default } => Expr::SwitchLit { |
| 196 | + on, |
| 197 | + cases: cases |
| 198 | + .into_iter() |
| 199 | + .map(|(l, b)| (l, self.expr(program, b, known))) |
| 200 | + .collect(), |
| 201 | + default: Box::new(self.expr(program, *default, known)), |
| 202 | + }, |
| 203 | + end => end, |
| 204 | + }; |
| 205 | + for (v, value, span) in lets.into_iter().rev() { |
| 206 | + out = Expr::Let(v, Box::new(value), Box::new(out), span); |
| 207 | + } |
| 208 | + out |
| 209 | + } |
| 210 | + |
| 211 | + /// Rewrite the value bound to `v`, recording what is known about `v`. |
| 212 | + fn value( |
| 213 | + &mut self, |
| 214 | + program: &mut Program, |
| 215 | + v: VarId, |
| 216 | + value: Value, |
| 217 | + known: &mut HashMap<VarId, Known>, |
| 218 | + ) -> Value { |
| 219 | + // Forget an earlier binding of the same variable, should lowering |
| 220 | + // ever reuse one in another branch. |
| 221 | + known.remove(&v); |
| 222 | + let var = |a: &Atom| match a { |
| 223 | + Atom::Var(x) => known.get(x).cloned(), |
| 224 | + _ => None, |
| 225 | + }; |
| 226 | + match value { |
| 227 | + Value::Block(inner) => Value::Block(Box::new(self.expr(program, *inner, known))), |
| 228 | + Value::Atom(a) => { |
| 229 | + if let Some(k) = var(&a) { |
| 230 | + known.insert(v, k); |
| 231 | + } |
| 232 | + Value::Atom(a) |
| 233 | + } |
| 234 | + Value::CallFn(g, args) if args.is_empty() && self.dicts.contains_key(&g) => { |
| 235 | + known.insert(v, Known::Dict(g)); |
| 236 | + Value::CallFn(g, args) |
| 237 | + } |
| 238 | + Value::Field(base, i) => { |
| 239 | + if let Some(k) = var(&base).and_then(|k| self.field(&k, i as usize)) { |
| 240 | + known.insert(v, k); |
| 241 | + } |
| 242 | + Value::Field(base, i) |
| 243 | + } |
| 244 | + Value::Call(f, args) => match var(&f) { |
| 245 | + Some(Known::Closure(g)) => self.call(program, g, args, known), |
| 246 | + _ => Value::Call(f, args), |
| 247 | + }, |
| 248 | + Value::CallFn(g, args) => self.call(program, g, args, known), |
| 249 | + value => value, |
| 250 | + } |
| 251 | + } |
| 252 | + |
| 253 | + /// Field `i` of a known value. |
| 254 | + fn field(&self, k: &Known, i: usize) -> Option<Known> { |
| 255 | + match k { |
| 256 | + Known::Dict(d) => self.field(&self.dicts[d], i), |
| 257 | + Known::Tuple(parts) => parts.get(i).cloned(), |
| 258 | + Known::Closure(_) => None, |
| 259 | + } |
| 260 | + } |
| 261 | + |
| 262 | + /// A direct call of `g`: to its specialised copy if some arguments are |
| 263 | + /// constant dictionaries, inlined if trivial. |
| 264 | + fn call( |
| 265 | + &mut self, |
| 266 | + program: &mut Program, |
| 267 | + g: FnId, |
| 268 | + args: Vec<Atom>, |
| 269 | + known: &HashMap<VarId, Known>, |
| 270 | + ) -> Value { |
| 271 | + let g = self.copy_for(program, g, &args, known); |
| 272 | + if let Some(body) = self.trivial.get(&g) { |
| 273 | + let params = &program.fns[g as usize].params; |
| 274 | + if params.len() == args.len() { |
| 275 | + return substitute(body, params, &args); |
| 276 | + } |
| 277 | + } |
| 278 | + Value::CallFn(g, args) |
| 279 | + } |
| 280 | + |
| 281 | + /// The copy of `g` specialised for the constant dictionaries among |
| 282 | + /// `args`, made if needed and the budget allows; else `g`. |
| 283 | + fn copy_for( |
| 284 | + &mut self, |
| 285 | + program: &mut Program, |
| 286 | + g: FnId, |
| 287 | + args: &[Atom], |
| 288 | + known: &HashMap<VarId, Known>, |
| 289 | + ) -> FnId { |
| 290 | + let mut dicts: Vec<Option<FnId>> = args |
| 291 | + .iter() |
| 292 | + .map(|a| match a { |
| 293 | + Atom::Var(x) => match known.get(x) { |
| 294 | + Some(Known::Dict(d)) => Some(*d), |
| 295 | + _ => None, |
| 296 | + }, |
| 297 | + _ => None, |
| 298 | + }) |
| 299 | + .collect(); |
| 300 | + // A copy is specialised further from its original, not copied. |
| 301 | + let mut g = g; |
| 302 | + if let Some((original, made_for)) = self.origin.get(&g) |
| 303 | + && made_for.len() == dicts.len() |
| 304 | + { |
| 305 | + for (d, m) in dicts.iter_mut().zip(made_for) { |
| 306 | + *d = d.or(*m); |
| 307 | + } |
| 308 | + g = *original; |
| 309 | + } |
| 310 | + let decl = &program.fns[g as usize]; |
| 311 | + if dicts.iter().all(Option::is_none) |
| 312 | + || decl.params.len() != args.len() |
| 313 | + || self.dicts.contains_key(&g) |
| 314 | + { |
| 315 | + return g; |
| 316 | + } |
| 317 | + if let Some(copy) = self.copies.get(&(g, dicts.clone())) { |
| 318 | + return *copy; |
| 319 | + } |
| 320 | + if self.budget == 0 { |
| 321 | + return g; |
| 322 | + } |
| 323 | + self.budget -= 1; |
| 324 | + let names: Vec<&str> = dicts |
| 325 | + .iter() |
| 326 | + .flatten() |
| 327 | + .map(|d| program.fns[*d as usize].name.as_str()) |
| 328 | + .collect(); |
| 329 | + let copy = FnDecl { |
| 330 | + name: format!("{} [{}]", decl.name, names.join(", ")), |
| 331 | + params: decl.params.clone(), |
| 332 | + body: Expr::Return(Atom::Unit), // made from the original's, later |
| 333 | + n_vars: decl.n_vars, |
| 334 | + borrowed: decl.borrowed.clone(), |
| 335 | + span: decl.span, |
| 336 | + }; |
| 337 | + let params_known: HashMap<VarId, Known> = decl |
| 338 | + .params |
| 339 | + .iter() |
| 340 | + .zip(&dicts) |
| 341 | + .filter_map(|(p, d)| d.map(|d| (*p, Known::Dict(d)))) |
| 342 | + .collect(); |
| 343 | + program.fns.push(copy); |
| 344 | + let id = (program.fns.len() - 1) as FnId; |
| 345 | + self.copies.insert((g, dicts.clone()), id); |
| 346 | + self.origin.insert(id, (g, dicts)); |
| 347 | + self.queue.push((id, g, params_known)); |
| 348 | + id |
| 349 | + } |
| 350 | +} |
| 351 | + |
| 352 | +/// `body` (a trivial function's value) with its parameters replaced by |
| 353 | +/// `args`. |
| 354 | +fn substitute(body: &Value, params: &[VarId], args: &[Atom]) -> Value { |
| 355 | + let map = |atoms: &[Atom]| -> Vec<Atom> { |
| 356 | + atoms |
| 357 | + .iter() |
| 358 | + .map(|a| match a { |
| 359 | + Atom::Var(x) => { |
| 360 | + let i = params.iter().position(|p| p == x).expect("a parameter"); |
| 361 | + args[i].clone() |
| 362 | + } |
| 363 | + a => a.clone(), |
| 364 | + }) |
| 365 | + .collect() |
| 366 | + }; |
| 367 | + match body { |
| 368 | + Value::CallExtern(sym, atoms) => Value::CallExtern(sym.clone(), map(atoms)), |
| 369 | + Value::Prim(p, atoms) => Value::Prim(*p, map(atoms)), |
| 370 | + _ => unreachable!("only extern calls and primitives are trivial bodies"), |
| 371 | + } |
| 372 | +} |
| 373 | + |
| 374 | +/// Whether removing an unused `let` of `value` changes nothing but |
| 375 | +/// allocation: no call, operation or control flow. |
| 376 | +fn pure(value: &Value) -> bool { |
| 377 | + matches!( |
| 378 | + value, |
| 379 | + Value::Atom(_) |
| 380 | + | Value::Field(..) |
| 381 | + | Value::Prim(..) |
| 382 | + | Value::Tuple(_) |
| 383 | + | Value::Construct { .. } |
| 384 | + | Value::Closure(..) |
| 385 | + ) |
| 386 | +} |
| 387 | + |
| 388 | +/// Remove the `let`s of pure values that nothing uses: the projections and |
| 389 | +/// dictionary reads devirtualisation leaves behind (reading a constant |
| 390 | +/// dictionary, one of `dicts`, only builds closures and tuples). Works |
| 391 | +/// backwards over chains, in linear time. |
| 392 | +fn remove_unused(e: Expr, dicts: &HashMap<FnId, Known>) -> Expr { |
| 393 | + remove_unused_in(e, dicts, &mut BTreeSet::new()) |
| 394 | +} |
| 395 | + |
| 396 | +/// [`remove_unused`], adding the free variables of the result to `used`. |
| 397 | +fn remove_unused_in(e: Expr, dicts: &HashMap<FnId, Known>, used: &mut BTreeSet<VarId>) -> Expr { |
| 398 | + let mut lets = Vec::new(); |
| 399 | + let mut end = e; |
| 400 | + while let Expr::Let(v, value, rest, span) = end { |
| 401 | + lets.push((v, *value, span)); |
| 402 | + end = *rest; |
| 403 | + } |
| 404 | + let atom = |a: &Atom, used: &mut BTreeSet<VarId>| { |
| 405 | + if let Atom::Var(x) = a { |
| 406 | + used.insert(*x); |
| 407 | + } |
| 408 | + }; |
| 409 | + let mut out = match end { |
| 410 | + Expr::Return(a) => { |
| 411 | + atom(&a, used); |
| 412 | + Expr::Return(a) |
| 413 | + } |
| 414 | + Expr::Switch { on, cases, default } => { |
| 415 | + atom(&on, used); |
| 416 | + Expr::Switch { |
| 417 | + on, |
| 418 | + cases: cases |
| 419 | + .into_iter() |
| 420 | + .map(|(t, b)| (t, remove_unused_in(b, dicts, used))) |
| 421 | + .collect(), |
| 422 | + default: default.map(|d| Box::new(remove_unused_in(*d, dicts, used))), |
| 423 | + } |
| 424 | + } |
| 425 | + Expr::SwitchLit { on, cases, default } => { |
| 426 | + atom(&on, used); |
| 427 | + Expr::SwitchLit { |
| 428 | + on, |
| 429 | + cases: cases |
| 430 | + .into_iter() |
| 431 | + .map(|(l, b)| (l, remove_unused_in(b, dicts, used))) |
| 432 | + .collect(), |
| 433 | + default: Box::new(remove_unused_in(*default, dicts, used)), |
| 434 | + } |
| 435 | + } |
| 436 | + end @ Expr::Panic(_) => end, |
| 437 | + Expr::Let(..) | Expr::Dup(..) | Expr::Drop(..) | Expr::Release { .. } => { |
| 438 | + unreachable!("Core before Perceus, after its `let`s") |
| 439 | + } |
| 440 | + }; |
| 441 | + for (v, value, span) in lets.into_iter().rev() { |
| 442 | + let dictionary_read = |
| 443 | + matches!(&value, Value::CallFn(g, args) if args.is_empty() && dicts.contains_key(g)); |
| 444 | + let removable = pure(&value) || dictionary_read; |
| 445 | + if removable && !used.contains(&v) { |
| 446 | + continue; |
| 447 | + } |
| 448 | + used.remove(&v); |
| 449 | + let value = match value { |
| 450 | + Value::Block(inner) => Value::Block(Box::new(remove_unused_in(*inner, dicts, used))), |
| 451 | + value => { |
| 452 | + value_vars(&value, used); |
| 453 | + value |
| 454 | + } |
| 455 | + }; |
| 456 | + out = Expr::Let(v, Box::new(value), Box::new(out), span); |
| 457 | + } |
| 458 | + out |
| 459 | +} |
| 460 | + |
| 461 | +fn value_vars(value: &Value, used: &mut BTreeSet<VarId>) { |
| 462 | + let mut atoms = |atoms: &[Atom]| { |
| 463 | + for a in atoms { |
| 464 | + if let Atom::Var(x) = a { |
| 465 | + used.insert(*x); |
| 466 | + } |
| 467 | + } |
| 468 | + }; |
| 469 | + match value { |
| 470 | + Value::Atom(a) => atoms(std::slice::from_ref(a)), |
| 471 | + Value::Call(f, args) => { |
| 472 | + atoms(std::slice::from_ref(f)); |
| 473 | + atoms(args); |
| 474 | + } |
| 475 | + Value::CallFn(_, args) |
| 476 | + | Value::CallExtern(_, args) |
| 477 | + | Value::Prim(_, args) |
| 478 | + | Value::Tuple(args) |
| 479 | + | Value::Construct { args, .. } |
| 480 | + | Value::Closure(_, args) => atoms(args), |
| 481 | + Value::Field(base, _) => atoms(std::slice::from_ref(base)), |
| 482 | + Value::Perform { cap, args, .. } => { |
| 483 | + atoms(std::slice::from_ref(cap)); |
| 484 | + atoms(args); |
| 485 | + } |
| 486 | + Value::Handle { |
| 487 | + body, ret, clauses, .. |
| 488 | + } => { |
| 489 | + atoms(std::slice::from_ref(body)); |
| 490 | + if let Some(r) = ret { |
| 491 | + atoms(std::slice::from_ref(r)); |
| 492 | + } |
| 493 | + atoms(clauses); |
| 494 | + } |
| 495 | + Value::Region { body, .. } => atoms(std::slice::from_ref(body)), |
| 496 | + Value::Defer { body, cleanup } => atoms(&[body.clone(), cleanup.clone()]), |
| 497 | + Value::Reuse { token, value } => { |
| 498 | + used.insert(*token); |
| 499 | + value_vars(value, used); |
| 500 | + } |
| 501 | + Value::Block(_) => unreachable!("blocks are walked by `remove_unused_in`"), |
| 502 | + } |
| 503 | +} |