llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

LoopVectorize: SCEV overflow runtime check prevents vectorization of narrow induction with cast chain

Open kartcq opened this issue 2 months ago • 1 comments

The loop vectorizer emits a SCEV wrap predicate runtime check for narrow induction variables widened by the frontend via integer promotion. The check prevents vectorization when the trip count exceeds the narrow type's overflow point, even though all uses truncate the result back to the narrow type.

Reproducer

#include <stdint.h>
void f(int n, int8_t *restrict a, int8_t *restrict b) {
    int8_t s = 0;
    for (int i = 0; i < n; i++) {
        s    = s + 2;
        a[i] = s * b[i];
    }
}

clang -O2 -emit-llvm -S repro.c -o -

Godbolt Link : https://godbolt.org/z/ad9fvvd77

The vectorizer emits a runtime check equivalent to n < 65. For n >= 65 the vector loop is never executed.

Analysis

The frontend promotes the i8 PHI to i32 with shl 24 / ashr 24 to simulate truncation. SCEV's createAddRecFromPHIWithCasts models this as {0, +, 2}_i32 under a wrap predicate requiring {0, +, 2}_i8 not to overflow. This predicate can be safely dropped when all consumers of the wide induction truncate it back to i8 before use. The predicate is needed when the wide value is consumed directly (e.g., as a live-out or pointer index).

kartcq avatar Oct 04 '26 07:10 kartcq

I have shared a fix for this. Any feedback on the approach or direction would be appreciated. Thanks.

kartcq avatar Oct 04 '26 13:10 kartcq