You are on page 1of 40

Control Flow

Subroutines
Program Stack
Exceptions
Topics
 Subroutines
 Jump to Subroutine (JSR)
 Return from Subroutine (RTS)
 The Processor Stack
 Role of the Stack in Subroutine Processing
 Stack Frame
 Exceptions
 Interrupts
 Traps
 Faults
 Aborts
Objectives:
 Describe how the order of execution of statements in a program is
affected by instructions that cause a change in the value of the
processor’s program counter
 Describe how a subroutine
 Describe how the stack is used to provide communication between a
subroutine and the calling environment
 Understand how exceptions are used to coordinate the operation of the
system
 Build a background for later discussion of
 Processor I/O
 Operating Systems
Control Flow
 As the processor of a computer executes instructions, the Program Counter
is updated to “point” to the next instruction that is to be fetched and
executed
 As each instruction is fetched the Program Counter is incremented to the
address of the immediately following instruction:
 [PC] ← [PC] + 1 /* 8 bit instruction */
 [PC] ← [PC] + 4 /* 32 bit instruction */

 This is the normal flow of control, or sequential flow


Branching
 An instruction that causes a branch will cause a change in the flow of
control (i.e. the normal sequential flow)
 Consider the following code (written in the style of an Accumulator ISA):

128 LOAD X ; Load accumulator with value from location X


129 L1: SUB #1 ; Subtract 1 from accumulator
130 BEQ L2 ; Branch to L2 if accumulator has 0
131 BRA L1 ; Branch to statement that is labelled L1
132 L2: STORE X ; Store accumulator to location

Address of each
8-bit instruction
Subroutines
 Another example of abrupt change In control flow is in the execution of
subroutines
 A subroutine is a group of instructions that performs some task
 Typically a task that is needed at several points in the execution of a program
 Concept that is used in HLLs:
 Functions in C
 Methods in Java
 similar structures in other languages
Subroutines
 A subroutine can be called from several places in a program
 This is accomplished by setting the program to the address of the first
instruction in the group of instructions that make up the subroutine.
 A subroutine is like a branch except that:
 Once the subroutine is completed, control must be returned to the statement
following the statement that called the subroutine
 A regular branch will not do in this case as the point to which control is not
always the same
 Also, a subroutine will typically need inputs (referred to as arguments, or
parameters)
e.g. int x = square(4);
Subroutines
 Most ISAs provide an instruction that is used to cause a branch to the first
instruction in a subroutine
 This transfer of control is termed a subroutine call
 For example, most ISAs provide an instruction that is named JSR (or something
similar) meaning Jump to Sub-Routine

 An instruction is also provided by which control can be returned to the


instruction immediately after the instruction that called the subroutine.
 Most languages provide an instruction that is named RTS (or something similar)
meaning Return from Sub-Routine
Subroutines

JSR SWAP1
1
MOVE D2, D3 How the Program Counter
4 … “moves” in a subroutine
…. call:
JSR SWAP2
3 ADD D3, D5
….
..
1. Subroutine call causes
Program Counter to be set to
2 first instruction in subroutine
SWAP1:
… 2. Subroutine code is executed
RTS
3. Program is restored to
SWAP2: ……. statement following the
……. statement that called the
RTS
subroutine
4. Execution in sequential
manner resumes
Subroutines
 There are several important points to note about subroutines:
 A subroutine will accept parameters, being values that are passed to the
subroutine from the calling environment
 A subroutine will often be expected to return a value, being the result of
the task carried out by the subroutine on the values that were passed as
parameters
 The subroutine must return control to the correct instruction in the
program. This is called the return address. This is critical since a
subroutine can be called from any point in the program.
 Most importantly mechanisms must be put in place to ensure that the
subroutine does not interfere with values that are in registers at the point of
the code where the subroutine call was made
 The ISA must provide mechanisms to ensure that these requirements are
met
Subroutines
 Must also take the following into
JSR SWAP1
consideration:
 Nested Sub-routine calls
SWAP1: …….
 Program calls subroutine A
JSR SWAP2
 Subroutine A calls subroutine B
……
RTS
SWAP2: …….
 Recursive Call RTS
 Subroutine A calls itself
JSR SWAP1

SWAP1: BEQ L2
JSR SWAP1
L2: ……
RTS
Subroutines
 The task of establishing communication with a subroutine is called subroutine
linkage.
 The methods that are used to accomplish subroutine linkage will vary across
different ISAs
 In some processors a special register, a link register, is used to store the
return address
 Cannot be used with nested subroutine calls as the return address in register will be
overwritten by the nested call
 Can also use an area of memory to store return address and parameters
 One approach is to store return address in first instruction of sub-routine
 Processor inserts address when subroutine is called
 Also not good for nested sub-routine calls (especially recursive calls)
The Program(Runtime) Stack
 Most processors use a stack to provide Address: 0
mechanisms for subroutine call and
return. Program
Instructions
 The Stack is an area of a program’s
address space that grows and shrinks as
the program runs.
Variable
 Usually high addresses of program space and
 Entries are added to the stack when a Constants
subroutine is called
Stack Program Stack
 When the subroutine returns the entries
grows each Is empty when
that were saved on the stack are
removed time a the program
subroutine starts
is called up
The Program Stack

 The set of entries that are pushed onto the stack for an invocation of a
subroutine is called a stack frame.
 Consider the following example:
MAIN: JSR SWAP1
.
.

SWaP1: ….
JSR SWAP2
….
RTS

SWAP2: …..
…..
RTS
The Program Stack
 Control flow is described as shown below:
MAIN: JSR SWAP1
.
.

SWAP1: ….
JSR SWAP2
….
RTS

SWAP2: …..
…..
RTS
The Program Stack

Stack
frame for
call to
SWAP2
Stack Stack Stack
frame for frame for frame for
call to call to call to
SWAP1 SWAP1 SWAP1

0. Initially 1. After 2. After 3. After 4. After SWAP1


call to call to SWAP2 has has returned
SWAP1 SWAP2 returned
Subroutines

 The use of a stack for subroutine call and return has several advantages
over other approaches:
 A subroutine can call another subroutine (nesting). The calling subroutine saves
its local variables, return addresses, and return address on the stack to be
restored when the called subroutine returns.
 A subroutine can call itself (recursion). Each call saves its local variables on the
stack to be restored when the call returns.
Stack Overflow
 A stack overflow occurs when the stack area of a program grows so large
that it meets the area which is used for variables and constants.
 This error usually results from:
 The stack area being too small
 A high number of subroutine calls that are stacked one upon the other.
 This would be the case where recursion is used without a base case
 Subroutines are being passed a large number of parameters
 Other conditions can lead to stack overflow but these are the most common.
Exceptions

• An exception is an abrupt change in the control flow in


response to some change in the processor’s state.
• Exceptions are partly implemented in hardware and
partly in software
• For this reason, the exact manner of implementation of
exceptions will differ across systems.
• However, there are some general principles that hold
regardless of implementation
Exceptions
• Events that give rise to exceptions occur at all levels of a
computer system
• Hardware
• Operating System
• Application Program Level

• Examples of some events:


• A device needs the processor’s attention
• Data arrives from a network and must be stored in memory
• A process needs to execute a task that it is not normally allowed to
execute
• An illegal memory address is specified by a program
• And there are quite a few others
Exceptions
• Exceptions must be handled when they occur
• As an example:
• The process is executing the current instruction when a
change in the processor’s state is detected (e.g. an arithmetic
overflow)

• The processor responds by executing code that


handles the exception
• The code that is run is referred to as an exception
handler and is usually a subroutine that is part of the
computer’s operating system code.
• Not a sub-routine that is part of the user’s program
Exceptions (Depiction of Control Flow)

Application Program Exception Handler

Current Instruction Exception


Exception i n c o n t rol flow Processing
Change
occurs here (run subroutine
Next Instruction that handles
Exception return exception
(optional)
Exception Handling - Before
Before
exception
This section of memory
occurs:
has subroutines for
handling exceptions
Processor is
executing an
instruction in
your (user)
PC Your program’s program.
instructions and data are
loaded here

Processor Primary Memory


Exception Handling – Saving Processor State
When
exception
This section of memory
occurs:
has subroutines for
handling exceptions
SYSTEM STACK
Values in
program
counter and
other registers
PC Your program’s are saved on
instructions and data are System Stack.
loaded here

Processor Primary Memory


Processing the exception
When
r o ce ssor
P exception
now This section of memory
ting occurs:
opera has subroutines for
in
ege handling exceptions
“privil ”
e SYSTEM STACK
d mod Program
counter is
loaded with
address of
PC Your program’s subroutine
instructions and data are which handles
loaded here the exception
(system
subroutine)
and executes
these
instructions.
Processor Primary Memory
Restoring Processor State Afterwards
After
r oc e ssor
P
ack exception is
now b al This section of memory
handled:
m
in nor r has subroutines for
(“use handling exceptions Program
”)
mode counter is
SYSTEM STACK
restored from
system stack
Program
PC Your program’s continues
instructions and data are execution
loaded here

*Except in
the case of
Abort.

Processor Primary Memory


Exceptions
• Just as with a regular subroutine, an exception handler
returns control to the point of the program from which the
handler was called except that for an exception control
flow can resume in one of several ways:
• At the next instruction
• Or at the instruction that was executing when the event occurred

• In some cases, the exception handler may abort the


program that was executed when the event occurred
• e.g. if a program attempts an illegal operation
• The exact way in which an exception returns depends on the
event that occurred.
Exception Classes
• Exceptions that can occur are varied
• Generally, there are 4 classes of exceptions:
• Interrupts
• Traps
• Faults
• Aborts
Interrupts
 Changes in the flow of control not due to an event that is caused by the
program that is running but by some other program or a device
 The user presses a key
 A device needs attention (e.g. network card has received packets)
 Like a “tap” on the shoulder
 Interrupts are used a lot for processor I/O
 Processor has pins that are signaled to indicate an interrupt
 Device places interrupt number on system
 Processor notices that the interrupt has gone high, reads the interrupt number
and calls the appropriate handler
Interrupts
 Interrupts are acknowledged after the instruction that was executing while
the interrupt was received completes
 After the interrupt is handled, control returns to the instruction following
the instruction that was running when the interrupt occurred
 To the running program it is as if nothing has happened
 All registers would have been saved before interrupt was handled
 Program’s state is restored when handler returns

 The subroutine that is executed when an interrupt occurs is called an


Interrupt Servicing Routine (ISR)
Interrupts

Application Program Exception Handler

(2) A subroutine that handles interrupts


(1) User (Interrupt Service Routine) is executed.
Current Instruction
presses key (3) Processor
when reads keystroke
Next Instruction and stores
program is (4) Handler character in
at this point returns to next memory.
instruction
Interrupts
 The term interrupt is often incorrectly used to refer to all classes of
exceptions
 Specifically, interrupts are used in computer systems for:
 Managing communications between the processor and devices
 To provide timing signals by the computer’s operating systems
 When a program starts executing a timer is set to some value
 As each instruction is executed, the timer is decremented by a
specific value
 When the timer reaches 0, an interrupt is sent to the processor
(called a Timer Interrupt) to tell the processor that the program
which is executing has used up all its allotted time
 Timer Interrupts are a feature of operating systems.
Traps

• There are some instances when a program needs


special attention from the processor to carry out a special
task that cannot be carried out by user instructions
• Most modern computer systems do not allow a user’s program
to access devices and other hardware directly
• Instead, a user’s program requests that access to the device be
carried out by the processor under the control of the operating
system.
• To do this, the program issues a special instruction that is called
the TRAP instruction
Traps
 A trap is a deliberate exception that is caused by the program when it
needs a service from the O/S
 The program loads details of the service it requires into special registers
 It then executes the TRAP instruction
 The system responds by causing the processor to run a subroutine (trap
handler) which satisfies the request
 After the TRAP has been satisfied, the normal control flow is resumed.
Traps

Application Program Exception Handler

(1) Program
issues TRAP TRAP #15
(2) Control passes to handler
(3) Trap handler
instruction runs
Next Instruction
(4) Handler
returns to
instruction
following the
TRAP
Faults
 Faults result from an error condition that its handler may be able to
correct
 Examples include requesting an address in a program that is not loaded
into memory at present
 Most modern computer systems do not load all of a program at once
 Instead portions of the program are brought into memory as needed
 A page fault, or segment fault occurs when a portion of the program that is needed is not
in memory
 More on this under the topic of Virtual memory.

 Control passes to the fault handler


 If the handler is able to correct the condition it returns control to the
faulting instruction thereby re-executing it
 E.g. load portion of program that is needed from disk
 Otherwise the handler returns to an abort procedure which terminates the
program
Aborts

Application Program Exception Handler

(2) Control passes to handler (instruction


not complete)
Current Instruction
(1Fault (3) Fault handler
runs
Next Instruction
(4) Handler either re-
executes current instruction
or aborts.
Aborts

 A running program can be aborted for any of several


reasons:
 Attempted to divide a number by 0
 Reference to illegal address (e.g. address in system area)
 Use of an unknown instruction
 User wants to abort program (e.g. infinite looping)
 Can also be aborted because fault has occurred but fault
handler cannot return the system to normal state.
 An abort is handled when it occurs (unlike interrupt in
which case execution of the current instruction is
completed.
Aborts

Application Program Exception Handler

(2) Control passes to handler


Current Instruction
(1) Abort (3) Abort handler
occurs runs
Next Instruction
(4) Handler causes program
to abort..
Summary

 Abrupt changes in the control flow of a program will occurs for several
reasons
 Instructions that execute branching are the most common reason for changes
in control flow
 Subroutine execution also causes branching
 Exceptions need to be handled
 The program’s stack area is used for subroutine linkage
 A stack frame is a set of entries that is created when a subroutine is called
 The stack frame will typically contain saved registers, parameters, space for a
returned value, and the return address of the subroutine
 An interrupt is an asynchronous exception
 Interrupts are primarily used for communicating with devices
 Traps, faults and aborts are synchronous exceptions
 The state of the processor must be saved before and exception is handled and
restored afterwards.

You might also like