8000 Internal code movements. by copybara-service[bot] · Pull Request #5556 · google/xls · GitHub
[go: up one dir, main page]

Skip to content
Draft
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
11 changes: 8 additions & 3 deletions docs_src/dslx_reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -1365,9 +1365,14 @@ shift-right (logical).
### Comparison Expressions

Comparison expressions require operands of the same type and return `bool`
(`bits[1]`). Ordering operators (`<`, `<=`, `>`, `>=`) require bits-typed
operands. To order numeric enum values, cast both operands to the enum's
underlying integer type.
(`bits[1]`). Equality operators (`==`, `!=`) and the `assert_eq` and `assert_ne`
builtins support bits and enums. They also support arrays, tuples, and ordinary
structs when the element type or every member type supports equality,
recursively.

Ordering operators (`<`, `<=`, `>`, `>=`) require bits-typed operands. To
order numeric enum values, cast both operands to the enum's underlying integer
type.

- equal (`==`)
- not-equal (`!=`)
Expand Down
1 change: 1 addition & 0 deletions docs_src/ir_semantics.md
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,7 @@ operations are free to return any values that sum to the product `lhs * rhs`.
### Equality comparison operations

Performs an equality comparison on a pair of identically-typed operands.
Neither operand may contain a token, including within a tuple or array.
Produces a result of bits[1] type.

**Syntax**
Expand Down
1 change: 1 addition & 0 deletions xls/dslx/type_system_v2/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -917,6 +917,7 @@ cc_library(
"//xls/dslx/type_system:unwrap_meta_type",
"//xls/ir:bits",
"//xls/ir:bits_ops",
"@abseil-cpp//absl/algorithm:container",
"@abseil-cpp//absl/base",
"@abseil-cpp//absl/container:flat_hash_map",
"@abseil-cpp//absl/log:check",
Expand Down
36 changes: 36 additions & 0 deletions xls/dslx/type_system_v2/typecheck_module_v2_array_tuple_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,42 @@ using ::absl_testing::IsOkAndHolds;
using ::testing::AllOf;
using ::testing::HasSubstr;

TEST(TypecheckV2Test, EqualityWithTokenTupleFails) {
EXPECT_THAT(R"(
const A = token();
const B = token();

pub fn main(x: bool) -> bool {
(A,) == (if x { A } else { B },)
}
)",
TypecheckFails(
HasSubstr("'==' requires operands that support equality")));
}

TEST(TypecheckV2Test, InequalityWithTokenFails) {
EXPECT_THAT("fn f(a: token, b: token) -> bool { a != b }",
TypecheckFails(
HasSubstr("'!=' requires operands that support equality")));
}

TEST(TypecheckV2Test, EqualityWithNestedChannelFails) {
EXPECT_THAT(R"(
struct Handles { pair: (u32, chan<u32> in) }
fn f(a: Handles, b: Handles) -> bool { a == b }
)",
TypecheckFails(
HasSubstr("'==' requires operands that support equality")));
}

TEST(TypecheckV2Test, EqualityWithComparableAggregateMembers) {
XLS_EXPECT_OK(TypecheckV2(R"(
enum E : u2 { A = 0, B = 1 }
struct Record { payload: (E, uN[7][2], ()) }
fn f(a: Record, b: Record) -> bool { a == b && a != b }
)"));
}

TEST(TypecheckV2Test, ConcatOfBitsLiterals) {
EXPECT_THAT("const X = u8:3 ++ u1:1;", TopNodeHasType("uN[9]"));
}
Expand Down
12 changes: 12 additions & 0 deletions xls/dslx/type_system_v2/typecheck_module_v2_builtin_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,18 @@ fn f(x: u32, y: u32) {
TypecheckSucceeds(HasNodeWithType("x", "uN[32]")));
}

TEST(TypecheckV2BuiltinTest, AssertEqWithTokenTupleFails) {
EXPECT_THAT("fn f(a: (token,), b: (token,)) { assert_eq(a, b); }",
TypecheckFails(HasSubstr(
"'assert_eq' requires operands that support equality")));
}

TEST(TypecheckV2BuiltinTest, AssertNeWithTokenFails) {
EXPECT_THAT("fn f(a: token, b: token) { assert_ne(a, b); }",
TypecheckFails(HasSubstr(
"'assert_ne' requires operands that support equality")));
}

TEST(TypecheckV2BuiltinTest, AssertEqExplicitParametricTypeConstants) {
EXPECT_THAT(R"(
fn f() {
Expand Down
53 changes: 50 additions & 3 deletions xls/dslx/type_system_v2/validate_concrete_type.cc
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#include <string_view>
#include <variant>

#include "absl/algorithm/container.h"
#include "absl/base/casts.h"
#include "absl/container/flat_hash_map.h"
#include "absl/log/check.h"
Expand Down Expand Up @@ -98,6 +99,28 @@ bool ContainsIoObject(const Type& type) {
return false;
}

bool SupportsEquality(const Type& type, const ImportData& import_data) {
if (IsBitsLike(type) || type.IsEnum()) {
return true;
}
if (type.IsArray()) {
return SupportsEquality(type.AsArray().element_type(), import_data);
}
auto member_supports_equality = [&](const std::unique_ptr<Type>& member) {
return SupportsEquality(*member, import_data);
};
if (type.IsTuple()) {
return absl::c_all_of(type.AsTuple().members(), member_supports_equality);
}
if (type.IsStruct()) {
const StructType& struct_type = type.AsStruct();
return !IsBuiltinIoObjectDef(&struct_type.nominal_type()) &&
!IsProcDefStateType(type, import_data) &&
absl::c_all_of(struct_type.members(), member_supports_equality);
}
return false;
}

absl::StatusOr<BitsLikeProperties> GetBitsLikeOrError(
const Expr* node, const Type* type, const FileTable& file_table) {
std::optional<BitsLikeProperties> bits_like = GetBitsLike(*type);
Expand Down Expand Up @@ -210,12 +233,14 @@ class TypeValidator : public AstNodeVisitorWithDefault {

absl::Status HandleBinop(const Binop* binop) override {
const BinopKind kind = binop->binop_kind();
if (GetBinopComparisonKinds().contains(kind) && kind != BinopKind::kEq &&
kind != BinopKind::kNe) {
if (GetBinopComparisonKinds().contains(kind)) {
// Both operands have the same type, while the result is always bool.
XLS_ASSIGN_OR_RETURN(const Type* operand_type,
ti_.GetItemOrError(binop->lhs()));
if (!IsBitsLike(*operand_type)) {
if (kind == BinopKind::kEq || kind == BinopKind::kNe) {
XLS_RETURN_IF_ERROR(ValidateEqualityOperand(
binop->op_span(), BinopKindFormat(kind), *operand_type));
} else if (!IsBitsLike(*operand_type)) {
return TypeInferenceErrorStatus(
binop->op_span(), nullptr,
absl::StrFormat(
Expand Down Expand Up @@ -285,6 +310,8 @@ class TypeValidator : public AstNodeVisitorWithDefault {
absl::Status (TypeValidator::*)(const Invocation&, const FunctionType&);
static const auto* builtin_validators =
new absl::flat_hash_map<std::string_view, BuiltinValidator>{
{"assert_eq", &TypeValidator::ValidateEqualityAssertion},
{"assert_ne", &TypeValidator::ValidateEqualityAssertion},
{"cover!", &TypeValidator::ValidateCoverInvocation},
{"decode", &TypeValidator::ValidateDecodeInvocation},
{"update", &TypeValidator::ValidateUpdateInvocation},
Expand Down Expand Up @@ -747,6 +774,26 @@ class TypeValidator : public AstNodeVisitorWithDefault {
return absl::OkStatus();
}

absl::Status ValidateEqualityOperand(const Span& span,
std::string_view operation,
const Type& operand_type) {
if (SupportsEquality(operand_type, import_data_)) {
return absl::OkStatus();
}
return TypeInferenceErrorStatus(
span, nullptr,
absl::StrFormat("'%s' requires operands that support equality, got %s.",
operation, operand_type.ToString()),
file_table_);
}

absl::Status ValidateEqualityAssertion(const Invocation& invocation,
const FunctionType& signature) {
return ValidateEqualityOperand(invocation.callee()->span(),
invocation.callee()->ToString(),
*signature.params().front());
}

absl::Status ValidateCoverInvocation(const Invocation& invocation,
const FunctionType& signature) {
// TODO(williamjhuang) - After TIv2 is enabled the validation logic should
Expand Down
30 changes: 30 additions & 0 deletions xls/ir/verifier_test.cc
Original file line number Diff line number Diff line change
"for this operation")));
}

TEST_F(VerifierTest, EqCompareTupleContainingToken) {
std::string input = R"(
package p

fn f(a: (token), b: (token)) -> bits[1] {
ret eq_val: bits[1] = eq(a, b)
}
)";
XLS_ASSERT_OK_AND_ASSIGN(auto p, ParsePackageNoVerify(input));
EXPECT_THAT(
VerifyPackage(p.get()),
StatusIs(absl::StatusCode::kInternal,
HasSubstr("Operand 0 of eq_val cannot contain a token")));
}

TEST_F(VerifierTest, NeCompareNestedTokenOperands) {
std::string input = R"(
package p

fn f(a: (bits[8], (token)[2]), b: (bits[8], (token)[2])) -> bits[1] {
ret ne_val: bits[1] = ne(a, b)
}
)";
XLS_ASSERT_OK_AND_ASSIGN(auto p, ParsePackageNoVerify(input));
EXPECT_THAT(
VerifyPackage(p.get()),
StatusIs(absl::StatusCode::kInternal,
HasSubstr("Operand 0 of ne_val cannot contain a token")));
}

TEST_F(VerifierTest, SelectWithTooNarrowSelector) {
std::string input = R"(
package p
Expand Down
9 changes: 5 additions & 4 deletions xls/ir/verify_node.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1405,16 +1405,17 @@ class NodeChecker : public DfsVisitor {
return absl::OkStatus();
}

// Verifies all operands are the same type, and that type is not Token.
// Verifies all operands have the same type and that it contains no tokens.
absl::Status ExpectOperandsSameTypeNoToken(Node* node) const {
if (node->operand_count() == 0) {
return absl::OkStatus();
}
Type* type = node->operand(0)->GetType();
if (type->IsToken()) {
if (TypeHasToken(type)) {
return absl::InternalError(absl::StrFormat(
"Operand 0 of %s cannot be Token type for this operation: %s",
node->GetName(), node->ToString()));
"Operand 0 of %s cannot %s for this operation: %s", node->GetName(),
type->IsToken() ? "be Token type" : "contain a token",
node->ToString()));
}
for (int64_t i = 1; i < node->operand_count(); ++i) {
XLS_RETURN_IF_ERROR(ExpectOperandHasType(node, i, type));
Expand Down
5 changes: 2 additions & 3 deletions xls/jit/function_jit_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -927,11 +927,10 @@ TEST(FunctionJitTest, TokenCompareError) {
HasSubstr("cannot be Token type for this operation")));
}

// Make sure the token comparison error is still reported when the token is
// inside a larger structure.
// Exercise the JIT's token comparison check with unverified IR.
TEST(FunctionJitTest, CompoundTokenCompareError) {
Package p("compound_token_eq");
FunctionBuilder b("fun", &p);
FunctionBuilder b("fun", &p, /*should_verify=*/false);

auto p0 = b.Param("tkn", p.GetTokenType());
BValue two = b.Literal(Value(UBits(2, 32)));
Expand Down
Loading
0