Sunteți pe pagina 1din 5

The B<cc> (Branch) instruction is used to change the

control flow by adding an offset to the current


Program Counter.
The offset is a signed number, allowing forward and
backward branches of up to 32MB..
The Branch instruction can be used in two ways,
conditionally and unconditionally. An unconditional
branch will always branch no matter what the state
of the flags, conventionally this is written as BAL
(Branch Always). For a conditional branch, one of the
condition codes is given immediately after the B.
Thus the BEQ instruction is used to branch on equal
condition (the Z flag is set).
There is also the BL<cc> (Branch and Link)
instruction which preserves the address of the
instruction immediately after the branch in the Link
Register (LR or R14). This allows for a subroutine
Branch Instructions.

The branch instructions cause the processor to


execute instructions from a different address.
Two branch instruction are available - b and bl.
The bl instruction in addition to branching, also
stores the return
address in the lr register, and hence can be used for
sub-routine
invocation. The instruction syntax is given below.
b label ; pc = label bl label ; pc = label, lr = addr of
next instruction
To return from the subroutine, the mov instruction
can be used as shown below.
mov pc, lr
Branch Instructions: A branch instruction
changes the normal flow of execution of a main
program or is used to call a subroutine routine.
This type of instruction allows programs to have
subroutines, if-then-else structures, and loops. The
change of execution flow forces the program
counter pc to point to a new address.
Example 1: B forward ;
(unconditional branch to forward)
ADD r1, r2, #4 ;
ADD r0, r6, #2 ;
ADD r3, r7, #4 ;
forward SUB r1, r2, #4 ;
Similarly Backward branch :
backward : ADD r1, r2,
#4 ;
SUB r1, r2,
#4 ;
B : Branch
B<suffix> <address> B is the simplest branch. Upon
encountering a B instruction, the ARM processor will
jump immediately to the address given, and resume
execution from there.
Note that the actual value stored in the branch
instruction is an offset from the current value of R15;
rather than an absolute address.
On the ARM processor, that would become
something like:
OPT 1 OPT 2
ADR R1, #&70 ADR R1, #&70
LDR R0, [R1] LDR R0, [R1]
CMP r0, #0 CMP R0, #0
BEQ Zero STRNE R0, [R1, #2]
STR R0, [R1, #2] MOV PC, R14
.Zero
MOV PC, R14
The branch with link, or BL, instruction is similar to
the B instruction but overwrites the link register lr
with a return address. It performs a subroutine call.
BL subroutine ; branch to
subroutine
CMP r1, #5 ; compare r1
with 5
MOVEQ r1, #0 ; if (r1==5) then
r1 = 0 :
Subroutine
MOV pc, lr ; return by moving pc
= lr
The Branch Exchange (BX) and Branch Exchange
with Link (BLX) are the third type of branch
instruction.
The BX instruction uses an absolute address stored
in register Rm. It is primarily used to branch to and
from Thumb code.

S-ar putea să vă placă și