MIPS Assembly Language Programming ICS 233 Computer Architecture
MIPS Assembly Language Programming ICS 233 Computer Architecture and Assembly Language Dr. Aiman El-Maleh College of Computer Sciences and Engineering King Fahd University of Petroleum and Minerals [Adapted from slides of Dr. M. Mudawar, ICS 233, KFUPM]
Outline v Assembly Language Statements v Assembly Language Program Template v Defining Data v Memory Alignment and Byte Ordering v System Calls v Procedures v Parameter Passing and the Runtime Stack MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 2
Assembly Language Statements v Three types of statements in assembly language ² Typically, one statement should appear on a line 1. Executable Instructions ² Generate machine code for the processor to execute at runtime ² Instructions tell the processor what to do 2. Pseudo-Instructions and Macros ² Translated by the assembler into real instructions ² Simplify the programmer task 3. Assembler Directives ² Provide information to the assembler while translating a program ² Used to define segments, allocate memory variables, etc. ² Non-executable: directives are not part of the instruction set MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 3
Instructions v Assembly language instructions have the format: [label: ] mnemonic [operands] [#comment] v Label: (optional) ² Marks the address of a memory location, must have a colon ² Typically appear in data and text segments v Mnemonic ² Identifies the operation (e. g. add, sub, etc. ) v Operands ² Specify the data required by the operation ² Operands can be registers, memory variables, or constants ² Most instructions have three operands L 1: addiu $t 0, 1 MIPS Assembly Language Programming ICS 233 – KFUPM #increment $t 0 © Muhamed Mudawar slide 4
Comments v Comments are very important! ² Explain the program's purpose ² When it was written, revised, and by whom ² Explain data used in the program, input, and output ² Explain instruction sequences and algorithms used ² Comments are also required at the beginning of every procedure § Indicate input parameters and results of a procedure § Describe what the procedure does v Single-line comment ² Begins with a hash symbol # and terminates at end of line MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 5
Next. . . v Assembly Language Statements v Assembly Language Program Template v Defining Data v Memory Alignment and Byte Ordering v System Calls v Procedures v Parameter Passing and the Runtime Stack MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 6
Program Template # Title: Filename: # Author: Date: # Description: # Input: # Output: ######### Data segment ###########. data. . . ######### Code segment ###########. text. globl main: # main program entry. . . li $v 0, 10 # Exit program syscall MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 7
. DATA, . TEXT, &. GLOBL Directives v. DATA directive ² Defines the data segment of a program containing data ² The program's variables should be defined under this directive ² Assembler will allocate and initialize the storage of variables v. TEXT directive ² Defines the code segment of a program containing instructions v. GLOBL directive ² Declares a symbol as global ² Global symbols can be referenced from other files ² We use this directive to declare main procedure of a program MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 8
Layout of a Program in Memory 0 x 7 FFFFFFF Memory Addresses in Hex Stack Segment Dynamic Area 0 x 10000000 Stack Grows Downwards Data Segment Static Area Text Segment 0 x 04000000 0 MIPS Assembly Language Programming Reserved ICS 233 – KFUPM © Muhamed Mudawar slide 9
Next. . . v Assembly Language Statements v Assembly Language Program Template v Defining Data v Memory Alignment and Byte Ordering v System Calls v Procedures v Parameter Passing and the Runtime Stack MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 10
Data Definition Statement v Sets aside storage in memory for a variable v May optionally assign a name (label) to the data v Syntax: [name: ] directive initializer [, initializer]. . . var 1: . WORD 10 v All initializers become binary data in memory MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 11
Data Directives v. BYTE Directive ² Stores the list of values as 8 -bit bytes v. HALF Directive ² Stores the list as 16 -bit values aligned on half-word boundary v. WORD Directive ² Stores the list as 32 -bit values aligned on a word boundary v. WORD w: n Directive ² Stores the 32 -bit value w into n consecutive words aligned on a word boundary. MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 12
Data Directives v. HALF w: n Directive ² Stores the 16 -bit value w into n consecutive half-words aligned on a half-word boundary. v. BYTE w: n Directive ² Stores the 8 -bit value w into n consecutive bytes. v. FLOAT Directive ² Stores the listed values as single-precision floating point v. DOUBLE Directive ² Stores the listed values as double-precision floating point MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 13
String Directives v. ASCII Directive ² Allocates a sequence of bytes for an ASCII string v. ASCIIZ Directive ² Same as. ASCII directive, but adds a NULL char at end of string ² Strings are null-terminated, as in the C programming language v. SPACE n Directive ² Allocates space of n uninitialized bytes in the data segment v Special characters in strings follow C convention ² Newline: n MIPS Assembly Language Programming Tab: t Quote: ” ICS 233 – KFUPM © Muhamed Mudawar slide 14
Examples of Data Definitions. DATA var 1: . BYTE 'A', 'E', 127, -1, 'n' var 2: . HALF -10, 0 xffff var 3: . WORD 0 x 12345678 Var 4: . WORD 0: 10 var 5: . FLOAT 12. 3, -0. 1 var 6: . DOUBLE 1. 5 e-10 str 1: . ASCII "A Stringn" str 2: . ASCIIZ "NULL Terminated String" array: . SPACE MIPS Assembly Language Programming 100 ICS 233 – KFUPM © Muhamed Mudawar slide 15
Next. . . v Assembly Language Statements v Assembly Language Program Template v Defining Data v Memory Alignment and Byte Ordering v System Calls v Procedures v Parameter Passing and the Runtime Stack MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 16
Memory Alignment v Memory is viewed as an array of bytes with addresses ² Byte Addressing: address points to a byte in memory v Words occupy 4 consecutive bytes in memory Memory v Alignment: address is a multiple of size ² Word address should be a multiple of 4 § Least significant 2 bits of address should be 00 ² Halfword address should be a multiple of 2 address ² MIPS instructions and integers occupy 4 bytes 12 . . . aligned word not aligned 8 4 0 v. ALIGN n directive ² Aligns the next data definition on a 2 n byte boundary MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 17 not aligned
Symbol Table v Assembler builds a symbol table for labels (variables) ² Assembler computes the address of each label in data segment v Example. DATA var 1: str 1: var 2: . ALIGN var 3: . BYTE. ASCIIZ. WORD 3. HALF var 1 Symbol Table 1, 2, 'Z' "My Stringn" 0 x 12345678 1000 Label Address var 1 str 1 var 2 var 3 0 x 10010000 0 x 10010003 0 x 10010010 0 x 10010018 str 1 0 x 10010000 1 2 'Z' 'M' 'y' ' ' 'S' 't' 'r' 'i' 'n' 'g' 'n' 0 0 x 10010010 0 x 12345678 0 0 1000 0 0 0 var 2 (aligned) MIPS Assembly Language Programming Unused ICS 233 – KFUPM var 3 (address is multiple of 8) © Muhamed Mudawar slide 18 Unused
Byte Ordering and Endianness v Processors can order bytes within a word in two ways v Little Endian Byte Ordering ² Memory address = Address of least significant byte ² Example: Intel IA-32, Alpha MSB LSB Byte 3 Byte 2 Byte 1 Byte 0 32 -bit Register a+1 a+2 a+3 address a. . . Byte 0 Byte 1 Byte 2 Byte 3 . . . Memory v Big Endian Byte Ordering ² Memory address = Address of most significant byte ² Example: SPARC, PA-RISC MSB LSB Byte 3 Byte 2 Byte 1 Byte 0 32 -bit Register a+1 a+2 a+3 address a. . . Byte 3 Byte 2 Byte 1 Byte 0. . . Memory v MIPS can operate with both byte orderings MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 19
Element Addresses in a 2 D Array v 2 D array elements are usually stored in memory in a row wise fashion v Address calculation is essential when programming in assembly COLS ROWS 0 1 … j … COLS-1 0 1 … i … ROWS-1 &matrix[i][j] = &matrix + (i×COLS + j) × Element_size MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 20
Next. . . v Assembly Language Statements v Assembly Language Program Template v Defining Data v Memory Alignment and Byte Ordering v System Calls v Procedures v Parameter Passing and the Runtime Stack MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 21
System Calls v Programs do input/output through system calls v MIPS provides a special syscall instruction ² To obtain services from the operating system ² Many services are provided in the SPIM and MARS simulators v Using the syscall system services ² Load the service number in register $v 0 ² Load argument values, if any, in registers $a 0, $a 1, etc. ² Issue the syscall instruction ² Retrieve return values, if any, from result registers MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 22
Syscall Services Service $v 0 Arguments / Result Print Integer 1 $a 0 = integer value to print Print Float 2 $f 12 = float value to print Print Double 3 $f 12 = double value to print Print String 4 $a 0 = address of null-terminated string Read Integer 5 Return integer value in $v 0 Read Float 6 Return float value in $f 0 Read Double 7 Return double value in $f 0 Read String 8 $a 0 = address of input buffer $a 1 = maximum number of characters to read Allocate Heap memory 9 $a 0 = number of bytes to allocate Return address of allocated memory in $v 0 Exit Program 10 MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 23
Syscall Services – Cont’d Print Char 11 $a 0 = character to print Read Char 12 Return character read in $v 0 13 $a 0 = address of null-terminated filename string $a 1 = flags (0=read, 1=write, 9=append) $a 2 = mode (ignored) Return file descriptor in $v 0 (negative if error) 14 $a 0 = File descriptor $a 1 = address of input buffer $a 2 = maximum number of characters to read Return number of characters read in $v 0 Write to File 15 $a 0 = File descriptor $a 1 = address of buffer $a 2 = number of characters to write Return number of characters written in $v 0 Close File 16 $a 0 = File descriptor Open File Read from File MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 24
Reading and Printing an Integer ######### Code segment ###########. text. globl main: # main program entry li $v 0, 5 # Read integer syscall # $v 0 = value read move $a 0, $v 0 li $v 0, 1 syscall # $a 0 = value to print # Print integer li $v 0, 10 syscall # Exit program MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 25
Reading and Printing a String ######### Data segment ###########. data str: . space 10 # array of 10 bytes ######### Code segment ###########. text. globl main: # main program entry la $a 0, str # $a 0 = address of str li $a 1, 10 # $a 1 = max string length li $v 0, 8 # read string syscall li $v 0, 4 # Print string str syscall li $v 0, 10 # Exit program syscall MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 26
Program 1: Sum of Three Integers # Sum of three integers # # Objective: Computes the sum of three integers. # Input: Requests three numbers. # Output: Outputs the sum. ########## Data segment ##########. data prompt: . asciiz "Please enter three numbers: n" sum_msg: . asciiz "The sum is: " ########## Code segment ##########. text. globl main: la $a 0, prompt # display prompt string li $v 0, 4 syscall li $v 0, 5 # read 1 st integer into $t 0 syscall move $t 0, $v 0 MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 27
Sum of Three Integers – Slide 2 of 2 li $v 0, 5 syscall move $t 1, $v 0 # read 2 nd integer into $t 1 li $v 0, 5 syscall move $t 2, $v 0 # read 3 rd integer into $t 2 addu # accumulate the sum $t 0, $t 1 $t 0, $t 2 la $a 0, sum_msg li $v 0, 4 syscall # write sum message move $a 0, $t 0 li $v 0, 1 syscall # output sum li $v 0, 10 syscall # exit MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 28
Program 2: Case Conversion # Objective: Convert lowercase letters to uppercase # Input: Requests a character string from the user. # Output: Prints the input string in uppercase. ########## Data segment ###########. data name_prompt: . asciiz "Please type your name: " out_msg: . asciiz "Your name in capitals is: " in_name: . space 31 # space for input string ########## Code segment ###########. text. globl main: la $a 0, name_prompt # print prompt string li $v 0, 4 syscall la $a 0, in_name # read the input string li $a 1, 31 # at most 30 chars + 1 null char li $v 0, 8 syscall MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 29
Case Conversion – Slide 2 of 2 loop: la $a 0, out_msg li $v 0, 4 syscall la $t 0, in_name # write output message lb $t 1, ($t 0) beqz $t 1, exit_loop # blt $t 1, 'a', no_change bgt $t 1, 'z', no_change addiu $t 1, -32 # sb $t 1, ($t 0) no_change: addiu $t 0, 1 # j loop exit_loop: la $a 0, in_name # li $v 0, 4 syscall li $v 0, 10 # syscall MIPS Assembly Language Programming if NULL, we are done convert to uppercase: 'A'-'a'=-32 increment pointer output converted string exit ICS 233 – KFUPM © Muhamed Mudawar slide 30
Example of File I/O # Sample MIPS program that writes to a new text file. data file: . asciiz "out. txt" # output filename buffer: . asciiz "Sample text to write". text li $v 0, la $a 0, li $a 1, li $a 2, syscall move $s 6, li $v 0, move $a 0, la $a 1, li $a 2, syscall li $v 0, move $a 0, syscall 13 file 1 0 $v 0 15 $s 6 buffer 20 16 $s 6 MIPS Assembly Language Programming # # # # system call to open a file for writing output file name Open for writing (flags 1 = write) mode is ignored open a file (file descriptor returned in $v 0) save the file descriptor Write to file just opened file descriptor address of buffer from which to write number of characters to write = 20 write to file system call to close file descriptor to close file ICS 233 – KFUPM © Muhamed Mudawar slide 31
Next. . . v Assembly Language Statements v Assembly Language Program Template v Defining Data v Memory Alignment and Byte Ordering v System Calls v Procedures v Parameter Passing and the Runtime Stack MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 32
Procedures v A procedure (or function) is a tool used by programmers ² Allows the programmer to focus on just one task at a time ² Allows code to be reused v Procedure Call and Return ² Put parameters in a place where procedure can access § Four argument registers: $a 0 thru $a 3 in which to pass parameters ² Transfer control to the procedure and save return address § Jump-and-Link instruction: jal (Return Address saved in $ra) ² Perform the desired task ² Put results in a place where the calling procedure can access § Two value registers to return results: $v 0 and $v 1 ² Return to calling procedure: jr $ra (jump to return address) MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 33
Procedures v Consider the following swap procedure (written in C) v Translate this procedure to MIPS assembly language void swap(int v[], int k) { int temp; temp = v[k] swap: v[k] = v[k+1]; sll $t 0, $a 1, 2 # $t 0=k*4 v[k+1] = temp; add $t 0, $a 0 # $t 0=v+k*4 } lw $t 1, 0($t 0) # $t 1=v[k] lw $t 2, 4($t 0) # $t 2=v[k+1 Parameters: sw $t 2, 0($t 0) # v[k]=$t 2 $a 0 = Address of v[] sw $t 1, 4($t 0) # v[k+1]=$t $a 1 = k, and Return address is in $ra jr $ra # return MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 34
Call / Return Sequence v Suppose we call procedure swap as: swap(a, 10) ² Pass address of array a and 10 as arguments ² Call the procedure swap saving return address in $31 = $ra ² Execute procedure swap ² Return control to the point of origin (return address) Registers. . . $a 0=$4 $a 1=$5 addr a 10. . . $ra=$31 ret addr MIPS Assembly Language Programming swap: sll Caller $t 0, $a 1, 2 add la $a 0, a $t 0, $a 0 li $a 1, lw 10 $t 1, 0($t 0) jal swap lw # return here $t 2, 4($t 0). . . ICS 233 – KFUPM © Muhamed Mudawar slide 35 sw
Details of JAL and JR Address Instructions 00400020 00400024 00400028 0040002 C 00400030 lui ori jal. . 0040003 C 00400044 00400048 0040004 C 00400050 00400054 sll add lw lw sw sw jr Assembly Language $1, 0 x 1001 $4, $1, 0 $5, $0, 10 0 x 10000 f. $8, $5, 2 $8, $4 $9, 0($8) $10, 4($8) $10, 0($8) $9, 4($8) $31 MIPS Assembly Language Programming ICS 233 – KFUPM la $a 0, a li $a 1, 10 jal swap # return here Pseudo-Direct Addressing PC = imm 26<<2 0 x 10000 f << 2 = 0 x 0040003 C $31 0 x 00400030 swap: sll $t 0, $a 1, 2 add $t 0, $a 0 Register $31 lw $t 1, 0($t 0) is the return lw $t 2, 4($t 0) address register sw $t 2, 0($t 0) sw $t 1, 4($t 0) jr $ra © Muhamed Mudawar slide 36
Instructions for Procedures v JAL (Jump-and-Link) used as the call instruction ² Save return address in $ra = PC+4 and jump to procedure ² Register $ra = $31 is used by JAL as the return address v JR (Jump Register) used to return from a procedure ² Jump to instruction whose address is in register Rs (PC = Rs) v JALR (Jump-and-Link Register) ² Save return address in Rd = PC+4, and ² Jump to procedure whose address is in register Rs (PC = Rs) ² Can be used to call methods (addresses known only at runtime) Instruction jal jr jalr Meaning label $31=PC+4, jump Rs PC = Rs Rd, Rs Rd=PC+4, PC=Rs MIPS Assembly Language Programming ICS 233 – KFUPM Format op 6 = 3 op 6 = 0 rs 5 0 0 imm 26 0 rd 5 © Muhamed Mudawar slide 37 0 0 8 9
Next. . . v Assembly Language Statements v Assembly Language Program Template v Defining Data v Memory Alignment and Byte Ordering v System Calls v Procedures v Parameter Passing and the Runtime Stack MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 38
Parameter Passing v Parameter passing in assembly language is different ² More complicated than that used in a high-level language v In assembly language ² Place all required parameters in an accessible storage area ² Then call the procedure v Two types of storage areas used ² Registers: general-purpose registers are used (register method) ² Memory: stack is used (stack method) v Two common mechanisms of parameter passing ² Pass-by-value: parameter value is passed ² Pass-by-reference: address of parameter is passed MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 39
Parameter Passing – cont'd v By convention, registers are used for parameter passing ² $a 0 = $4. . $a 3 = $7 are used for passing arguments ² $v 0 = $2. . $v 1 = $3 are used for result values v Additional arguments/results can be placed on the stack v Runtime stack is also needed to … ² Store variables / data structures when they cannot fit in registers ² Save and restore registers across procedure calls ² Implement recursion v Runtime stack is implemented via software convention ² The stack pointer $sp = $29 (points to top of stack) ² The frame pointer $fp = $30 (points to a procedure frame) MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 40
Stack Frame v Stack frame is the segment of the stack containing … ² Saved arguments, registers, and local data structures (if any) v Called also the activation frame or activation record v Frames are pushed and popped by adjusting … ² Stack pointer $sp = $29 and Frame pointer $fp = $30 $fp Frame f() $sp ↓ Stack $fp Frame f() $fp Frame g() $sp stack grows downwards allocate stack frame MIPS Assembly Language Programming ICS 233 – KFUPM $sp arguments saved $ra Frame f() g returns Stack f calls g ² Decrement $sp to allocate stack frame, and increment to free ↑ saved registers free stack frame local data structures or variables $sp © Muhamed Mudawar slide 41
Preserving Registers v Need to preserve registers across a procedure call ² Stack can be used to preserve register values v Caller-Saved Registers ² Registers $a 0 to $a 3 and $t 0 to $t 9 should be saved by Caller ² Only if needed after a procedure call v Callee-Saved Registers (Saved inside procedure) ² Registers $s 0 to $s 7, $fp, and $ra should be saved ² Only if used and modified inside procedure ² Should be saved upon procedure entry before they are modified ² Restored at end of procedure before returning to caller MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 42
Procedure Calling Convention v The Caller should do the following: 1. Pass Arguments ² First four arguments are passed in registers $a 0 thru $a 3 ² Additional arguments are pushed on the stack 2. Save Registers $a 0 - $a 3 and $t 0 - $t 9 if needed ² Registers $a 0 - $a 3 and $t 0 - $t 9 should be saved by Caller ² To preserve their value if needed after a procedure call ² Called procedure is free to modify $a 0 to $a 3 and $t 0 to $t 9 3. Execute JAL Instruction ² Jumps to the first instruction inside the procedure ² Saves the return address in register $ra MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 43
Procedure Calling Convention - 2 v The Called procedure (Callee) should do the following: 1. Allocate memory for the stack frame ² $sp = $sp – n (n bytes are allocated on the stack frame) ² The programmer should compute n ² A simple leaf procedure might not need a stack frame (n = 0) 2. Save registers $ra, $fp, $s 0 - $s 7 in the stack frame ² $ra, $fp, $s 0 - $s 7 should be saved inside procedure (callee) ² Before modifying their value and only if needed ² Register $ra should be saved only if the procedure makes a call 3. Update the frame pointer $fp (if needed) ² For simple procedures, the $fp register may not be required MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 44
Procedure Return Convention v Just before returning, the called procedure should: 1. Place the returned results in $v 0 and $v 1 (if any) 2. Restore all registers that were saved upon entry ² Load value of $ra, $fp, $s 0 - $s 7 if saved in the stack frame 3. Free the stack frame ² $sp = $sp + n (if n bytes are allocated for the stack frame) 4. Return to caller ² Jump to the return address: jr $ra MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 45
Example on Preserving Register v A function f calls g twice as shown below. We don't know what g does, or which registers are used in g. v We only know that function g receives two integer arguments and returns one integer result. v Translate f: int f(int a, int b) { int d = g(b, g(a, b)); return a + d; } MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 46
Example on Preserving Registers int f(int a, int b) { int d = g(b, g(a, b)); return a + d; } f: addiu sw sw sw jal lw move jal lw addu lw addiu jr $sp, $ra, $a 0, $a 1, g $a 0, $v 0, $ra, $sp, $ra MIPS Assembly Language Programming $sp, -12 # frame = 12 bytes 0($sp) # save $ra 4($sp) # save argument a 8($sp) # save argument b # call g(a, b) 8($sp) # $a 0 = b $v 0 # $a 1 = g(a, b) # call g(b, g(a, b)) 4($sp) # $a 0 = a $a 0, $v 0 # $v 0 = a + d 0($sp) # restore $ra $sp, 12 # free stack frame # return to caller ICS 233 – KFUPM © Muhamed Mudawar slide 47
Selection Sort Array first max Array first max value first max last value last value Unsorted Locate Max v Example first max last 3 1 5 2 4 3 1 4 2 5 last first max last MIPS Assembly Language Programming 3 1 4 2 5 3 1 2 4 5 ICS 233 – KFUPM max first last max value Swap Max with Last Decrement Last 3 1 2 4 5 2 1 3 4 5 max first last © Muhamed Mudawar slide 48 2 1 3 4 5 1 2 3 4 5
Selection Sort Procedure # Objective: Sort array using selection sort algorithm # Input: $a 0 = pointer to first, $a 1 = pointer to last # Output: array is sorted in place ############################# sort: addiu $sp, -4 # allocate one word on stack sw $ra, 0($sp) # save return address on stack top: jal max # call max procedure lw $t 0, 0($a 1) # $t 0 = last value sw $t 0, 0($v 0) # swap last and max values sw $v 1, 0($a 1) addiu $a 1, -4 # decrement pointer to last bne $a 0, $a 1, top # more elements to sort lw $ra, 0($sp) # pop return address addiu $sp, 4 # free stack frame jr $ra # return to caller MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 49
Max Procedure # Objective: Find the address and value of maximum element # Input: $a 0 = pointer to first, $a 1 = pointer to last # Output: $v 0 = pointer to max, $v 1 = value of max ############################# max: move $v 0, $a 0 # max pointer = first pointer lw $v 1, 0($v 0) # $v 1 = first value beq $a 0, $a 1, ret # if (first == last) return move $t 0, $a 0 # $t 0 = array pointer loop: addi $t 0, 4 # point to next array element lw $t 1, 0($t 0) # $t 1 = value of A[i] ble $t 1, $v 1, skip # if (A[i] <= max) then skip move $v 0, $t 0 # found new maximum move $v 1, $t 1 skip: bne $t 0, $a 1, loop # loop back if more elements ret: jr $ra MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 50
Example of a Recursive Procedure int fact(int n) { if (n<2) return 1; else return (n*fact(n-1)); } fact: slti beq li jr $t 0, $a 0, 2 $t 0, $0, else $v 0, 1 $ra # # (n<2)? if false branch to else $v 0 = 1 return to caller else: addiu sw sw addiu jal lw lw mul addi jr $sp, -8 $a 0, 4($sp) $ra, 0($sp) $a 0, -1 fact $a 0, 4($sp) $ra, 0($sp) $v 0, $a 0, $v 0 $sp, 8 $ra # # # # # allocate 2 words on stack save argument n save return address argument = n-1 call fact(n-1) restore argument restore return address $v 0 = n*fact(n-1) free stack frame return to caller MIPS Assembly Language Programming ICS 233 – KFUPM © Muhamed Mudawar slide 51
- Slides: 51