Conditional Branches What distinguishes a computer from a simple calculator is its ability to make decisions Decisions are made using the if statement, sometimes combined with “go to” statements and “labels”. MIPS assembly language includes many decision-making instructions. Two of them are BEQ and BNE.
Branch on Equal if ($u == $v) then jump to “Label” beq u,v,Label if the bit patterns in register $u == register $v PC <-- address of Label after a delay of one machine cycle. else Continue the sequence of instructions without jumping. bit patterns – unsigned or two’s complement ?
“If” structure IF $8 equals to $9 then go to CONT. Otherwise do the block of statements Then again go through the CONT
“If” structure on assembly The bit patterns in two registers are compared. If the bit patterns are the same, the PC is changed to the branch address. There is a branch delay following the instruction (just as for a jump instruction). ... # load values into $8 and $9 beq $8,$9,cont # branch if equal sll $0,$0,0 # branch delay slot ... # conditionally ... # executed ... # statements cont: add $10,$10,$11 # always executed
? Two – way decision ... # load values into # $8 and $9 beq $8,$9,equal # branch if equal sll $0,$0,0 # branch delay slot ... # ... # false branch j cont equal: ... # ... # true branch cont: add $10,$10,$11 # always executed ?
Branch on Not Equal if ($u != $v) then jump to “Label” bne u, v, Label if register $u != register $v PC <-- address of Label after a delay of one machine cycle. else Continue the sequence of instructions without jumping.
Absolute Value calculation # Get A lui $10,0x1000 # base register lw $8,0($10) # Load A sll $0,$0,0 # no-op # Is A Negative? srl $9,$8,31 # Shift sign bit beq $0,$9,done # sign bit == zero # Store –A sub $8,$0,$8 # negate A sw $8,0($10) # save it done: sll $0,$0,0 # target of the branch .data A: .word -1
BEQ instruction format beq $0, $9, done beq $0 $9 0 0 0 3 opcode oprnd dest offset(2’s comp.) 000100 00000 01001 0000 0000 0000 0011 0001 0000 0000 1001 0000 0000 0000 0011 1 0 0 9 0 0 0 3 New PC = PC + Off*4 = 0x00400010+4 + 0x0003*4 = 0x00400014 + 0x0000000C = 0x00400020 [0x00400000] 0x3c0a1000 lui $10, 4096 [0x00400004] 0x8d480000 lw $8, 0($10) [0x00400008] 0x00000000 nop [0x0040000c] 0x00084fc2 srl $9, $8, 31 PC+4 [0x00400010] 0x10090003 beq $0,$9,12 [done-0x00400010] [0x00400014] 0x00000000 nop +12 [0x00400018] 0x00084022 sub $8, $0, $8 [0x0040001c] 0xad480000 sw $8, 0($10) done:[0x00400020] 0x00000000 nop
Addressing Modes 4. BEQ and BNE use PC-relative addressing, where the branch address is the sum of the PC and a constant in the instruction Addressing mode – One of several addressing regimes delimited by their varied use of operands and or addresses.