Skip to content

Failure to unroll loop with unknown but small countΒ #116119

@Kmeakin

Description

@Kmeakin

Consider this function that calculates the number of digits in n's base-10 representation (eg as part of a formatting library):

u8 src(u8 n) {
    u8 num_digits = 0;
    do {
        num_digits++;
        n /= 10;
    } while (n != 0);
    return num_digits;
}

Since n is in the range 0-255, the loop will run exactly 1, 2 or 3 times, and the function can be optimized by unrolling the loop manually:

u8 intermediate(u8 n) {
    u8 num_digits = 0;

    // iteration 1
    num_digits++;
    n /= 10;
    if (n == 0) return num_digits;

    // iteration 2
    num_digits++;
    n /= 10;
    if (n == 0) return num_digits;

    // iteration 3
    num_digits++;
    n /= 10;

    return num_digits;
}

which then simplifies to:

u8 tgt(u8 n) {
    if (n < 10) return 1;
    if (n < 100) return 2;
    return 3;
}

LLVM is smart enough to do this optimization if the base is 16, but not for any other base

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions