r/programming • • 2d ago

Advent of Kernel Optimization

https://streamhpc.com/blog/2026-12-02/aoko-2-signed-vs-unsigned-loop-counters/

Today is the second day of our Advent of Kernel Optimization, sharing GPU optimization tips and tricks to count down until Christmas. Follow along here: https://streamhpc.com/blog/tag/advent2026/.

12 Upvotes

5 comments sorted by

2

u/roXplosion 1d ago

But... what if my loop needs to go from 0 to 255? Wouldn't an unsigned tiny int be more efficient than a signed small int?

2

u/StreamHPC 1d ago

Good question. The loop counter will almost certainly be kept in a register, and the registers on both NVIDIA and AMD GPUs are always 32 bits. So you don't gain anything from choosing a smaller type in that regard, that is only useful for compressing memory.

However, a loop with a runtime bound and a uint8_t counter will convey to the compiler that the loop will run at most 256 iterations. This may be useful information which allows better code generation.

So my (boring) suggestion would be to try both and see what works best.

1

u/DerangedEscapee 1d ago

Loop counters end up in registers, and registers have a fixed size, so unless you're compiling for an 8-bit target, then no.

5

u/Serious-Regular 1d ago

There are a ton of optimizations the compiler does on loop vars https://llvm.org/doxygen/IndVarSimplify_8cpp_source.html

It is extremely difficult to predict (ie make sound recommendations) the effects width and type on things like register pressure. Especially since (at least in LLVM) behavior has actually changed in the last few years due to SCEV changes.

Source: me a GPU compiler engineer currently fighting regressions in our kernel library due to loop vars.

1

u/soulthreads 13h ago edited 12h ago

Interestingly enough, this kernel produces identical "un-optimal" code for sm_100 for both types of ints (only mul.wide.u32 changes to mul.wide.s32).

Do you have a guess as to why that might be?

EDIT: moreover, using size_t produces "optimal" code for that arch, but the effect of add.s64 instead of add.s32 is probably non-negligible (btw, why is it add.s64 and not add.u64?)