[EXT_EP-9681] Compiler incorrectly optimizes unsigned loop counter which wraps around Created: 20/Feb/20  Updated: 24/Apr/20  Resolved: 01/Apr/20

Status: Fixed
Project: Embedded Software & Tools
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Medium
Reporter: TI User Assignee: TI User
Resolution: Fixed Votes: 0
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Product: Code Generation Tools
Internal ID: CODEGEN-7227
Forum URL: https://e2e.ti.com/support/tools/ccs/f/81/t/882077
Found In Release: C6000_8.2.0
C2000_18.1.0.LTS
C6000_8.3.0
MSP430_20.2.0.LTS
C7000_1.4.0.LTS*
ARM_18.12.0.LTS
PRU_2.3.0
ARP32_1.1.0*
ARM_20.2.0.LTS
C2000_20.2.0.LTS
ARM_18.1.0.LTS
MSP430_18.1.0.LTS
PRU_2.4.0*
MSP430_18.12.0.LTS
C2000_18.12.0.LTS
Fix In Release: ARM_18.12.6.LTS*
C7000_1.4.0.LTS*
MSP430_18.1.8.LTS
C6000_8.3.7*
ARP32_1.1.0*
MSP430_20.2.1.LTS
ARM_20.2.1.LTS
C2000_18.12.6.LTS*
PRU_2.4.0*
ARM_18.1.8.LTS
MSP430_18.12.6.LTS*
C2000_18.1.8.LTS
PRU_2.3.4*
C6000_8.2.9
C2000_20.2.1.LTS
Affected Platform/Device: default
Workaround: Avoid writing a do-while loop in which the loop variable wraps around on the first iteration. For instance, use a signed loop variable or a while-loop.
Release Notes: A do-while loop which uses an unsigned loop variable that wraps around on the first iteration (for example, initialised to (unsigned)-1 and incremented before the first end-test) may confuse the compiler into removing the entire loop. It may interpret the -1 as a large constant that is already past the loop's end value, and fold the loop away.

 Description   

The attached file contains an implementation of strnlen.

size_t strnlen_wtf(const char *s, size_t maxlen)
{
    size_t n = (size_t)-1;

    do n++; while ( (*s++)  &&  (n < maxlen) );
    return n;
}

Build it ...

% cl2000 -o2 -s try1.c

Inspect the resulting assembly to see that it is optimized into a function that always returns the value 0.

Please see the associated forum thread for more context.


Generated at Sat Dec 13 11:31:01 CST 2025 using Jira 10.3.7#10030007-sha1:a563685562f94d165eb4e158cfb2a142338d8c54.