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
36 changes: 21 additions & 15 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,27 @@ impl<'p, 'a> Ff<'p, 'a> {
let Some(id) = self.m.id(lvalue.name()) else {
return;
};
let variable = self.m.var(id);
let constant = match lvalue {
sv::ir::LValue::Ident(_) => None,
sv::ir::LValue::Select { msb, lsb, .. } => sv::typecheck::eval_const_expr_with_types(
msb,
self.m.constants,
self.m.parameter_types,
)
.zip(sv::typecheck::eval_const_expr_with_types(
lsb,
self.m.constants,
self.m.parameter_types,
))
.and_then(|(msb, lsb)| constant_select_write(variable, msb, lsb)),
};
// An empty constant write is not a dynamic write of the whole
// variable. Keep it out of publication and latch-coverage targets.
if matches!(constant, Some((None, _))) {
return;
}
let constant = constant.and_then(|(access, _)| access);
if blocking {
self.working.insert(id);
} else {
Expand All @@ -288,7 +309,6 @@ impl<'p, 'a> Ff<'p, 'a> {
if self.m.is_hidden(id) {
return;
}
let variable = self.m.var(id);
// A run-time bit select within one array element writes only that
// element (see `write`); a run-time element may be any of them.
let element_write = dynamic_array_element_lvalue(
Expand All @@ -312,20 +332,6 @@ impl<'p, 'a> Ff<'p, 'a> {
.flatten()
.and_then(|write| write.window)
.unwrap_or(BitAccess::new(0, variable.width - 1));
let constant = match lvalue {
sv::ir::LValue::Ident(_) => None,
sv::ir::LValue::Select { msb, lsb, .. } => sv::typecheck::eval_const_expr_with_types(
msb,
self.m.constants,
self.m.parameter_types,
)
.zip(sv::typecheck::eval_const_expr_with_types(
lsb,
self.m.constants,
self.m.parameter_types,
))
.and_then(|(msb, lsb)| constant_select_write(variable, msb, lsb)?.0),
};
if constant.is_none() {
// `write` takes the same order: a constant range, then one
// run-time element, then a read-modify-write of the variable.
Expand Down
60 changes: 44 additions & 16 deletions crates/celox-sv-analyzer/src/ast/selects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ pub(super) fn lvalue_from_indices(
packed_dimensions: &PackedDimensions,
) -> Converted<LValue> {
if let Some((array_offset, packed_indices)) =
flatten_variable_select(state, &name, &indices, packed_dimensions)
flatten_variable_select(&name, &indices, packed_dimensions)
{
if !packed_indices.is_empty() {
if let Some((msb, lsb)) =
Expand Down Expand Up @@ -186,6 +186,43 @@ pub(super) fn lvalue_from_indices(
Ok(LValue::Ident(name))
}

/// Fold the invalid-element sentinel emitted by `flatten_variable_select`.
/// Keep the selected integral type even in an unselected conditional arm:
/// both operands determine the conditional width and signedness (11.4.11).
pub(super) fn invalid_unpacked_read(
state: &AnalysisState,
lhs: &LValue,
dimensions: &PackedDimensions,
) -> Option<Expr> {
let LValue::Select {
name,
msb,
lsb,
signed,
..
} = lhs
else {
return None;
};
let variable = dimensions.get(name)?;
if variable.unpacked.is_empty() || variable.real || variable.string || variable.class.is_some()
{
return None;
}
let full_width = lvalue_expr_type(state, &LValue::Ident(name.clone()), dimensions)?.width;
let msb = eval_ast_const_expr(state, msb, &dimensions.const_env)?;
let lsb = eval_ast_const_expr(state, lsb, &dimensions.const_env)?;
if msb < lsb || lsb < i128::try_from(full_width).ok()? {
return None;
}
let width = usize::try_from(msb.checked_sub(lsb)?)
.ok()?
.checked_add(1)?;
let signing = if *signed { "s" } else { "" };
let digit = if variable.is_2state { "0" } else { "x" };
Some(Expr::Literal(format!("{width}'{signing}b{digit}")))
}

/// Shared syntax-independent assignment range flattening and array metadata.
pub(super) fn lvalue_from_range(
state: &AnalysisState,
Expand Down Expand Up @@ -348,7 +385,6 @@ pub(super) fn indexed_range_values(
}

fn flatten_variable_select(
state: &AnalysisState,
name: &str,
indices: &[ConstExpr],
packed_dimensions: &PackedDimensions,
Expand All @@ -360,15 +396,9 @@ fn flatten_variable_select(
let mut offset = ConstExpr::Literal("0".to_string());
let mut valid = None;
for (index, value) in indices[..selected_unpacked_count].iter().enumerate() {
if const_expr_is_out_of_range(
state,
value,
&dimensions.unpacked[index].left,
&dimensions.unpacked[index].right,
&packed_dimensions.const_env,
) {
return None;
}
// Constant and runtime invalid indices have the same semantics:
// read the element type's default value and ignore writes (7.4.5).
// Route both through the guard below instead of rejecting constants.
let dimension = &dimensions.unpacked[index];
let descending = ConstExpr::Binary {
left: Box::new(dimension.left.clone()),
Expand Down Expand Up @@ -483,7 +513,7 @@ fn unpacked_select_range_metadata(
) {
return None;
}
let (_, packed_indices) = flatten_variable_select(state, name, indices, packed_dimensions)?;
let (_, packed_indices) = flatten_variable_select(name, indices, packed_dimensions)?;
if !packed_indices.is_empty() {
return None;
}
Expand Down Expand Up @@ -554,8 +584,7 @@ fn flatten_unpacked_select_range(
) {
return None;
}
let (array_offset, packed_indices) =
flatten_variable_select(state, name, indices, packed_dimensions)?;
let (array_offset, packed_indices) = flatten_variable_select(name, indices, packed_dimensions)?;
if !packed_indices.is_empty() {
return None;
}
Expand Down Expand Up @@ -642,8 +671,7 @@ fn flatten_select_range(
packed_dimensions,
);
}
let (array_offset, packed_indices) =
flatten_variable_select(state, name, indices, packed_dimensions)?;
let (array_offset, packed_indices) = flatten_variable_select(name, indices, packed_dimensions)?;
let dimension = dimensions.packed.get(packed_indices.len())?;
if const_expr_is_out_of_range(
state,
Expand Down
3 changes: 3 additions & 0 deletions crates/celox-sv-analyzer/src/ast/statements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,9 @@ pub(super) fn expr_from_lvalue(
lhs: &LValue,
packed_dimensions: &PackedDimensions,
) -> Expr {
if let Some(value) = selects::invalid_unpacked_read(state, lhs, packed_dimensions) {
return value;
}
let (base, array_slice_width, array_slice_reversed, signed) = match lhs {
LValue::Ident(name) => return Expr::Ident(name.clone()),
LValue::Select {
Expand Down
171 changes: 171 additions & 0 deletions crates/celox-test-suite/src/sv/cases/indexed_select.vtest
Original file line number Diff line number Diff line change
Expand Up @@ -1959,6 +1959,177 @@
(run_until 1)
(assert_eq s0 0) (assert_eq s1 0x42) (assert_eq s2 0))

(case generated_pipeline_with_unselected_invalid_array_element
; IEEE 1800-2023 7.4.5 and 11.4.11: an invalid element in the unused
; conditional arm must not prevent elaboration or change the result type.
(source "generated_pipeline.sv" #"
module Asc #(parameter N=0)(input logic clk, rst, input logic [7:0] d,
output logic [7:0] q);
if (N>0) begin : pipe
logic [7:0] r[3:N+2];
for(genvar n=0;n<N;n++) begin : stage
always_ff @(posedge clk)
if (rst) r[n+3] <= '0;
else r[n+3] <= n==0 ? d : r[n+2];
end
assign q=r[N+2];
end else assign q=d;
endmodule
module Desc #(parameter N=0)(input logic clk, rst, input logic [7:0] d,
output logic [7:0] q);
if (N>0) begin : pipe
logic [7:0] r[N+2:3];
for(genvar n=0;n<N;n++) begin : stage
always_ff @(posedge clk)
if (rst) r[n+3] <= '0;
else r[n+3] <= n==0 ? d : r[n+2];
end
assign q=r[N+2];
end else assign q=d;
endmodule
module Top(input logic clk, rst, input logic [7:0] d,
output logic [7:0] a1,a2,a4,b1,b2,b4);
Asc #(.N(1)) u1(clk,rst,d,a1);
Asc #(.N(2)) u2(clk,rst,d,a2);
Asc #(.N(4)) u4(clk,rst,d,a4);
Desc #(.N(1)) v1(clk,rst,d,b1);
Desc #(.N(2)) v2(clk,rst,d,b2);
Desc #(.N(4)) v4(clk,rst,d,b4);
endmodule
"#)
(top Top)
(modify (set rst 1))
(tick clk)
(modify (set rst 0))
(for cycle (range 1 8)
(modify (set d (* cycle 17)))
(tick clk)
(assert_eq a1 (* cycle 17))
(assert_eq b1 (* cycle 17))
(assert_eq a2 (? (> cycle 1) (* (- cycle 1) 17) 0))
(assert_eq b2 (? (> cycle 1) (* (- cycle 1) 17) 0))
(assert_eq a4 (? (> cycle 3) (* (- cycle 3) 17) 0))
(assert_eq b4 (? (> cycle 3) (* (- cycle 3) 17) 0))))

(case constant_invalid_unpacked_indices_read_defaults_and_ignore_writes
; IEEE 1800-2023 7.4.5, Table 7-1. Invalid inner indices must never
; wrap into a neighboring element, in either declaration direction.
(four_state)
(source "constant_invalid_array_indices.sv" #"
module Top(input logic clk, input logic [7:0] d,
output logic [7:0] above, below, inner, row,
output logic [7:0] written, written_ff,
output logic [128:0] wide);
logic [7:0] a[3:4];
logic [7:0] b[4:3];
logic [7:0] matrix[0:1][0:2];
logic [7:0] w[3:4], f[3:4];
logic [128:0] wide_array[2];
assign wide=wide_array[2];
always_comb begin
a[3]=d; a[4]=~d;
b[3]=d; b[4]=~d;
for (int i=0;i<2;i++) for (int j=0;j<3;j++) matrix[i][j]=d;
w[3]=d; w[4]=~d;
w[2]=8'hff; w[5]=8'hff;
end
always_ff @(posedge clk) begin
f[3]<=d; f[4]<=~d;
f[2]<=8'hff; f[5]<=8'hff;
end
assign below=a[2];
assign above=b[5];
assign inner=matrix[0][3];
assign row=matrix[2][0];
assign written=w[3]^w[4];
assign written_ff=f[3]^f[4];
endmodule
"#)
(top Top)
(for value (list 0x12 0xa5 0xff)
(modify (set d value))
(assert_eq below (fourstate 255 255))
(assert_eq above (fourstate 255 255))
(assert_eq inner (fourstate 255 255))
(assert_eq row (fourstate 255 255))
(let wide_mask (- (<< 1 129) 1))
(assert_eq wide (fourstate wide_mask wide_mask))
(assert_eq written 255)
(tick clk)
(assert_eq written_ff 255)))

(case generated_pipeline_with_unselected_invalid_array_element_four_state
; IEEE 1800-2023 7.4.5 and 11.4.11: an invalid element in the unused
; conditional arm must not prevent elaboration or change the result type.
(four_state)
(source "generated_pipeline.sv" #"
module Asc #(parameter N=0)(input logic clk, rst, input logic [7:0] d,
output logic [7:0] q);
if (N>0) begin : pipe
logic [7:0] r[3:N+2];
for(genvar n=0;n<N;n++) begin : stage
always_ff @(posedge clk)
if (rst) r[n+3] <= '0;
else r[n+3] <= n==0 ? d : r[n+2];
end
assign q=r[N+2];
end else assign q=d;
endmodule
module Desc #(parameter N=0)(input logic clk, rst, input logic [7:0] d,
output logic [7:0] q);
if (N>0) begin : pipe
logic [7:0] r[N+2:3];
for(genvar n=0;n<N;n++) begin : stage
always_ff @(posedge clk)
if (rst) r[n+3] <= '0;
else r[n+3] <= n==0 ? d : r[n+2];
end
assign q=r[N+2];
end else assign q=d;
endmodule
module Top(input logic clk, rst, input logic [7:0] d,
output logic [7:0] a1,a2,a4,b1,b2,b4);
Asc #(.N(1)) u1(clk,rst,d,a1);
Asc #(.N(2)) u2(clk,rst,d,a2);
Asc #(.N(4)) u4(clk,rst,d,a4);
Desc #(.N(1)) v1(clk,rst,d,b1);
Desc #(.N(2)) v2(clk,rst,d,b2);
Desc #(.N(4)) v4(clk,rst,d,b4);
endmodule
"#)
(top Top)
(modify (set rst 1))
(tick clk)
(modify (set rst 0))
(for cycle (range 1 8)
(modify (set d (* cycle 17)))
(tick clk)
(assert_eq a1 (* cycle 17))
(assert_eq b1 (* cycle 17))
(assert_eq a2 (? (> cycle 1) (* (- cycle 1) 17) 0))
(assert_eq b2 (? (> cycle 1) (* (- cycle 1) 17) 0))
(assert_eq a4 (? (> cycle 3) (* (- cycle 3) 17) 0))
(assert_eq b4 (? (> cycle 3) (* (- cycle 3) 17) 0))))

(case invalid_unpacked_elements_preserve_type_in_conditionals
; Both conditional operands contribute width and signedness even when
; a constant condition selects the other operand (11.4.11, 11.8.2).
(four_state)
(source "invalid_array_element_types.sv" #"
module Top(output logic [15:0] mixed_sign, both_signed,
output logic [31:0] width);
logic [15:0] u[1];
logic signed [15:0] s[1];
assign mixed_sign=1'b1 ? 8'sh80 : u[-1];
assign both_signed=1'b1 ? 8'sh80 : s[-1];
assign width=$bits(1'b1 ? 8'sh80 : u[-1]);
endmodule
"#)
(top Top)
(assert_eq mixed_sign 0x0080)
(assert_eq both_signed 0xff80)
(assert_eq width 16))

(case generated_pipeline_with_explicit_generate_branches
; Separate FF producers may share one array. Removing a task's staging
; must preserve publication of elements computed by other tasks (10.4.2).
Expand Down
17 changes: 9 additions & 8 deletions crates/celox/tests/diagnostic_policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -604,14 +604,15 @@ mod inferred_latch {
#[test]
fn out_of_bounds_state_writes_do_not_expand_diagnostic_masks() {
let source = "module Top(output logic [7:0] q); logic [7:0] a[2]; always_comb begin q=$time; a[-1]=$time; a[2147483647]=$time; end endmodule";
let error = Simulator::from_sv_sources(vec![(source, Path::new("oob_state.sv"))], "Top")
.diagnostic_policy(policy("inferred_latch", DiagnosticLevel::Warn))
.build_interpreter()
.unwrap_err();
assert!(
error.to_string().contains("outside its declared range"),
"{error}"
);
// Invalid unpacked writes are ignored (IEEE 1800-2023 7.4.5).
// Their offsets must not enlarge coverage masks or create a latch.
for level in [DiagnosticLevel::Error, DiagnosticLevel::Warn] {
let sim = Simulator::from_sv_sources(vec![(source, Path::new("oob_state.sv"))], "Top")
.diagnostic_policy(policy("inferred_latch", level))
.build_interpreter()
.unwrap();
assert!(sim.warnings().is_empty(), "{:?}", sim.warnings());
}
}
}

Expand Down
Loading
Loading