Skip to content

[TableGen] Avoid evaluating RHS of a BinOp until short-circuit is complete #144021

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 13, 2025
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
11 changes: 6 additions & 5 deletions llvm/lib/TableGen/Record.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1557,8 +1557,7 @@ const Init *BinOpInit::Fold(const Record *CurRec) const {
}

const Init *BinOpInit::resolveReferences(Resolver &R) const {
const Init *lhs = LHS->resolveReferences(R);
const Init *rhs = RHS->resolveReferences(R);
const Init *NewLHS = LHS->resolveReferences(R);

unsigned Opc = getOpcode();
if (Opc == AND || Opc == OR) {
Expand All @@ -1570,15 +1569,17 @@ const Init *BinOpInit::resolveReferences(Resolver &R) const {
// limited version of short-circuit against all ones (`true` is casted
// to 1 rather than all ones before we evaluate `!or`).
if (const auto *LHSi = dyn_cast_or_null<IntInit>(
lhs->convertInitializerTo(IntRecTy::get(getRecordKeeper())))) {
NewLHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())))) {
if ((Opc == AND && !LHSi->getValue()) ||
(Opc == OR && LHSi->getValue() == -1))
return LHSi;
}
}

if (LHS != lhs || RHS != rhs)
return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))
const Init *NewRHS = RHS->resolveReferences(R);

if (LHS != NewLHS || RHS != NewRHS)
return (BinOpInit::get(getOpcode(), NewLHS, NewRHS, getType()))
->Fold(R.getCurrentRecord());
return this;
}
Expand Down
9 changes: 7 additions & 2 deletions llvm/test/TableGen/true-false.td
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,18 @@ def rec7 {
bits<3> flags = { true, false, true };
}

// `!and` and `!or` should be short-circuit such that `!tail` on empty list will never
// be evaluated.
// `!and` and `!or` should be short-circuited such that any of the `!head` or
// `!tail` on empty list below will never be evaluated.
// CHECK: def rec8
// CHECK: bit v = 0;
// CHECK: int v2 = -1;
// CHECK: list<int> newSeq = [];
// CHECK: list<int> newSeq2 = [];

class Foo <list<int> seq = []> {
bit v = !and(false, !head(seq));
int v2 = !or(-1, !head(seq));

bit unresolved = !ne(!find(NAME, "BAR"), -1);
list<int> newSeq = !if(!and(false, unresolved), !tail(seq), seq);
list<int> newSeq2 = !if(!or(-1, unresolved), seq, !tail(seq));
Expand Down
Loading