src/loops.h
/* Specialize a counted loop with one side-effect-free accumulator update.
Keep the original instructions for the AOT backend and as operand storage. */
static void specialize_loops(void) {
for (int j = 0; j < ncode - 3; j++) {
Ins *test = &code[j];
Ins update = code[j+1], step = code[j+2], back = code[j+3];
if (test->op != BR_LT_FALSE || test->target != j+4 ||
back.op != JUMP || back.target != j) continue;
int index = test->a, limit = test->b, acc = update.dst;
if (step.op != ADD || step.dst != index || step.a != index ||
slots[step.b].initial != 1) continue; /* only literals start nonzero */
if (update.op != ADD && update.op != SUB &&
update.op != MUL && update.op != MADD) continue;
if (acc == index || acc == limit || update.a != acc ||
update.b == acc || (update.b == index && update.op != ADD && update.op != SUB)) continue;
if (update.op == MADD && (update.c == acc || update.c == index)) continue;
test->op = COUNT_AFFINE;
}
}
static inline void execute_counted(const Ins *test, Word *r) {
Word first = r[test->a], limit = r[test->b];
if (!signed_less(first, limit)) return;
const Ins *u = test + 1;
if (u->b==test->a) {
Word sum=index_sum(first,limit-first);
r[u->dst]+=u->op==SUB ? 0-sum : sum;
r[test->a]=limit;
return;
}
Word factor = 1, bias = 0;
switch (u->op) {
case ADD: bias = r[u->b]; break;
case SUB: bias = 0 - r[u->b]; break;
case MUL: factor = r[u->b]; break;
case MADD: factor = r[u->b]; bias = r[u->c]; break;
default: abort();
}
r[u->dst] = affine_advance(r[u->dst],limit-first,factor,bias);
r[test->a] = limit;
}