Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Cranelift: add "fuel" to egraph rewrites. (#13390)

Chris Fallin66f1b3bce6b4
diff --git a/cranelift/codegen/src/egraph/mod.rs b/cranelift/codegen/src/egraph/mod.rs
index 47455a9eca..0ac2b9d036 100644
--- a/cranelift/codegen/src/egraph/mod.rs
+++ b/cranelift/codegen/src/egraph/mod.rs
@@ -281,6 +281,12 @@ const MATCHES_LIMIT: usize = 5;
/// The maximum number of enodes in any given eclass.
const ECLASS_ENODE_LIMIT: usize = 5;
+/// The amount of "fuel" available for each top-level rewrite
+/// invocation's eclass extractors.
+///
+/// Each yield from a multi-extractor iterator consumes one unit.
+pub(crate) const EXTRACTOR_FUEL: u32 = 500;
+
/// Context passed through node insertion and optimization.
pub(crate) struct OptimizeCtx<'opt, 'analysis>
where
@@ -301,6 +307,7 @@ where
ctrl_plane: &'opt mut ControlPlane,
// Held locally during optimization of one node (recursively):
pub(crate) rewrite_depth: usize,
+ pub(crate) extractor_fuel: u32,
pub(crate) subsume_values: FxHashSet<Value>,
optimized_values: SmallVec<[Value; MATCHES_LIMIT]>,
optimized_insts: SmallVec<[SkeletonInstSimplification; MATCHES_LIMIT]>,
@@ -1056,6 +1063,7 @@ impl<'a> EgraphPass<'a> {
available_block: &mut available_block,
eclass_size: &mut eclass_size,
rewrite_depth: 0,
+ extractor_fuel: EXTRACTOR_FUEL,
subsume_values: FxHashSet::default(),
remat_values: &mut self.remat_values,
stats: &mut self.stats,
@@ -1274,6 +1282,7 @@ pub(crate) struct Stats {
pub(crate) rewrite_rule_invoked: u64,
pub(crate) rewrite_rule_results: u64,
pub(crate) rewrite_depth_limit: u64,
+ pub(crate) rewrite_fuel_exhausted: u64,
pub(crate) elaborate_visit_node: u64,
pub(crate) elaborate_memoize_hit: u64,
pub(crate) elaborate_memoize_miss: u64,
diff --git a/cranelift/codegen/src/opts.rs b/cranelift/codegen/src/opts.rs
index 07d395a464..3471acb2f1 100644
--- a/cranelift/codegen/src/opts.rs
+++ b/cranelift/codegen/src/opts.rs
@@ -103,6 +103,17 @@ where
continue;
}
ValueDef::Result(inst, _) if ctx.ctx.func.dfg.inst_results(inst).len() == 1 => {
+ // Charge one unit of fuel per yielded match. When
+ // fuel is exhausted, terminate iteration early:
+ // returning no matches is always semantically valid
+ // (we just skip would-be rewrites) and bounds work
+ // per top-level ISLE invocation.
+ if ctx.ctx.extractor_fuel == 0 {
+ ctx.ctx.stats.rewrite_fuel_exhausted += 1;
+ trace!(" -> rewrite fuel exhausted");
+ return None;
+ }
+ ctx.ctx.extractor_fuel -= 1;
let ty = ctx.ctx.func.dfg.value_type(value);
trace!(" -> value of type {}", ty);
return Some((ty, ctx.ctx.func.dfg.insts[inst]));