0% found this document useful (0 votes)
45 views34 pages

4 Branch Instructions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views34 pages

4 Branch Instructions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

COMPUTER

ORGANIZATION(PCO303C)

UNIT III
Register & Control Unit Organization
Topic: Program Control
Contents
• Introduction to Program Control
• Basic Control Structures in High-Level Languages
• Machine-Level Representation of Control
• Unconditional Branching
• Conditional Branching
• Subroutines and Function Calls
1. Program Control
Program Control is the mechanism that determines the sequence in which
instructions in a program are executed.
• At its core, programming is not just about performing computations but also
about controlling the order of these computations. This is where program control
comes into play.

• In almost all computational tasks, from simple arithmetic operations to complex


simulations, the sequence in which instructions are executed can significantly
influence the outcome.

• For instance, in a high-level language, evaluating a condition before printing a


message ensures that the message is printed only if the condition is met. The
order here is crucial.
• Imagine the importance of program control in a real-world scenario
like air traffic control.
• Deciding the order in which planes land is crucial for safety.
• Similarly, in a computer program, determining the sequence of
operations is vital for correctness, efficiency, and often, security.

The Role of the Program Counter (PC)


• The Program Counter (PC), sometimes called the Instruction Pointer
(IP), plays a pivotal role in program control at the hardware level.
• It is a register in the Central Processing Unit (CPU) that holds the
address of the next instruction to be executed.
How does the PC work? Sequential Execution:
• By default, after the execution of an instruction, the PC is incremented to
point to the next instruction in memory.
• This ensures that instructions are executed in sequence, one after the other.
Example:
Memory Address Value Comment
1000 ADD ; Add two numbers
1001 SUB ; Subtract two numbers
1002 MUL ; Multiply two numbers

If the PC starts at address 1000, it will increment to 1001 after the ADD
operation, then to 1002 after the SUB operation, ensuring sequential
execution of instructions.
Branching & Jumping:
• Sometimes, sequential execution is not desired, such as in loops or
conditional statements.
• In such cases, the PC's value can be changed arbitrarily, causing it to
"jump" to a different address.
Memory Address Value Comment
1000 CMP ; Compare two numbers
1001 JEQ 1004 ; Jump to address 1004 if numbers are equal
1002 ADD ; Add two numbers (executed if numbers are not equal)
1003 STOP ; End of program
1004 MUL ; Multiply two numbers (executed if numbers are equal)

Here, depending on the result of the CMP instruction, the PC might


jump from 1001 to 1004, skipping the ADD instruction.
Function Calls & Returns:
• During a function or subroutine call, the PC is set to the address
where the function starts.
• Once the function completes, the PC is restored to the point after
where the function was called, ensuring the main program resumes
execution.
Memory Address Value Comment
• 1000 CALL 1003; Call the function at address 1003
• 1001 ADD ; Add two numbers (executed after function returns)
• 1002 STOP ; End of program
• 1003 SUB ; Subtract two numbers (part of the function)
• 1004 RET ; Return from function
2. Basic Control Structures in High-Level
Languages
Control structures determine the flow of execution in a program. High-
level programming languages provide various constructs to allow more
intuitive, human-readable ways of dictating this flow.
Here are the basic control structures:
Sequence: This is the default control structure where statements in a
program are executed sequentially, one after the other, in the order
they appear.
Example:
print("This is the first statement.")
print("This is the second statement.")
Selection (or Conditional): This refers to making a decision in the code
based on evaluating certain conditions.
a. If-Else: Allows for conditional execution of code blocks. If the
condition is true, the code within the if block executes. If it's false,
and there is an accompanying else block, then the else block
executes.
Example:
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
b. Switch-Case: Allows a variable to be tested for equality against multiple cases. Each case has a block of code
associated with it that will be executed if the case matches.
Example:
int day = 3;
switch(day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
default:
printf("Another day");
}
Iteration (or Looping):
• This involves executing a block of code multiple times based on a
condition or a set number of times.
a. While: A loop that will continue executing as long as its condition is
true.
Example:
count = 1
while count <= 3:
print(f"Count is: {count}")
count += 1
b. For: Often used to iterate over a sequence (like a list or a range) or to repeat a
block of code a fixed number of times.
Example:
for i in range(3):
print(f"Value of i: {i}")
c. Do-While: Similar to the while loop but evaluates its condition at the end,
ensuring the loop body executes at least once.
Example:
int count = 1;
do {
printf("Count is: %d\n", count);
count++;
} while (count <= 3);
3. Machine-Level
Representation of Control
• At a high level, programming languages provide us with intuitive
constructs such as if-else, loops, and function calls.
• However, when it comes to execution, a computer does not directly
understand these high-level constructs.
• Instead, it understands a set of instructions written in machine code
or assembly language.
• How do we translate these high-level constructs to a form that the
machine can understand and execute??
How High-Level Control Structures Are Translated to Machine Code??
1. Conditional Statements (like If-Else):
High-level example:
if (a > b) {
// Do something
} else {
// Do something else
}
Machine-Level Representation (simplified pseudo-assembly code):

COMPARE a, b ; Compare 'a' and 'b'


JLE ElseLabel ; If 'a' is less than or equal to 'b', jump to 'ElseLabel'
... ; Code for "Do something"
JUMP EndIfLabel ; Jump to the end of the conditional block
ElseLabel:
... ; Code for "Do something else"
EndIfLabel:
2. Loops (like For and While):
High-level example (for loop):
for (int i = 0; i < 3; i++) {
// Repeat something
}
Machine-Level Representation (simplified pseudo-assembly code):
MOV i, 0 ; Initialize 'i' to 0
StartLoop:
COMPARE i, 3 ; Compare 'i' with 3
JGE EndLoop ; If 'i' is greater than or equal to 3, jump to 'EndLoop'
... ; Code to "Repeat something"
ADD i, 1 ; Increment 'i'
JUMP StartLoop ; Jump back to the start of the loop
EndLoop:
The Concept of Branching and Jumps
• Branching and jumps are fundamental in machine-level control.
• They provide a way to alter the flow of execution by changing the
next instruction to be executed.
Branching: It is a mechanism to conditionally change the flow of
execution based on the evaluation of certain conditions.
• For instance, after a comparison instruction, the processor sets or
clears specific "condition flags" in a special register.
• Branching instructions, like JLE (Jump if Less or Equal) or JGE (Jump if
Greater or Equal), inspect these flags and decide whether to jump to
a new address or continue sequentially.
• Jumps: These are similar to branching but are often unconditional.
They simply instruct the CPU to jump to a different address in the
instruction sequence, no matter what. A JUMP or JMP instruction is
used for this purpose.

• Program Counter (PC): The PC is a crucial component here. It typically


points to the next instruction to be executed.
• When a branching or jump instruction is encountered, the PC is
updated to point to the target address of the branch or jump.
• If the branch condition is not met, the PC is simply incremented to the
next instruction in sequence.
Example: JMP
High-Level Language Example
print("Before the jump")
goto jump_destination # Note: Python doesn't have a native 'goto', this is for illustrative purposes
print("This won't be printed")
jump_destination:
print("After the jump")

Pseudo-Assembly Representation:

PRINT "Before the jump"


JMP JumpDestination
PRINT "This won't be printed"
JumpDestination:
PRINT "After the jump"

• In the above pseudo-assembly, the JMP JumpDestination instruction means the flow of execution
will skip the next PRINT instruction and jump straight to the label JumpDestination.
Example:PC Initial State
• PC = Address of the first instruction
PRINT "Before the jump" <-- PC is here
JMP JumpDestination
PRINT "This won't be printed"
JumpDestination:
PRINT "After the jump“

After the first instruction executes:


PC = Address of the second instruction (due to default increment)

PRINT "Before the jump"


JMP JumpDestination <-- PC is here
PRINT "This won't be printed"
JumpDestination:
PRINT "After the jump"
After the JMP instruction:
PC = Address of the instruction labeled JumpDestination (because of the JMP)

PRINT "Before the jump"


JMP JumpDestination
PRINT "This won't be printed"
JumpDestination:
PRINT "After the jump" <-- PC is here

• So, the PC started at the top, incremented by one to move to the JMP instruction, and then due
to the JMP, it jumped to the address labeled JumpDestination, skipping over the next PRINT.
4. Unconditional Branching
• Its primary purpose is to divert the normal flow of execution to a different part of the program without checking any
condition.
Unconditional Branching with Examples:
1. Basic Jump in Assembly:
• In assembly, the straightforward unconditional jump is often represented by the JMP instruction.
JMP loopStart

; This section will be skipped


MOV AX, 10
loopStart:
MOV BX, 5
; ... other instructions ...
• In this example, execution jumps directly to the loopStart label, skipping the MOV AX, 10 instruction.
2. Using GOTO in High-Level Languages:
• Languages like C, C++, and Fortran support the goto statement.
#include <stdio.h>

int main() {
printf("Start\n");
goto end;
printf("Middle\n"); // This line will be skipped
end:
printf("End\n");
return 0;
}
• When executed, this program will print:
Start
End
3. Jump Tables in Assembly:
• Unconditional jumps are often used in jump tables, which are efficient ways to implement switch-case
structures in low-level code.
MOV AX, [userChoice] ; Let's assume userChoice is 2
JMP [jumpTable + AX*4]
jumpTable:
DW option1
DW option2
DW option3
option1:
; ... Code for option 1 ...
RET
option2:
; ... Code for option 2 ...
RET
option3:
; ... Code for option 3 ...
RET
• In this scenario, based on the value of userChoice, the program jumps to the appropriate label.
4. Looping with Unconditional Branching:

• Loops can be implemented using unconditional jumps.

MOV CX, 5

loopStart:
; ... loop body ...
DEC CX
; At this point, CX is decremented.

TEST CX, CX ; This sets the ZF (zero flag) if CX is 0, and clears it otherwise.
JZ endOfLoop ; Jump to endOfLoop if CX is zero (i.e., if ZF is set).

JMP loopStart ; This is the unconditional jump. If we reach this point, we will always jump back to loopStart.

endOfLoop:
; Rest of the program or function.
5. Early Function Exit in High-Level Languages:

• Unconditional branching can be used to exit functions early when certain


conditions are met, using constructs like return, break, or continue.

void printNumber(int num) {


if (num < 0) {
printf("Negative numbers not allowed!\n");
return; // Unconditional exit from function
}
printf("Number: %d\n", num);
}
6. Reset or Error Handlers in Embedded Systems:

• In embedded systems programming, it's common to have a reset routine that is jumped to
unconditionally upon certain error conditions or watchdog timer events.
; Some operation
CMP AX, BX
JE resetRoutine

; ... Other operations ...

resetRoutine:
; ... Reset the system ...
The code compares AX and BX.
• If they are equal, the program jumps to resetRoutine.
• If they are not equal, the program continues with the next operations.
• The resetRoutine is a set of operations to reset or recover the system, executed only if AX
equals BX.
5. Conditional Branching
• Making a decision in code to execute a certain block of statements
based on a condition.
• Comparison with Unconditional Branching: Unlike unconditional
jumps, which always divert the flow of execution to a specific point,
conditional jumps depend on a certain condition being true or false.
I. Basic Comparison Instructions:
CMP (Compare):
• The CMP instruction is used to compare two operands.
• It works by performing a subtraction between the operands but
doesn't save the result; instead, it modifies the flags based on the
result of the subtraction.
Flags Affected:
• Zero Flag (ZF): Set if the result is zero.
• Sign Flag (SF): Set if the result is negative. Using these flags, one could take
• Overflow Flag (OF): Set if there was an overflow. decisions like:
• Carry Flag (CF): Set if there was a carry (for
unsigned numbers).
Example: • JG AX_is_greater ; Jumps to the
MOV AX, 10 label if AX > BX
MOV BX, 5
CMP AX, BX ; Here AX - BX is 5, but the result isn't
stored.
; Only flags are set based on the outcome.

After the CMP:


• ZF will be 0 (because the result is not zero).
• SF will be 0 (because the result is positive).
• CF and OF will also be 0 (no carry or overflow).
 TEST (Bitwise Test):
Here's a practical usage of TEST:
• The TEST instruction is a bitwise AND operation between
• If you want to check if a specific bit is set, you can use the
two operands. Like CMP, it doesn't store the result; it just
affects the flags based on the outcome of the AND TEST instruction:
operation.
Flags Affected: MOV AX, 0008h ; Binary: 0000 0000 1000
• Zero Flag (ZF): Set if the result of the AND operation is TEST AX, 0008h ; Testing if the 4th bit (from the right) is set.
zero.
JZ Bit_is_clear ; If Zero Flag is set, it means the bit was not
• Sign Flag (SF): Set if the most significant bit of the result is set.
set (i.e., the result is negative for signed numbers).
• In the above, the jump to Bit_is_clear won't happen
Example: because the specific bit we're checking for is indeed set in
MOV AX, 0000h AX.

MOV BX, FFFFh


• Both CMP and TEST are crucial for decision-making in
TEST AX, BX ; This is essentially AND-ing AX with BX, but the
result is not stored. assembly. They provide ways to inspect values and bits
without altering the original data, allowing for conditional
After the TEST: branching based on the outcome.
• ZF will be 1 (because the result is zero).
• SF will be 0 (because the most significant bit of the result
is not set).
II. Flag Registers:
• The Flag Register in x86 architectures is a special register that holds the flags, which are individual
bits representing specific outcomes from various operations.
• These flags are pivotal for conditional branching since they allow the program to make decisions
based on the results of previous computations.

 Zero Flag (ZF):


Purpose: Indicates if the result of an operation is zero.
Set When: The result is zero.
Cleared When: The result is non-zero.
Example:
SUB AX, AX
; ZF will be set because AX - AX = 0
Sign Flag (SF): Overflow Flag (OF):

• Purpose: Reflects the sign of a • Purpose: Indicates an overflow in signed


arithmetic operations.
result.
• Set When: The result of a signed
• Set When: The most significant operation is too large (positive overflow)
bit (MSB) of the result is 1 or too small (negative overflow) to fit in
(indicating a negative number in the destination operand.
two's complement form). Example:
MOV AX, 7FFFh: This instruction loads
• Cleared When: The MSB is 0 7FFFh, the maximum positive 16-bit signed
(indicating a positive number). integer, into AX.
Example: ADD AX, 1: Adding 1 to 7FFFh results in
8000h, which is outside the range for 16-
MOV AX, -1 bit signed integers.
; SF will be set because -1 is Since this result causes a positive overflow,
negative. the Overflow Flag (OF) will be set.
 Carry Flag (CF):  Parity Flag (PF):
• Purpose: Indicates if the number of set bits in
• Purpose: Represents carry in the least significant byte of the result is even
addition or borrow in subtraction or odd.
for unsigned arithmetic. • Set When: The number of set bits in the LSB
is even.
• Set When: A carry out of the most
• Cleared When: The number of set bits in the
significant bit occurs in addition LSB is odd.
or a borrow in subtraction. Instruction: MOV AL, 3
Example: This instruction moves the value 3 into the AL
register.
MOV AX, FFFFh Binary Representation: The binary equivalent
ADD AX, 1 of 3 is 0000 0011, which contains 2 set bits (1s).
Result: Since there are an even number of set
; CF will be set due to carry. bits, the Parity Flag (PF) will be set.
Auxiliary Flag (AF):
• Purpose: Used in Binary Coded Decimal (BCD) arithmetic. It indicates
a carry or borrow in the least significant nibble (4 bits).
• Set When: There's a carry from or borrow to the 4th bit during
arithmetic operations.
Example:
MOV AL, 9
ADD AL, 2
; AF will be set if there is carry from the 4th bit.
III. . Conditional Jump Instructions:

You might also like