Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8827,6 +8827,12 @@ fn runtime_select_width(
if constant(msb).is_some() && constant(lsb).is_some() {
return None;
}
// A bit select has width one regardless of its runtime position. Sampling
// both bounds evaluates the same (potentially inlined) expression twice,
// and the zero sample need not even be a valid index computation.
if msb == lsb {
return Some(1);
}
// The width is the same for every value of the runtime operands.
let mut sample = constants.clone();
for name in name_to_id.keys() {
Expand Down Expand Up @@ -10510,6 +10516,37 @@ fn inferred_clock(
mod tests {
use super::*;

#[test]
fn bit_select_width_does_not_evaluate_a_runtime_zero_sample() {
let index = sv::ir::ConstExpr::Ident("index".into());
let bound = sv::ir::ConstExpr::Binary {
left: Box::new(sv::ir::ConstExpr::Literal("255".into())),
op: sv::ir::BinaryOp::Div,
right: Box::new(index.clone()),
};
let names = HashMap::from_iter([("index".into(), SourceVarId(0))]);
let constants = HashMap::default();
let types = HashMap::default();
assert_eq!(
runtime_select_width(&bound, &bound, &names, &constants, &types),
Some(1)
);
let high = sv::ir::ConstExpr::Binary {
left: Box::new(index.clone()),
op: sv::ir::BinaryOp::Add,
right: Box::new(sv::ir::ConstExpr::Literal("7".into())),
};
assert_eq!(
runtime_select_width(&high, &index, &names, &constants, &types),
Some(8)
);
let constant = sv::ir::ConstExpr::Literal("3".into());
assert_eq!(
runtime_select_width(&constant, &constant, &names, &constants, &types),
None
);
}

/// The per-name driver scan [`ModuleDrivers`] replaced, which walks every
/// process for each name.
mod per_name_scan {
Expand Down
45 changes: 35 additions & 10 deletions crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,46 @@ fn query_context(context: &PackedDimensions) -> PackedDimensions {
query
}

/// These operands carry all type information in their literal leaves. Walking
/// declaration scopes cannot change their shape or signedness. Keep calls,
/// casts and names on the discovery path, including names in unevaluated arms.
fn literal_operand(root: ExprId, native: &celox_sv_syntax::Declarations) -> bool {
let root = expression_binding::ungroup(root, native);
if matches!(native.expression(root).kind, ExprKind::Literal(_)) {
return true;
}
let mut pending = vec![root];
while let Some(id) = pending.pop() {
match &native.expression(id).kind {
ExprKind::Literal(_) => {}
ExprKind::Group(inner)
| ExprKind::Unary {
expression: inner, ..
} => {
pending.push(*inner);
}
ExprKind::Binary { left, right, .. } => pending.extend([*left, *right]),
ExprKind::Conditional {
condition,
then_expression,
else_expression,
} => {
pending.extend([*condition, *then_expression, *else_expression]);
}
_ => return false,
}
}
true
}

pub(in crate::ast) fn query_context_for_operand(
root: ExprId,
tree: &AnalysisContext<'_>,
context: &PackedDimensions,
) -> Converted<PackedDimensions> {
// Literals carry their type in their spelling and cannot reference lexical
// declarations. Pattern elements otherwise rediscover the whole scope for
// each literal while the surrounding declaration is still being bound.
let operand = expression_binding::ungroup(root, tree.declarations());
if context.scope_types_complete
|| matches!(
tree.declarations().expression(operand).kind,
ExprKind::Literal(_)
)
{
// Aggregate port defaults commonly repeat literal arithmetic. Rediscovering
// all declarations for each item repeatedly snapshots the growing prefix.
if context.scope_types_complete || literal_operand(root, tree.declarations()) {
return Ok(query_context(context));
}
Ok(query_context(&query_operand_dimensions_id(
Expand Down
68 changes: 68 additions & 0 deletions crates/celox-sv-analyzer/src/ast/dimensions/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,74 @@ fn query_number(
.and_then(|value| usize::try_from(value).ok())
}

#[test]
fn repeated_literal_port_defaults_do_not_rediscover_declarations() {
for count in [8, 32, 128] {
let ports = (0..count)
.map(|i| format!("input logic [7:0] p{i}[2] = '{{2{{8'd60-1}}}}"))
.collect::<Vec<_>>()
.join(",");
let code = format!("module Top({ports}, output wire [7:0] y); assign y=p0[0]; endmodule");
let tree =
crate::source_tree::parse_scope_fixture(&code, Path::new("literal-port-defaults.sv"))
.unwrap();
let tree = AnalysisContext::unspecialized(&tree);
SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.set(0));
let source = Source::from_syntax(&tree).unwrap();
assert_eq!(source.modules()[0].ports().len(), count + 1);
assert_eq!(
SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.get()),
0,
"{count} ports"
);
}
}

#[test]
fn literal_arithmetic_queries_keep_widths_and_skip_scope_discovery() {
let code = "module Top; assign y=$bits(8'd60-1)+$bits(-8'sd1+16'sd2)+$bits(1'b0 ? 8'hff : 16'hffff)+$bits(~8'hff)+$bits(32'd1<<64'd40); endmodule";
let tree =
crate::source_tree::parse_scope_fixture(code, Path::new("literal-query-types.sv")).unwrap();
let tree = AnalysisContext::unspecialized(&tree);
let input = PackedDimensions::default();
SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.set(0));
let values = native_calls(&tree)
.into_iter()
.map(|root| {
query_number(
root,
&tree,
&HashMap::default(),
&HashMap::default(),
Some(&input),
)
})
.collect::<Vec<_>>();
assert_eq!(values, [Some(32), Some(16), Some(16), Some(8), Some(32)]);
assert_eq!(SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.get()), 0);
}

#[test]
fn queries_still_discover_names_in_unselected_conditional_arms() {
let code = "module Top; logic [15:0] data; assign y=$bits(1'b0 ? data : 8'hff); endmodule";
let tree =
crate::source_tree::parse_scope_fixture(code, Path::new("conditional-query-types.sv"))
.unwrap();
let tree = AnalysisContext::unspecialized(&tree);
SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.set(0));
assert_eq!(
query_number(
native_calls(&tree)[0],
&tree,
&HashMap::default(),
&HashMap::default(),
Some(&PackedDimensions::default())
),
Some(16)
);
assert!(SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.get()) > 0);
}

#[test]
fn function_result_queries_preserve_expression_bodies() {
let tree = crate::source_tree::parse_scope_fixture(
Expand Down
164 changes: 163 additions & 1 deletion crates/celox-sv-analyzer/src/typecheck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,11 @@ pub fn eval_const_expr_with_types(
constants: &HashMap<String, i128>,
types: &HashMap<String, (usize, bool)>,
) -> Option<i128> {
// Runtime select bounds often contain large inlined expressions. Reject a
// required runtime value before attempting literal folding at every node.
if requires_unbound_value(expr, constants) {
return None;
}
// Substitution only replaces the identifiers of typed constants.
if !has_typed_constant(expr, constants, types) {
return eval_const_expr(expr, constants);
Expand All @@ -353,6 +358,38 @@ pub fn eval_const_expr_with_types(
eval_const_expr(&expr, constants)
}

fn requires_unbound_value(expr: &ConstExpr, constants: &HashMap<String, i128>) -> bool {
match expr {
ConstExpr::Literal(_) | ConstExpr::Function { .. } => return false,
ConstExpr::Ident(name) => return !constants.contains_key(name),
_ => {}
}
let mut pending = vec![expr];
while let Some(expr) = pending.pop() {
match expr {
ConstExpr::Ident(name) if !constants.contains_key(name) => return true,
ConstExpr::Unary { expr, .. } | ConstExpr::Resize { expr, .. } => pending.push(expr),
ConstExpr::Select { expr, bit } => pending.extend([bit.as_ref(), expr.as_ref()]),
ConstExpr::SelectRange { expr, msb, lsb, .. } => {
pending.extend([lsb.as_ref(), msb.as_ref(), expr.as_ref()]);
}
ConstExpr::Binary { left, op, right } => {
// A right logical operand can be skipped. The left operand is
// required; preserve the evaluator's short-circuiting policy.
if !matches!(op, BinaryOp::LogicAnd | BinaryOp::LogicOr) {
pending.push(right);
}
pending.push(left);
}
ConstExpr::Mux { condition, .. } => pending.push(condition),
// Argument evaluation belongs to the callee (including checked
// accesses). Do not infer whether a call needs its actuals here.
ConstExpr::Function { .. } | ConstExpr::Literal(_) | ConstExpr::Ident(_) => {}
}
}
false
}

/// Whether `expr` names a constant that has a type, which
/// [`substitute_typed_constants`] replaces with a sized literal.
fn has_typed_constant(
Expand Down Expand Up @@ -714,6 +751,15 @@ fn context_binary_operands(
right: &ConstExpr,
) -> Option<(IntegralLiteral, IntegralLiteral, bool)> {
let (left_type, right_type) = integral_binary_operands(left, right)?;
context_binary_values(left, right, left_type, right_type)
}

fn context_binary_values(
left: &ConstExpr,
right: &ConstExpr,
left_type: IntegralLiteral,
right_type: IntegralLiteral,
) -> Option<(IntegralLiteral, IntegralLiteral, bool)> {
let width = left_type.width.max(right_type.width);
let signed = left_type.signed && right_type.signed;
// These values were already evaluated in their own expression contexts.
Expand Down Expand Up @@ -783,7 +829,7 @@ fn eval_literal_binary(
);
return eval_four_state_binary(&left, op, &right, signed);
}
let (left, right, signed) = context_binary_operands(left_expr, right_expr)?;
let (left, right, signed) = context_binary_values(left_expr, right_expr, left, right)?;
eval_four_state_binary(&left, op, &right, signed)
}

Expand Down Expand Up @@ -1089,7 +1135,14 @@ fn self_determined_integral_literal(expr: &ConstExpr) -> Option<IntegralLiteral>
}
}

#[cfg(test)]
thread_local! {
static LITERAL_EVALUATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

fn integral_literal_from_const_expr(expr: &ConstExpr) -> Option<IntegralLiteral> {
#[cfg(test)]
LITERAL_EVALUATIONS.with(|count| count.set(count.get() + 1));
match expr {
ConstExpr::Literal(literal) => parse_integral_literal(literal),
ConstExpr::Resize {
Expand Down Expand Up @@ -2015,6 +2068,115 @@ fn extension_for_leading_digit(ch: char) -> (bool, bool) {
mod literal_tests {
use super::*;

#[test]
fn numeric_binary_operands_are_evaluated_once_before_type_context() {
let expr = ConstExpr::Binary {
left: Box::new(ConstExpr::Literal("2".into())),
op: BinaryOp::Add,
right: Box::new(ConstExpr::Literal("3".into())),
};
LITERAL_EVALUATIONS.with(|count| count.set(0));
assert_eq!(
eval_const_expr_with_types(&expr, &HashMap::default(), &HashMap::default()),
Some(5)
);
assert_eq!(LITERAL_EVALUATIONS.with(|count| count.get()), 2);
}

#[test]
fn runtime_bounds_skip_literal_evaluation_before_substitution() {
let mut bound = ConstExpr::Ident("runtime_index".into());
for _ in 0..64 {
bound = ConstExpr::Resize {
expr: Box::new(ConstExpr::Binary {
left: Box::new(bound),
op: BinaryOp::Add,
right: Box::new(ConstExpr::Ident("P".into())),
}),
width: 32,
signed: false,
};
}
LITERAL_EVALUATIONS.with(|count| count.set(0));
assert_eq!(
eval_const_expr_with_types(
&bound,
&HashMap::from_iter([("P".into(), 7)]),
&HashMap::from_iter([("P".into(), (32, false))])
),
None
);
assert_eq!(LITERAL_EVALUATIONS.with(|count| count.get()), 0);
}

#[test]
fn runtime_bound_probe_preserves_short_circuiting_and_sampled_values() {
let literal = |text: &str| ConstExpr::Literal(text.into());
let missing = || ConstExpr::Ident("runtime_index".into());
let expressions = [
(
ConstExpr::Binary {
left: Box::new(literal("0")),
op: BinaryOp::LogicAnd,
right: Box::new(missing()),
},
Some(0),
),
(
ConstExpr::Binary {
left: Box::new(literal("1")),
op: BinaryOp::LogicOr,
right: Box::new(missing()),
},
Some(1),
),
(
ConstExpr::Mux {
condition: Box::new(literal("1")),
then_expr: Box::new(literal("13")),
else_expr: Box::new(missing()),
},
Some(13),
),
(
ConstExpr::Mux {
condition: Box::new(literal("0")),
then_expr: Box::new(missing()),
else_expr: Box::new(literal("19")),
},
Some(19),
),
(
ConstExpr::Mux {
condition: Box::new(literal("1'bx")),
then_expr: Box::new(literal("17")),
else_expr: Box::new(literal("17")),
},
Some(17),
),
];
for (expr, expected) in expressions {
assert_eq!(
eval_const_expr_with_types(&expr, &HashMap::default(), &HashMap::default()),
expected,
"{expr:?}"
);
}
let sample = ConstExpr::Binary {
left: Box::new(missing()),
op: BinaryOp::Mul,
right: Box::new(ConstExpr::Ident("P".into())),
};
assert_eq!(
eval_const_expr_with_types(
&sample,
&HashMap::from_iter([("runtime_index".into(), 3), ("P".into(), 7)]),
&HashMap::from_iter([("P".into(), (32, false))])
),
Some(21)
);
}

/// Expressions without typed constants evaluate as their substituted
/// copies do, and typed constants still take their declared type.
#[test]
Expand Down
Loading