Issue 243464
Summary [llvm-cov] Ghost line coverage and phantom branch counters generated for unchosen alternatives of __builtin_choose_expr
Labels new issue
Assignees
Reporter Durgesh-Shelke
    ### Summary

In GNU C, `__builtin_choose_expr(const_exp, exp1, exp2)` is a compile-time selection construct heavily used in system headers, the Linux kernel, and type-generic macros. Only the chosen _expression_ is evaluated and emitted into machine code; the unchosen alternative is completely discarded at compile time.

In Clang CodeGen (`clang/lib/CodeGen/CGExprScalar.cpp`), Clang correctly visits only the chosen _expression_:
    
    Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
      return Visit(E->getChosenSubExpr());
    }

However, in Clang's source-based coverage pipeline (clang/lib/CodeGen/CoverageMappingGen.cpp), CounterCoverageMappingBuilder does not implement VisitChooseExpr. It falls back to ConstStmtVisitor::VisitStmt, which naively traverses all children (the condition, exp1, and exp2).

This causes two severe accuracy defects:

  1. Ghost Line Coverage: Multi-line expressions in the unchosen alternative (e.g., statements or printf calls) inherit the outer region and are reported by llvm-cov as 100% executed with count 1, despite producing zero machine instructions and never executing.
  2. Phantom Branch Generation: If the unchosen alternative contains any branching construct (e.g., a ternary x > 0 ? 100 : 200 or logical operators && / ||), CounterCoverageMappingBuilder allocates runtime counter #1 and records branch coverage. Because CodeGen emits zero instructions for the discarded branch, counter #1 remains 0 at runtime.

Consequently, llvm-cov reports:
    Branch: [True: 0, False: 1]
  falsely claiming that a non-existent runtime branch was evaluated, missed True, and taken False.
  ──────

### Minimal Standalone Reproducer (test_choose_expr_ghost.c)
    #include <stdio.h>

    int test_choose(int x) {
        int res = __builtin_choose_expr(
            1,
            x + 10,
            (
                printf("Unchosen ghost printf!\n"),
                x > 0 ? x * 100 : x * 200
            )
        );
        return res;
    }

    int main(void) {
        test_choose(5);
        return 0;
    }
  ──────
### Steps to Reproduce
    # Compile with Clang source coverage instrumentation
    clang-16 -O0 -g -fprofile-instr-generate -fcoverage-mapping test_choose_expr_ghost.c -o test_choose_expr_ghost
    LLVM_PROFILE_FILE="test_choose_expr_ghost.profraw" ./test_choose_expr_ghost
    llvm-profdata-16 merge -sparse test_choose_expr_ghost.profraw -o test_choose_expr_ghost.profdata

    # View coverage and branch decisions
    llvm-cov-16 show ./test_choose_expr_ghost -instr-profile="" -show-branches=count test_choose_expr_ghost.c

    # Inspect AST coverage mapping dump
    clang-16 -O0 -fprofile-instr-generate -fcoverage-mapping -Xclang -dump-coverage-mapping -c test_choose_expr_ghost.c
  ──────
### Observed Output
  #### 1. llvm-cov show Output:
       11|      1|int test_choose(int x) {
       12|      1|    int res = __builtin_choose_expr(
       13|      1|        1,
       14|      1|        x + 10,
       15|      1|        (
       16|      1|            printf("Unchosen ghost printf!\n"),
       17|      1|            x > 0 ? x * 100 : x * 200
      ------------------
      |  Branch (17:13): [True: 0, False: 1]
      ------------------
       18|      1|        )
       19|      1|    );
       20|      1|    return res;
       21|      1|}

  • Ghost Line Coverage: Line 16 (printf) is marked as executed 1 time, but strings confirms the string is completely absent from the binary.
  • Phantom Branch: Line 17 synthesizes [True: 0, False: 1] for uncompiled code.
  #### 2. Disassembly (objdump -d):
    00000000000023b0 <test_choose>:
        23b0: push   rbp
        23b1: mov    rbp,rsp
        23b4: mov    DWORD PTR [rbp-0x4],edi
        23b7: mov    rax,QWORD PTR [rip+0x8dea]        # increment __profc_test_choose[0]
        23be: add    rax,0x1
        23c2: mov    QWORD PTR [rip+0x8ddf],rax
        23c9: mov    eax,DWORD PTR [rbp-0x4]
        23cc: add    eax,0xa                           # x + 10
        23cf: mov    DWORD PTR [rbp-0x8],eax
        23d2: mov    eax,DWORD PTR [rbp-0x8]
        23d5: pop    rbp
        23d6: ret

  Disassembly proves that zero branch instructions and zero instructions for the unchosen branch exist.

  #### 3. Clang Trunk Coverage Mapping Dump:
    test_choose:
      File 0, 11:24 -> 21:2 = #0
      File 0, 17:13 -> 17:18 = #0
      Branch,File 0, 17:13 -> 17:18 = #1, (#0 - #1)
      Gap,File 0, 17:20 -> 17:21 = #1
      File 0, 17:21 -> 17:28 = #1
      File 0, 17:31 -> 17:38 = (#0 - #1)
  ──────
### Comparison with GCC gcov

  GCC 11.4.0 and GCC 15.2.0 correctly report No branches and mark the unchosen _expression_ as uninstrumented (-:):
    File 'test_choose_expr_ghost.c'
    Lines executed:100.00% of 6
    No branches
    Calls executed:100.00% of 1

            1:   11:int test_choose(int x) {
            1:   12:    int res = __builtin_choose_expr(
            -:   13:        1,
            -:   14:        x + 10,
            -:   15:        (
            -:   16:            printf("Unchosen ghost printf!\n"),
            -:   17:            x > 0 ? x * 100 : x * 200
            -:   18:        )
            -:   19:    );
            1:   20:    return res;
            -:   21:}
  ──────
### Proposed Fix

  1. In clang/lib/CodeGen/CoverageMappingGen.cpp, implement VisitChooseExpr in CounterCoverageMappingBuilder:

    void VisitChooseExpr(const ChooseExpr *E) {
      if (E->isConditionDependent())
        return;

      extendRegion(E);

      const Expr *Chosen = E->getChosenSubExpr();
      const Expr *Unchosen = E->isConditionTrue() ? E->getRHS() : E->getLHS();

      // Mark the unchosen branch as skipped so it displays as uninstrumented
      if (Unchosen)
        markSkipped(getStart(Unchosen), getEnd(Unchosen));

      // Propagate coverage only through the chosen _expression_
      Visit(Chosen);
    }

  2. In clang/lib/CodeGen/CodeGenPGO.cpp, prevent MapRegionCounters from allocating unused counters for discarded subexpressions:

    bool TraverseChooseExpr(ChooseExpr *CE) {
      if (CE->isConditionDependent())
        return Base::TraverseChooseExpr(CE);
      return TraverseStmt(CE->getChosenSubExpr());
    }

  Tested on Clang 16.0.6 and verified persistent on Clang trunk (2026).
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to