Next: , Previous: , Up: Optimizer Idiom Language   [Index]


C.6 OIL Loops

When writing idioms, sometimes instead of using very complicated expressions to try to match multiple situations at once it’s easier to have a separate idiom for each possible situation; for instance, it’s easier to write idioms for right-shift by 1, right-shift by 2, right-shift by 3, etc., rather than a general idiom to rightshift by any amount. When the idioms follow a pattern, as they will do in basically every case of this sort, it’s possible to automatically generate them using a loop. For instance, idioms to optimize a one-bit rightshift and a two-bit rightshift are:

(_1~#{xselx(x)<<1==x&&x}2)->((_1&_2)>>#1)
(_1~#{xselx(x)<<2==x&&x}2)->((_1&_2)>>#2)

Adding a loop to automatically generate the idioms, and placing a name for the group of idioms at the start, produces the following code:

[rshift]
<#1-#31
(_1~#{xselx(x)<<r==x&&x}2)->((_1&_2)>>#{r}0)
>

That’s 31 different idioms, generated with a loop. As the above example shows, a loop starts with <#NUMBER-#NUMBER and ends with >; a different idiom is generated for each possible value of the loop counter r in the range given by the opening line of the loop. Loops must be placed around idioms, but inside a group of idioms. Note the use of #{r}0 to generate a constant whose value is equal to the value of the loop counter.