Skip to content

Commit 90b86f2

Browse files
author
Enrico Steffinlongo
committed
Avoid adding useless goto blocks in if with return
When the parsed AST is transformed in GOTO language the if conditions are translated in: `if (!c) goto else; then_branch; goto endif; else: else_branch; endif: nop` and `if (!c) goto endif; then_branch; endif: nop`. This commit avoids to add the `goto endif` command and the `endif` label if the `then_branch` ends with a `return` or a `goto` statement. The benefit is that the `--cover location` command returns a more precise result as unreachable code blocks that are added by CBMC's frontend are not marked as unreachable.
1 parent 9238a38 commit 90b86f2

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

src/goto-programs/goto_convert.cpp

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1639,13 +1639,28 @@ void goto_convertt::generate_ifthenelse(
16391639
dest.destructive_append(tmp_v);
16401640
dest.destructive_append(tmp_w);
16411641

1642+
// When the `then` branch of a balanced `if` condition ends with a `return` or
1643+
// a `goto` statement, it is not necessary to add the `goto z` and `z:` goto
1644+
// elements as they are never used.
1645+
// This helps for example when using `--cover location` as such command are
1646+
// marked unreachable, but are not part of the user-provided code to analyze.
1647+
bool then_branch_returns = dest.instructions.rbegin()->is_goto();
1648+
16421649
if(has_else)
16431650
{
1644-
dest.destructive_append(tmp_x);
1651+
// Don't add the `goto` at the end of the `then` branch if not needed
1652+
if(!then_branch_returns)
1653+
{
1654+
dest.destructive_append(tmp_x);
1655+
}
16451656
dest.destructive_append(tmp_y);
16461657
}
16471658

1648-
dest.destructive_append(tmp_z);
1659+
// Don't add the `z` label at the end of the `if` when not needed.
1660+
if(!has_else || !then_branch_returns)
1661+
{
1662+
dest.destructive_append(tmp_z);
1663+
}
16491664
}
16501665

16511666
/// if(guard) goto target;

0 commit comments

Comments
 (0)