Skip to content

Commit

Permalink
Constant-fold some expressions involving variables.
Browse files Browse the repository at this point in the history
  • Loading branch information
bbannier committed May 10, 2023
1 parent b26c4a9 commit 0df13a5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
24 changes: 24 additions & 0 deletions hilti/toolchain/src/compiler/optimizer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -852,6 +852,18 @@ struct ConstantFoldingVisitor : OptimizerVisitor, visitor::PreOrder<bool, Consta
replaceNode(p, builder::bool_(true));
return true;
}

// If the LHS is some variable and the RHS is a literal `true`
// the result is always `true` and we can replace the AND without
// removing side-effects.
if ( auto lhs = x.op0().tryAs<expression::ResolvedID>();
lhs &&
(lhs->declaration().isA<declaration::GlobalVariable>() ||
lhs->declaration().isA<declaration::LocalVariable>()) &&
rhs && rhs.value() ) {
replaceNode(p, builder::bool_(true));
return true;
}
}
};

Expand All @@ -877,6 +889,18 @@ struct ConstantFoldingVisitor : OptimizerVisitor, visitor::PreOrder<bool, Consta
replaceNode(p, builder::bool_(false));
return true;
}

// If the LHS is some variable and the RHS is a literal `false`
// the result is always `false` and we can replace the AND without
// removing side-effects.
if ( auto lhs = x.op0().tryAs<expression::ResolvedID>();
lhs &&
(lhs->declaration().isA<declaration::GlobalVariable>() ||
lhs->declaration().isA<declaration::LocalVariable>()) &&
rhs && ! rhs.value() ) {
replaceNode(p, builder::bool_(false));
return true;
}
}
};

Expand Down
4 changes: 2 additions & 2 deletions tests/Baseline/hilti.optimization.const/opt.hlt
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ False;
True;
1;
1;
a || True;
True;
a || False;
a && True;
a && False;
False;
True;
False || a;
True && a;
Expand Down

0 comments on commit 0df13a5

Please sign in to comment.