|
|
8.1.7 'switch' Statements
|
SDCC can optimize switch statements to jump tables.
It makes the decision based on an estimate of the generated code size.
SDCC is quite liberal in the requirements for jump table generation:
- The labels need not be in order, and the starting number need not
be one or zero, the case labels are in numerical sequence or not too
many case labels are missing.
switch(i) { switch
(i) {
case 4: ... case
0: ...
case 5: ... case
1: ...
case 3: ...
case 6: ... case
3: ...
case 7: ... case
4: ...
case 8: ... case
5: ...
case 9: ... case
6: ...
case 10: ... case
7: ...
case 11: ... case
8: ...
} }
Both the above switch statements will be implemented using a jump-table.
The example to the right side is slightly more efficient as the check
for the lower boundary of the jump-table is not needed.
- The number of case labels is not larger than supported by the target
architecture.
- If the case labels are not in numerical sequence ('gaps' between cases)
SDCC checks whether a jump table with additionally inserted dummy
cases is still attractive.
- If the starting number is not zero and a check for the lower boundary
of the jump-table can thus be eliminated SDCC might insert dummy cases
0, ... .
Switch statements which have large gaps in the numeric sequence or
those that have too many case labels can be split into more than one
switch statement for efficient code generation, e.g.:
switch (i) {
case 1: ...
case 2: ...
case 3: ...
case 4: ...
case 5: ...
case 6: ...
case 7: ...
case 101: ...
case 102: ...
case 103: ...
case 104: ...
case 105: ...
case 106: ...
case 107: ...
}
If the above switch statement is broken down into two switch statements
switch (i) {
case 1: ...
case 2: ...
case 3: ...
case 4: ...
case 5: ...
case 6: ...
case 7: ...
}
and
switch (i) {
case 101: ...
case 102: ...
case 103: ...
case 104: ...
case 105: ...
case 106: ...
case 107: ...
}
then both the switch statements will be implemented using jump-tables
whereas the unmodified switch statement will not be.
The pragma nojtbound can be used to turn
off checking the jump table boundaries. It has
no effect if a default label is supplied. Use of this pragma is dangerous:
if the switch argument is not matched by
a case statement the processor will happily jump into Nirvana.
Next: 8.1.8 Bit-shifting Operations.
Up: 8.1 Optimizations
Previous: 8.1.6 Algebraic Simplifications
Contents
Index
2008-03-13
|