Thursday, 19 January 2017

Basics of conditional branching (b)

Conditional branches are a lot more flexible than unconditional branches, but it comes at a cost of branchable distance. Conditional branches use the B-Form instruction format:

The B-Form instruction format

Bits 0-5
Opcode
Bits 6-10
Specifies the options used regarding how the bit is tested, whether and how the counter register is involved, and any branch prediction hints (called the BO field)
Bits 11-15
Specifies the bit in the condition register to test (called the BI field)
Bits 16-29
Absolute or Relative Address
Bit 30
Addressing Mode -- when set to 0 the specified address is considered a relative address; when set to 1 the address is considered an absolute address
Bit 31
Link Bit -- when set to 1 the link register is set to the address following the current instruction; when set to 0 the link register is not set
As you an see, a full 10 bits are used to specify the branch mode and condition, which limits the address size to only 14 bits (only a 16K range). This is usable for small jumps within a function, but not much else. To conditionally call a function outside of this 16K range, the code would need to do a conditional branch to an instruction containing an unconditional branch to the right location.
The basic forms of the conditional branch look like this:
bc BO, BI, address
bcl BO, BI, address
bca BO, BI, address
bcla BO, BI, address

In this basic form, BO and BI are numbers. Thankfully, we don't have to memorize all the numbers and what they mean. The extended mnemonics (described in the first article) of the PowerPC instruction set come to the rescue again, and we can avoid having to memorize all of the field numbers. Like unconditional branches, appending an l to the instruction name sets the link register and appending an a makes the instruction use absolute addressing instead of relative addressing.
For a simple compare and branch if equal, the basic form (not using the extended mnemonics) looks like this:
Listing 4. Basic form of the conditional branch
#compare register 4 and 5
cmpd 4, 5
#branch if they are equal
bc 12, 2 address
bc stands for "branch conditionally." The 12 (the BO operand) means to branch if the given condition register field is set, with no branch prediction hint, and 2 (the BI operand) is the bit of the condition register to test (it is the equal bit). Now, very few people, especially beginners, are going to be able to remember all of the branch code numbers and condition register bit numbers, nor would it be useful. The extended mnemonics make the code clearer for reading, writing, and debugging.

No comments:

Post a Comment