CHAPTER 13. SWITCH()/CASE/DEFAULT CHAPTER 13. SWITCH()/CASE/DEFAULT
000001A0 04 00 00 EA B loc_1B8
000001A4
000001A4 two_case ; CODE XREF: f2+4
000001A4 ; f2:loc_188
000001A4 01 0C 8F E2 ADR R0, aTwo ; jumptable 00000178 case 2
000001A8 02 00 00 EA B loc_1B8
000001AC
000001AC three_case ; CODE XREF: f2+4
000001AC ; f2:loc_18C
000001AC 01 0C 8F E2 ADR R0, aThree ; jumptable 00000178 case 3
000001B0 00 00 00 EA B loc_1B8
000001B4
000001B4 four_case ; CODE XREF: f2+4
000001B4 ; f2:loc_190
000001B4 01 0C 8F E2 ADR R0, aFour ; jumptable 00000178 case 4
000001B8
000001B8 loc_1B8 ; CODE XREF: f2+24
000001B8 ; f2+2C
000001B8 66 18 00 EA B __2printf
000001BC
000001BC default_case ; CODE XREF: f2+4
000001BC ; f2+8
000001BC D4 00 8F E2 ADR R0, aSomethingUnkno ; jumptable 00000178 default case
000001C0 FC FF FF EA B loc_1B8
This code makes use of the ARM mode feature in which all instructions have a fixed size of 4 bytes.
Let’s keep in mind that the maximum value forais 4 and any greater value will cause«something unknown\n»string to be
printed.
The firstCMP R0, #5 instruction compares the input value ofawith 5.
The nextADDCC PC, PC, R0,LSL#2^5 instruction is being executed only ifR 0 < 5 (CC=Carry clear / Less than). Conse-
quently, ifADDCCdoes not trigger (it is aR 0 ≥ 5 case), a jump todefault_caselabel will occur.
But ifR 0 < 5 andADDCCtriggers, the following is to be happen:
The value inR0is multiplied by 4. In fact,LSL#2 at the instruction’s suffix stands for “shift left by 2 bits”. But as we will
see later (16.2.1 on page 204) in section “Shifts”, shift left by 2 bits is equivalent to multiplying by 4.
Then we addR 0 ∗ 4 to the current value inPC, thus jumping to one of theB(Branch) instructions located below.
At the moment of the execution ofADDCC, the value inPCis 8 bytes ahead (0x180) than the address at which theADDCC
instruction is located (0x178), or, in other words, 2 instructions ahead.
This is how the pipeline in ARM processors works: whenADDCCis executed, the processor at the moment is beginning to
process the instruction after the next one, so that is whyPCpoints there. This has to be memorized.
Ifa= 0, then is to be added to the value inPC, and the actual value of thePCwill be written intoPC(which is 8 bytes ahead)
and a jump to the labelloc_180will happen, which is 8 bytes ahead of the point where theADDCCinstruction is.
Ifa= 1, thenP C+ 8 +a∗4 =P C+ 8 + 1∗4 =P C+ 12 = 0x 184 will be written toPC, which is the address of theloc_184
label.
With every 1 added toa, the resultingPCis increased by 4. 4 is the instruction length in ARM mode and also, the length of
eachBinstruction, of which there are 5 in row.
Each of these fiveBinstructions passes control further, to what was programmed in theswitch(). Pointer loading of the
corresponding string occurs there,etc.
13.2.3 ARM: Optimizing Keil 6/2013 (Thumb mode)
Listing 13.7: Optimizing Keil 6/2013 (Thumb mode)
000000F6 EXPORT f2
000000F6 f2
000000F6 10 B5 PUSH {R4,LR}
(^5) ADD—addition