MIPS Assembly Language Programming

Similar documents
MIPS Reference Guide

Computer Architecture. The Language of the Machine

MIPS Instruction Set

MIPS Instruction Format

SPIM Instruction Set

The MIPS Instruction Set Architecture

Overview. Introduction to the MIPS ISA. MIPS ISA Overview. Overview (2)

MIPS Instruction Reference

Reduced Instruction Set Computer (RISC)

EEM 486: Computer Architecture. Lecture 2. MIPS Instruction Set Architecture

F. Appendix 6 MIPS Instruction Reference

MIPS ISA. 1. Data and Address Size 8-, 16-, 32-, 64-bit 2. Which instructions does the processor support

MIPS Assembly Language

Reduced Instruction Set Computer (RISC)

CISC 662 Graduate Computer Architecture. Lecture 4 - ISA

MIPS Assembly Language. Today s Lecture

Kernel Registers 0 1. Global Data Pointer. Stack Pointer. Frame Pointer. Return Address.

Today s Lecture. MIPS Assembly Language. Review: What Must be Specified? Review: A Program. Review: MIPS Instruction Formats

ECE Exam I February 19 th, :00 pm 4:25pm

101 Assembly. ENGR 3410 Computer Architecture Mark L. Chang Fall 2009

TSK3000A - Generic Instructions

Mark Redekopp, All rights reserved. EE 357 Unit 11 MIPS ISA

ECE232: Hardware Organization and Design. Computer Organization - Previously covered

Computer Architecture. MIPS Instruction Set Architecture

CISC 662 Graduate Computer Architecture. Lecture 4 - ISA MIPS ISA. In a CPU. (vonneumann) Processor Organization

M2 Instruction Set Architecture

Question 0. Do not turn this page until you have received the signal to start. (Please fill out the identification section above) Good Luck!

CSc 256 Midterm (green) Fall 2018

ECE 2035 Programming HW/SW Systems Fall problems, 7 pages Exam Two 23 October 2013

CSc 256 Midterm 2 Fall 2011

Introduction to the MIPS. Lecture for CPSC 5155 Edward Bosworth, Ph.D. Computer Science Department Columbus State University

Instruction Set Architecture of. MIPS Processor. MIPS Processor. MIPS Registers (continued) MIPS Registers

CSc 256 Midterm 2 Spring 2012

Introduction to MIPS Processor

Examples of branch instructions

Flow of Control -- Conditional branch instructions

MIPS Assembly Programming

Mips Code Examples Peter Rounce

The MIPS R2000 Instruction Set

Week 10: Assembly Programming

Chapter 2. Instructions: Language of the Computer. Adapted by Paulo Lopes

Midterm. Sticker winners: if you got >= 50 / 67

Lecture 2. Instructions: Language of the Computer (Chapter 2 of the textbook)

Assembly Programming

Programming the processor

CPS311 - COMPUTER ORGANIZATION. A bit of history

5/17/2012. Recap from Last Time. CSE 2021: Computer Organization. The RISC Philosophy. Levels of Programming. Stored Program Computers

Chapter 2A Instructions: Language of the Computer

Recap from Last Time. CSE 2021: Computer Organization. Levels of Programming. The RISC Philosophy 5/19/2011

ece4750-parc-isa.txt

INSTRUCTION SET COMPARISONS

CS3350B Computer Architecture MIPS Instruction Representation

Q1: /30 Q2: /25 Q3: /45. Total: /100

A Processor. Kevin Walsh CS 3410, Spring 2010 Computer Science Cornell University. See: P&H Chapter , 4.1-3

Adventures in Assembly Land

Processor. Han Wang CS3410, Spring 2012 Computer Science Cornell University. See P&H Chapter , 4.1 4

Instruction Set Architecture part 1 (Introduction) Mehran Rezaei

Lec 10: Assembler. Announcements

Mark Redekopp, All rights reserved. EE 352 Unit 3 MIPS ISA

CSc 256 Final Fall 2016

Exam in Computer Engineering

Computer Architecture

Instructions: Language of the Computer

ECE 2035 Programming HW/SW Systems Spring problems, 6 pages Exam One 4 February Your Name (please print clearly)

ECE 15B Computer Organization Spring 2010

MACHINE LANGUAGE. To work with the machine, we need a translator.

MIPS R-format Instructions. Representing Instructions. Hexadecimal. R-format Example. MIPS I-format Example. MIPS I-format Instructions

EE 109 Unit 13 MIPS Instruction Set. Instruction Set Architecture (ISA) Components of an ISA INSTRUCTION SET OVERVIEW

ECE 2035 Programming HW/SW Systems Fall problems, 6 pages Exam One 19 September 2012

Instructions: MIPS ISA. Chapter 2 Instructions: Language of the Computer 1

ECE 2035 Programming HW/SW Systems Fall problems, 6 pages Exam Two 23 October Your Name (please print clearly) Signed.

EE108B Lecture 3. MIPS Assembly Language II

CS 4200/5200 Computer Architecture I

MIPS ISA and MIPS Assembly. CS301 Prof. Szajda

Concocting an Instruction Set

Anne Bracy CS 3410 Computer Science Cornell University. See P&H Chapter: , , Appendix B

Anne Bracy CS 3410 Computer Science Cornell University. [K. Bala, A. Bracy, E. Sirer, and H. Weatherspoon]

Chapter 2. Computer Abstractions and Technology. Lesson 4: MIPS (cont )

software hardware Which is easier to change/design???

Computer Organization & Design

ECE 2035 Programming HW/SW Systems Spring problems, 6 pages Exam Two 11 March Your Name (please print) total

Thomas Polzer Institut für Technische Informatik

Computer Organization and Structure. Bing-Yu Chen National Taiwan University

MIPS%Assembly% E155%

Assembly Language. Prof. Dr. Antônio Augusto Fröhlich. Sep 2006

Arithmetic for Computers

EE 109 Unit 8 MIPS Instruction Set

Number Systems and Their Representations

CS 61c: Great Ideas in Computer Architecture

Computer Systems and Architecture

Outline. EEL-4713 Computer Architecture Multipliers and shifters. Deriving requirements of ALU. MIPS arithmetic instructions

ENCM 369 Winter 2013: Reference Material for Midterm #2 page 1 of 5

CENG3420 Lecture 03 Review

Computer Organization and Structure. Bing-Yu Chen National Taiwan University

CSCI 402: Computer Architectures. Instructions: Language of the Computer (3) Fengguang Song Department of Computer & Information Science IUPUI.

MIPS Coding Snippets. Prof. James L. Frankel Harvard University. Version of 9:32 PM 14-Feb-2016 Copyright 2016 James L. Frankel. All rights reserved.

ECE260: Fundamentals of Computer Engineering

Character Is a byte quantity (00~FF or 0~255) ASCII (American Standard Code for Information Interchange) Page 91, Fig. 2.21

ECE468 Computer Organization & Architecture. MIPS Instruction Set Architecture

ECE 2035 Programming HW/SW Systems Fall problems, 6 pages Exam One 22 September Your Name (please print clearly) Signed.

Transcription:

MIPS Assembly Language Programming Bob Britton Chapter 1 The MIPS Architecture My objective in teaching assembly language is to introduce students to the fundamental concepts of contemporary computer architecture. First impressions are important. When students are first introduced to computer architecture it is important that they are exposed to the fundamentals of how modern computers are organized. Prentice Hall The MIPS architecture embodies the fundamental design principles of all contemporary RISC architectures. All instructions are directly executed in hardware The rate at which instructions are issued is maximized Instructions are easy to decode Only load and store instructions reference memory Plenty of general purpose registers are provided (32 for MIPS) Suggested Background Preparation Experience in developing algorithms, and running programs in some high level language such as C, C++, or Java

Benefits of Studying Assembly Language Programming Obtain Insights into writing more efficient code Will become familiar with what compilers do http://www.mips.com/ The most likely area where assembly language programming is done is with embedded Processors,and MIPS has the largest share of the 64-bit embedded processor market. Acquire an understanding of how a RISC CPU is organized Open new opportunities in the field of embedded processors Going to the web site http://www.mips.com/ you will find that the MIPS processor is used in: Cisco Routers Laser Printers built by HP and Fuji Xerox PDA s Set-Top Boxes Sony AIBO Entertainment Robot Minolta Digital Camera Sony PlayStation Course Description Chapter 1 - The MIPS architecture Chapter 2 - Algorithm Development in Pseudocode Chapter 3 - Number Systems Chapter 4 - PCSpim The MIPS Simulator Chapter 5 - Efficient Algorithm Development Chapter 6 - Passing Parameters on the Stack Chapter 7 - Reentrant Functions Chapter 8 - Memory-Mapped I/O Chapter 9 - Exceptions and Interrupts Chapter 10 - A Pipelined Implementation Chapter 11 - Floating-Point Instructions

The Datapath Diagram MIPS DataPath Diagram Program Counter (PC) MIPS Cache Memory Out Address Instruction Register Control Logic Rs ALU Rd Rt Data In Register File 4 A Register Transfer Description of the Control Logic lw lw or sw Address = Rs + Offset IR = Mem[PC] PC = PC + 4 Decode Instruction Read from Reg. File sw Memory[Address] = Rt Reg. File[Rt] = Memory[Address] Fetch Execute Cycle R-Type beqz If (Rs == 0 ) then PC = PC + Offset Reg. File[Rd] = Rs operation Rt Register File Register File Number Value 0 $zero 1 $at 2 $v0 3 $v1 4 $a0 5 $a1 6 $a2 7 $a3 8 $t0 9 $t1 10 $t2 11 $t3 12 $t4 13 $t5 14 $t6 15 $t7 16 $s0 17 $s1 18 $s2 19 $s3 20 $s4 21 $s5 22 $s6 23 $s7 24 $t8 Name Return values from functions Pass parameters to functions Caller Saved Registers Use these registers in functions Callee-Saved Registers Use these registers for values that must be maintained across function calls.

Number Value Name MIPS Register File 25 $t9 26 $k0 27 $k1 28 $gp 29 $sp 30 $fp 31 $ra Register Naming Convention (See Table 1.1) $0 : Constant Zero $v0 : Returned values from functions $a0 : Arguments passed to functions $t0 : Temporary registers (functions) $s0 : Saved registers (main program) $sp : Stack Pointer $ra : Return address Three Instruction Word Formats Register Format Op-Code Rs Rt Rd Code 6 5 5 5 6 Immediate Format Instruction Word Formats MIPS Assembly Language Programming Bob Britton Chapter 1 - b The MIPS Architecture Op-Code Rs Rt 16 - Bit Immediate Value 6 5 5 16 Jump Format Op-Code 26 Bit Current Segment Address 6 26

Instruction Set MIPS Instruction Set See Appendix C in the textbook for a detailed description of every instruction. Arithmetic, Logic, and Shifting Instructions Conditional Branch Instructions Load and Store Instructions Function Call Instructions An Example Let us suppose that an assembly language programmer wants to add the contents of register $a1 to the contents of register $s1, and to place the result in register $v1. The assembly language instruction to accomplish this is: add $v1, $a1, $s1 The equivalent pseudocode statement is: $v1 = $a1 + $s1 Quick Reference Appendix A Integer Instruction Set Name Syntax Space/Time Add: add Rd, Rs, Rt 1/1 Add Immediate: addi Rt, Rs, Imm 1/1 Add Immediate Unsigned: addiu Rt, Rs, Imm 1/1 Add Unsigned: addu Rd, Rs, Rt 1/1 And: and Rd, Rs, Rt 1/1 And Immediate: andi Rt, Rs, Imm 1/1 Branch if Equal: beq Rs, Rt, Label 1/1 Branch if Greater Than or Equal to Zero: bgez Rs, Label 1/1 Branch if Greater Than or Equal to Zero and Link: bgezal Rs, Label 1/1 Branch if Greater Than Zero: bgtz Rs, Label 1/1 Branch if Less Than or Equal to Zero: blez Rs, Label 1/1 Branch if Less Than Zero and Link: bltzal Rs, Label 1/1 Branch if Less Than Zero: bltz Rs, Label 1/1 Branch if Not Equal: bne Rs, Rt, Label 1/1 Divide: div Rs, Rt 1/38 Divide Unsigned: divu Rs, Rt 1/38 Jump: j Label 1/1 Jump and Link: jal Label 1/1 Jump and Link Register: jalr Rd, Rs 1/1 Jump Register: jr Rs 1/1 Integer Instruction Set Name Syntax Space/Time Load Byte: lb Rt, offset(rs) 1/1 Load Byte Unsigned: lbu Rt, offset(rs) 1/1 Load Halfword: lh Rt, offset(rs) 1/1 Load Halfword Unsigned: lhu Rt, offset(rs) 1/1 Load Upper Immediate: lui Rt, Imm 1/1 Load Word: lw Rt, offset(rs) 1/1 Load Word Left: lwl Rt, offset(rs) 1/1 Load Word Right: lwr Rt, offset(rs) 1/1 Move From Coprocessor 0 mfc0 Rd, Cs 1/1 Move From High: mfhi Rd 1/1 Move From Low: mflo Rd 1/1 Move To Coprocessor 0 mtc0 Rt, Cd 1/1 Move to High: mthi Rs 1/1 Move to Low: mtlo Rs 1/1 Multiply: mult Rs, Rt 1/32 Multiply Unsigned: multu Rs, Rt 1/32 NOR: nor Rd, Rs, Rt 1/1 OR: or Rd, Rs, Rt 1/1 OR Immediate: ori Rt, Rs, Imm 1/1 Return From Exception: rfe 1/1 Store Byte: sb Rt, offset(rs) 1/1 Store Halfword: sh Rt, offset(rs) 1/1 Shift Left Logical: sll Rd, Rt, sa 1/1 Shift Left Logical Variable: sllv Rd, Rt, Rs 1/1

Integer Instruction Set Name Syntax Space/Time Set on Less Than: slt Rd, Rt, Rs 1/1 Set on Less Than Immediate: slti Rt, Rs, Imm 1/1 Set on Less Than Immediate Unsigned: sltiu Rt, Rs, Imm 1/1 Set on Less Than Unsigned: sltu Rd, Rt, Rs 1/1 Shift Right Arithmetic: sra Rd, Rt, sa 1/1 Shift Right Arithmetic Variable: srav Rd, Rt, Rs 1/1 Shift Right Logical: srl Rd, Rt, sa 1/1 Shift Right Logical Variable: srlv Rd, Rt, Rs 1/1 Subtract: sub Rd, Rs, Rt 1/1 Subtract Unsigned: subu Rd, Rs, Rt 1/1 Store Word: sw Rt, offset(rs) 1/1 Store Word Left: swl Rt, offset(rs) 1/1 Store Right: swr Rt, offset(rs) 1/1 System Call: 1/1 Exclusive OR: xor Rd, Rs, Rt 1/1 Exclusive OR Immediate: xori Rt, Rs, Imm 1/1 Macro Instructions Load Address la $s0, table Load Immediate li $v0, 10 Move mov $t8, $sp Multiply mul $t2, $a0, $a1 Divide div $s1, $v1, $t7 Remainder rem $s2, $v1, $t7 Negate neg $s0, $s0 There are instructions to implement control structures such as: if... then... else... Let us suppose that if the contents of register $s6 is less than zero, in other words negative, we want to branch to a location in the program labeled Quit. Otherwise (else) we want to decrement the contents of register $s6. if ($s6 >= 0) then ($s6 = $s6 1) else goto Quit The assembly language instructions to accomplish this are: bltz $s6, Quit addi $s6, $s6, -1 The multiply instruction mult multiplies two 32-bit binary values and produces a 64-bit product which is stored in two special registers named High and Low. In this case, the destination for the result is implicitly understood. Register High will be loaded with the upper 32-bits of the product and register Low will be loaded with the lower 32-bits of the product. To move a copy of the value in the High register to the register file we use the instruction mfhi and to move a copy of the value in the Low register to the register file we use the instruction mflo. The following code segment shows how the 64-bit product of $a1 times $s1 can be moved into $v0 and $v1: mult $a1, $s1 mfhi $v0 mflo $v1

The following divide instruction divides the 32-bit binary value in register $a1 by the 32-bit value in register $s1. The quotient is stored in the Low register and the remainder is stored in the High register. The following code segment shows how the quotient is moved into $v0 and the remainder is moved into $v1: div $a1, $s1 mflo $v0 mfhi $v1 In the MIPS architecture, division by zero is undefined. If it is possible that the divisor could be zero, then it is the programmers responsibility to test for this condition and to provide code to handle this special situation. An Example MIPS Assembly Language Program to find the sum of the integers from 1 to 99 Label Op-Code Dest. S1, S2 Comments move $a0, $0 # $a0 = 0 li $t0, 99 # $t0 = 99 loop: add $a0, $a0, $t0 # $a0 = $a0 + $t0 addi $t0, $t0, -1 # $t0 = $t0-1 bnez $t0, loop # if ($t0!= zero) branch loop li $v0, 1 # Print the value in $a0 li $v0, 10 # Terminate Program Run Addressing Modes Memory Addressing Modes The MIPS architecture is a Load/Store architecture, which means the only instructions that access main memory are the load and store instructions. Only one addressing mode is implemented in the hardware. The addressing mode is referred to as base address plus displacement. A load instruction accesses a value from memory and places a copy of the value found in memory in the register file. For example, the instruction: lw $s1, 8($a0) computes the effective address of the memory location to be accessed by adding together the contents of register $a0 (the base address) and the constant value eight (the displacement). A copy of the value accessed from memory at the effective address is loaded into register $s1. The equivalent pseudocode statement would be: $s1 = Mem[$a0 + 8]

The syntax of the assembly language load instruction is somewhat confusing. lw $s1, 8($a0) If someone were to write a new MIPS assembler, the following syntax would do a better job of conveying what the instruction actually does: lw $s1, [$a0+8] The following is an example of a Store Word instruction: sw $s1, 12($a0) When the hardware executes this instruction it will compute the effective address of the destination memory location by adding together the contents of register $a0 and the constant value 12. A copy of the contents of register $s1 is stored in memory at the effective address. The equivalent pseudocode statement would be: Mem[$a0 + 12] = $s1 From the point of view of an assembly language programmer, memory can be thought of as a very long linear array of locations where binary codes are stored. An effective address is a pointer to some location in this array. Fetch Execute Cycle A Register Transfer Description of the Control Logic IR = Mem[PC] PC = PC + 4 DataPath Diagram Program Counter (PC) Cache Memory Instruction Register Out ALU lw or sw Decode Instruction Read from Reg. File beqz Address Control Logic Rs Address = Rs + Offset R-Type sw Memory[Address] = Rt lw If (Rs == 0 ) then PC = PC + Offset Data In Rd Register File Rt 4 Reg. File[Rt] = Memory[Address] Reg. File[Rd] = Rs operation Rt

Exercises Exercises 1.1 Explain the difference between a register and the ALU. 1.2 Explain the difference between Assembly Language and Machine Language. 1.3 Explain the difference between Cache Memory and the Register File. 1.4 Explain the difference between the Instruction Register and the Program Counter. 1.5 Explain the difference between a buss and a control line. 1.6 Identify a kitchen appliance that contains a control unit. 1.7 What is an algorithm? 1.8 Provide a step-by-step description of the sequence of operations that must take place within a MIPS processor to fetch and execute the load word instruction. 1.9 Provide a step-by-step description of the sequence of operations that must take place within a MIPS processor to fetch and execute the store word instruction. MIPS Assembly Language Programming Bob Britton Chapter 2 Algorithm Development in Pseudocode Pseudocode Using Pseudocode to Document a MIPS Assembly Language Program When documenting an algorithm in a language such as C, programmers use descriptive variable names such as: speed, volume, size, count, amount, etc. After the program is compiled, these variable names correspond to memory locations. To efficiently execute code, a compiler will attempt to keep the variables that are referenced most often in processor registers because access to a variable in a processor register is much faster than access to memory. MIPS has 32 processor registers. The names used to reference these registers are defined in Table 1.1 in the textbook. As an assembly language programmer you must take maximum advantage of the processor registers. When using pseudocode to document an assembly language program, you will be expected to use the names of the registers you intend to use in the assembly language code. It is advisable to create a cross reference table between the processor register name and what it is being used for in the program.

We use register names in pseudocode because the purpose of the pseudocode is to document an assembly language program. Unless you identify the registers being used, the pseudocode is quite limited in terms of having any correspondence to the assembly language code. You will also find that as soon as you are able to develop the pseudocode in this format it is a very simple process to translate pseudocode into assembly language code. For (t0=1; t0 < s0; t0++) do {this block of code}; Pseudocode for assembly language programs will have the appearance of C in terms of control structures and arithmetic expressions, but descriptive variable names will usually only appear in the LOAD ADDRESS (la) instruction where there is a reference to a symbolic memory address. In assembly language you define and allocate space for variables in the data segment of memory using assembler directives such as.word and.space. You will find that all of the MIPS instructions require the use of processor registers. When writing pseudocode you should specify the processor registers you are planning to use to accomplish the task.

MIPS Assembly Language Syntax Translation an Arithmetic Expression $s0 = srt ( $a0 * $a0 + $a1 * $a1) [label:] Op-Code [operand], [operand], [operand] [#comment] Label Op-Code Dest. S1, S2 Comment chico: add $a0, $t0, $t1 # a0 = t0 + t1 Hypotenuse: mult $a0, $a0 # Square $a0 mflo $t0 # t0 = Lower 32-bits of product mult $a1, $a1 # Square $a1 mflo $t1 # t1 = Lower 32-bits of product add $a0, $t0, $t1 # a0 = t0 + t1 jal srt # Call the square root function move $s0, $v0 # By convention, the result of sqr # is returned in $v0 Area: Area of a Circle $s0 = π * $t8 * $t8 li $t0, 314156 # Load immediate Pi scaled up 100,000 mult $t8, $t8 # Radius squared mflo $t1 # Move lower 32-bits of product in # Low register to $t1 mult $t1, $t0 # Multiply by scaled Pi mflo $s0 # Move lower 32-bits of product in # Low register to $s0 li $t1, 100000 # Load immediate scale factor of 100,000 div $s0, $t1 # Divide by scale factor mflo $s0 # Truncated integer result left in $s0 Translation of an if then else Control Structure if ($t8 < 0) then {$s0 = 0 - $t8; $t1 = $t1 +1} else {$s0 = $t8; $t2 = $t2 + 1} else: next: bgez $t8, else # if ($t8 is greater than or # equal to zero) branch to else sub $s0, $zero, $t8 # $s0 gets the negative of $t8 addi $t1, $t1, 1 # increment $t1 by 1 b next # branch around the else code move $s0, $t8 # $s0 gets a copy of $t8 addi $t2, $t2, 1 # increment $t2 by 1

Translation of a while Control Structure while ($a1 < $a2) do { $a1 = $a1 + 1 $a2 = $a2-1} while: bgeu $a1, $a2, done # If( $a1 >= $a2) Branch to done addi $a1, $a1, 1 # $a1 = $a1 + 1 addi $a2, $a2, -1 # $a2 = $a2-1 b while # Branch to while done: loop: Translation of a for Loop Control Structure $a0 = 0; for ( $t0 =10; $t0 > 0; $t0 = $t0-1) do {$a0 = $a0 + $t0} li $a0, 0 # $a0 = 0 li $t0, 10 # Initialize loop counter to 10 add $a0, $a0, $t0 addi $t0, $t0, -1 # Decrement loop counter bgtz $t0, loop # If ($t0 > 0) Branch to loop Now for an example, let us suppose that we want to write an assembly language program to find the sum of the integers from 1 to N. In other words do the following: 1 + 2 + 3 + 4 + 5 + 6 + 7 +...+ N, where N is an input value. On the next slide you will see a pseudocode description of the algorithm and following that the corresponding assembly language program, where processor register $t0 is used to accumulate the sum, and processor register $v0 is used as a loop counter. Use a word processor to create the following program file. Be sure to save as text only. Next, load the program into SPIM. Run the program and experiment with the different features of the MIPS simulator. ( For example: Single Step) Read the help file for a description of how to use the simulator. An Example MIPS Program # Program #1 : (descriptive name) Programmer: YOUR NAME # Due Date : Sep. 13, 2001 Course: CSCI 221 # Last Modified: Sep. 12, 2006 # Functional Description: Find the sum of the integers from 1 to N where # N is a value input from the keyboard. ######################################################### # Algorithmic Description in Pseudocode: # main: v0 << value read from the keyboard ( 4) # if (v0 < = 0 ) stop # t0 = 0; # t0 is used to accumulate the sum # While (v0 > 0) { t0 = t0 + v0; v0 = v0-1} # Output to monitor (1) << t0; goto main ########################################################## # Register Usage: $t0 is used to accumulate the sum # $v0 the loop counter, counts down to zero ##########################################################

.data prompt:.asciiz "\n\n Please Input a value for N = " result:.asciiz " The sum of the integers from 1 to N is " bye:.asciiz "\n **** Adios Amigo - Have a good day **** ".globl main.text main: li $v0, 4 # system call code for print_str la $a0, prompt # load address of prompt into a0 # print the prompt message li $v0, 5 # system call code for read_int # reads a value of N into v0 blez $v0, done # if ( v0 < = 0 ) go to done li $t0, 0 # clear $t0 to zero loop: add $t0, $t0, $v0 # sum of integers in register $t0 addi $v0, $v0, -1 # summing in reverse order bnez $v0, loop # branch to loop if $v0 is!= zero li $v0, 4 # system call code for print_str la $a0, result # load address of message into $a0 # print the string li $v0, 1 # system call code for print_int move $a0, $t0 # a0 = $t0 # prints the value in register $a0 b main done: li $v0, 4 # system call code for print_str la $a0, bye # load address of msg. into $a0 # print the string li $v0, 10 # terminate program # return control to system MUST HAVE A BLANK LINE AT THE END OF THE TEXT FILE Translation of a switch Control Structure $s0 = 32; top: cout << Input a value from 1 to 3 cin >> $v0 switch ($v0) { case(1):{$s0 = $s0 << 1; break;} case(2):{$s0 = $s0 << 2; break;} case(3):{$s0 = $s0 << 3; break;} default: goto top; } cout << $s0.data.align 2 jumptable:.word top, case1, case2, case3 prompt:.asciiz \n\n Input a value from 1 to 3:.text top: li $v0, 4 # Code to print a string la $a0, prompt li $v0, 5 # Code to read an integer blez $v0, top # Default for less than one li $t3, 3 bgt $v0, $t3, top # Default for greater than 3 la $a1, jumptable # Load address of jumptable sll $t0, $v0, 2 # Compute word offset (multiply by 4) add $t1, $a1, $t0 # Form a pointer into jumptable lw $t2, 0($t1) # Load an address from jumptable jr $t2 # Jump to specific case switch case1: sll $s0, $s0, 1 # Shift left logical one bit b output case2: sll $s0, $s0, 2 # Shift left logical two bits b output case3: sll $s0, $s0, 3 # Shift left logical three bits output: li $v0, 1 # Code to print an integer is 1 move $a0, $s0 # Pass argument to system in $a0 # Output result

Assembler Directives To allocate space in memory for a one-dimensional array of 1024 integers, the following construct is used in the C language: int ARRAY[1024] ; In MIPS assembly language, the corresponding construct is:.data ARRAY:.space 4096 To initialize a memory array before program execution begins with a set of 16 values corresponding to the powers of 2 ( 2 N with N going from 0 to 15), the following construct is used in the C language: Int Pof2[16] ={ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768 } In MIPS assembly language the corresponding construct is:.data Pof2:.word 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768 Here is an example of how MIPS code can be written to access element two in the array and place a copy of the value in reg. $s0. The load address la macro instruction is used to initialize a pointer in $a0 with the base address of the array labeled Pof2. la $a0, Pof2 # a0 = &Pof2 lw $s0, 8($a0) # s0 = MEM[a0 + 8] A Complete Example Input/Output System Calls See Appendix A $v0 Service Call Code Arguments Results Print_integer 1 $a0 = integer Print_ string 4 $a0 = &string Read_integer 5 $v0= integer Read_string 8 $a0 = &buffer $a1 = Length of buffer Exit 10 ################################################################## # Program Name: Sum of Integers # Programmer: YOUR NAME # Date last modified: ################################################################## # Functional Description: # A program to find the Sum of the Integers from 1 to N, where N is a value # read in from the keyboard. ################################################################## # Pseudocode description of algorithm: # main: cout << \n Please input a value for N = # cin >> v0 # If ( v0 > 0 ) # {t0 = 0; # While (v0 > 0 ) do # {t0 = t0 + v0; # v0 = v0 1} # cout << The sum of the integers from 1 to N is, t0; # go to main # } # else # cout << \n **** Adios Amigo - Have a good day **** ################################################################## # Cross References:

#####################################################################.data Prompt:.asciiz \n Please Input a value for N = Result:.asciiz The sum of the integers from 1 to N is Bye:.asciiz \n **** Adios Amigo - Have a good day ****.globl main.text main: li $v0, 4 # system call code for Print String la $a0, Prompt # load address of prompt into $a0 # print the prompt message li $v0, 5 # system call code for Read Integer # reads the value of N into $v0 blez $v0, End # branch to end if $v0 < = 0 li $t0, 0 # clear register $t0 to zero Loop: add $t0, $t0, $v0 # sum of integers in register $t0 addi $v0, $v0, -1 # summing integers in reverse order bnez $v0, Loop # branch to loop if $v0 is!= zero li $v0, 4 # system call code for Print String la $a0, Result # load address of message into $a0 # print the string li $v0, 1 # system call code for Print Integer move $a0, $t0 # move value to be printed to $a0 # print sum of integers b main # branch to main End: li $v0, 4 # system call code for Print String la $a0, Bye # load address of msg. into $a0 # print the string li $v0, 10 # terminate program run and # return control to system Exercises Chapter 2 2.1 Using Appendix A, translate each of the following pseudocode expressions into MIPS assembly language: (a) t3 = t4 + t5 t6; (b) s3 = t2 / (s1 4321); (c) sp = sp 16; (d) cout << t3; (e) cin >> t0; (f) a0 = &array; (g) t8 = Mem(a0); (h) Mem(a0+ 16) = 32768; (i) cout << Hello World ; Solutions to Chap 2 Exercises label op-code Rd, Rs, Rt a: add $t3, $t4, $t5 sub $t3, $t3, $t6 b: addi $s3, $s1, -4321 div $t2, $s3 mflo $s3 c: addi $sp, $sp, -16 d: move $a0, $t3 li $v0, 1 e: li $v0, 5 move $t0, $v0

Solutions to Chap 2 Exercises label op-code Rd, Rs, Rt f: la $a0, array g: lw $t8, 0($a0) h: li $t0, 32768 sw $t0, 16($a0) i:.data Msg:.asciiz Hello World.text li $v0, 4 la $a0, Msg Solutions to Chap 2 Exercises (j) If (t0 < 0) then t7 = 0 t0 else t7 = t0; bgez $t0, else sub $t7, $0, $t0 b next else: move $t7, $t0 (k) while ( t0!= 0) { s1 = s1 + t0; t2 = t2 + 4; t0 = Mem(t2) }; while: beqz $t0, done add $s1, $s1, $t0 addi $t2, $t2, 4 lw $t0, 0($t2) b while done: Solutions to Chap 2 Exercises (l) for ( t1 = 99; t1 > 0; t1 = t1-1) v0 = v0 + t1; li $t1, 99 loop: add $v0, $v0, $t1 addi $t1, $t1, -1 bgtz $t1, loop (m) t0 = 2147483647-2147483648; li $t0, -1 (n) s0 = -1 * s0; sub $s0, $0, $s0 Exercises Chapter 2 (o) s1 = s1 * a0; mult $s1, $a0 mflo $s1 (p) s2 = srt(s0 2 + 56) / a3; mult $s0, $s0 mflo $a0 addi $a0, $a0, 56 jal srt div $v0, $a3 mflo $s2

Exercises Chapter 2 (q) s3 = s1 - s2 / s3; div $s2, $s3 mflo $t0 sub $s3, $s1, $t0 (r) s4 = s4 * 8; sll $s4, $s4, 3 2.2 Analyze the assembly language code that you developed for each of the pseudocode expressions and calculate the number of clock cycles required to fetch and execute the code corresponding to each expression. (Assume it takes one clock cycle to fetch and execute every instruction except multiply and divide, which require 32 clock cycles and 38 clock cycles respectively.) (s) s5 = 7 * s5; sll $t1, $s5, 1 sll $t2, $s5, 2 add $t1, $t1, $t2 add $s5, $s5, $t1 Exercises Continued 2.3 Show how the following expression can be evaluated in MIPS assembly language, without modifying the contents of the s registers: $t0 = ( $s1 - $s0 / $s2) * $s4 ; div $s0, $s2 mflo $t0 sub $t0, $s1, $t0 2.4 Show how the following expression can be efficiently evaluated in MIPS assembly language. $t0 = $s0/ 8 2*$s1 + $s2 sra $t0, $s0, 3 sll $t1, $s1, 1 sub $t0, $t0, $t1 add $t0, $t0, $s2 mult $t0, $s4 mflo $t0

Clock Cycles Exercises 2.3 & 2.4 Clock Cycles 2.3 div $s0, $s2 38 mflo $t0 1 sub $t0, $s1, $t0 1 mult $t0, $s4 32 mflo $t0 1 Total= 73 2.4 sra $t0, $s0, 3 1 sll $t1, $s1, 1 1 sub $t0, $t0, $t1 1 add $t0, $t0, $s2 1 Total= 4 Bonus Exercise #1 Show how the following pseudo code can be evaluated in MIPS assembly language. How many clock cycles will it take to execute your code? $s0 = 1; $s1 = &array For ($t7 = 40; $t7 > 0; $t7 = $t7 4) { $s0 = $s0 * Mem[$s1 + $t7] } Solution to for loop Exercise ############################# Clock Cycles li $s0, 1 # 1 la $s1, array # 2 li $t7, 40 # 1 loop: addu $t1, $s1, $t7 # 1 lw $t2, 0($t1) # 1 mult $s0, $t2 # 32 mflo $s0 # 1 addi $t7, $t7, -4 # 1 bgtz $t7, loop # 1 Bonus Exercise #2 Show how the following pseudo code can be evaluated in MIPS assembly language. How many clock cycles will it take to execute your code? $t1 = 40; $s1 = -2; $s2 = &array; While ($t1 > 0) { $s1 = Mem[$t1 + $s2] * $s1; $t1 = $t1 4}

Solution to while Exercise ############################ Clock Cycles li $t1, 40 # 1 li $s1, -2 # 1 la $s2, array # 2 while: addu $t7, $t1, $s2 # 1 lw $t6, 0($t7) # 1 mult $t6, $s1 # 32 mflo $s1 # 1 addi $t1, $t1, -4 # 1 bgtz $t1, while # 1 MIPS Assembly Language Programming Bob Britton Chapter 3 Number Systems Number Systems Introduction Polynomial Expansion Binary Numbers Hexadecimal Numbers Two s Complement Number System Arithmetic & Overflow Detection American Standard Code for Information Interchange (ASCII) Polynomial Expansion of a Decimal Number (Base 10) 496 = 4 x 10 + 9 x 10 + 6 x 10 10 2 1 0 Polynomial Expansion of a Binary Number (Base 2) 5 4 3 2 1 0 00101101 = 1 x 2 + 0 x 2 + 1 x 2 + 1 x 2 + 0 x 2 + 1x 2 2 A Faster Method ------ Double and Add 00101101 = 45 (1, 2, 5, 11, 22, 45)

Conversion of Decimal Numbers to Binary Divide by 2 and extract the remainder 45 Remainder 1 0 1 1 0 1 22 1 11 0 5 1 2 1 1 0 0 1 Practice - Convert 25 to Binary Divide by 2 and record the remainder 25 Remainder 12 To represent binary values in the positive and negative domains we use the Two s Complement Number System Here is the polynomial expansion of a two s complement 8-bit binary number N: 7 6 5 4 3 2 1 0 N = - d7x2 + d6x2 + d5x2 + d4x2 + d3x2 + d2x2 + d1x2 +d0x2 Notice the Minus sign!!!!!!!! The Two s Complement Operation When we take the two s complement of a binary number, the result will be the negative of the value we started with. For example, the 8-bit binary value 00011010 is 26 in decimal. To find the value negative 26 (-26) in binary we perform the two s complement operation on 00011010. Scan the binary number from right to left leaving all least significant zeros (0) and the first one (1) unchanged, and then complement the remaining digits to the left: 11100110 The result is the value negative 26 (-26) in binary. *** You need to memorize powers of 2 ***

Binary Arithmetic & Overflow Detection in the Two s Complement Number System 1111 Overflow 0000 0001 Here is an addition example where we assume we are limited to 8 binary digits. 1101 1110-3 -2-1 0 1 2 3 0010 0011 01000100 = 68 1100-4 4 0100 + 00111100 = 60 10000000 = -128 Overflow Occurred 1011-5 -6 6 5 0101 1010-7 -8 7 0110 1001 1000 0111 Binary Arithmetic in the Two s Complement Number System Here is a subtraction example where we assume we are limited to 8 binary digits. To subtract in binary we always add the two s complement of the subtrahend. 01000100 = 01000100 68-00111100 = +11000100 60 00001000 = 00001000 = 8 The Rule for Detection of Overflow ################################################# Adding numbers of opposite signs, overflow is impossible. When adding numbers of the same sign, if the result is not the same as the operands then overflow occurred. ################################################# Here is an example: You are given the following two numbers in two s complement representation. Perform the binary subtraction and indicate if there is signed overflow. Explain Why: 11101000-00010011 11101000 = -24 +11101101 = -19 11010101 Correct Result = -43

Sign Extension The value 43 as an 8-bit binary number is: 11010101 The value 43 as an 32-bit binary number is: 11111111111111111111111111010101 In Hexadecimal 43 appears as: 0xFFFFFFD5 ############################################### The value 68 as an 8-bit binary number is: 01000100 The value 68 as an 32-bit binary number is: 00000000000000000000000001000100 In Hexadecimal 68 appears as: 0x00000044 The Hexadecimal Number System Decimal Hex Binary 0 0 0000 1 1 0001 2 2 0010 3 3 0011 4 4 0100 5 5 0101 6 6 0110 7 7 0111 8 8 1000 9 9 1001 10 A 1010 11 B 1011 12 C 1100 13 D 1101 14 E 1110 15 F 1111 Here is an example of how we compactly represent binary numbers in hexadecimal: 001111001000111101111110 0x 3 C 8 F 7 E MIPS Assembly Language Programming Bob Britton Chapter 3 -b Number Systems Exercises 3.1 Convert the decimal number 35 to an 8-bit binary number. 3.2 Convert the decimal number 32 to an 8-bit binary number. 3.3 Using the double and add method convert 00010101 to a decimal number. 3.4 Using the double and add method convert 00011001 to a decimal number. 3.5 Explain why the Least Significant digit of a binary number indicates if the number is odd or even. 3.6 Convert the binary number 00010101 to a hexadecimal number. 3.7 Convert the binary number 00011001 to a hexadecimal number. 3.8 Convert the hexadecimal number 0x15 to a decimal number. 3.9 Convert the hexadecimal number 0x19 to a decimal number. 00100011 00100000 21 25 LSD is a 1 0x15 0x19 21 25 3.10 Convert the decimal number -35 to an 8-bit two s complement binary number. 11011101

Exercises 3.11 Convert the decimal number -32 to an 8-bit two s complement binary number. 3.12 Assuming the use of the two s complement number system find the equivalent decimal values for the following 8-bit binary numbers: (a) 10000001 (b) 11111111 (c) 01010000 (d) 11100000 (e) 10000011 3.13 Convert the base 8 number 204 to decimal 3.14 Convert the base 7 number 204 to decimal 3.15 Convert the base 6 number 204 to decimal 3.16 Convert the base 5 number 204 to decimal 3.17 Convert the base 10 number 81 to a base 9 number. 11100000-127 -1 80-32 -125 132 102 76 54 100 3.18 For each row of the table below convert the given 16 bit number to each Exercises of the other two bases, assuming the two s complement number system is used. 16 Bit Binary Hexadecimal Decimal 1111111100111100 1111111111111010 0xFF88 0x0011 3.19 You are given the following two numbers in two s complement representation. Perform the binary addition and indicate if there is signed overflow. Explain Why: 01101110 00011010-128 10001000 Yes overflow occurred Sign of the result is different from the operands -25 Exercises Exercises 3.20 You are given the following two numbers in two s complement representation. Perform the binary subtraction and indicate if there is signed overflow. Explain Why: 11101000-00010011 3.21 Sign extend the 8 bit hex number 0x88 to a 16 bit number. 0x FF88 3.22 The following subtract instruction is located at address 0x00012344. What are the two possible values for the contents of the PC after the branch instruction executed? 0x 00012340 0x 0001234C This branch instruction is described in Appendix C. loop: addi $t4, $t4, -8 11101000 + 11101101 11010101 No Overflow sub $t2, $t2, $t0 3.23 You are given the following two 8-bit binary numbers in the two s complement number system. What values do they represent in decimal? X = 10010100 = -108 Y = 00101100 = 44 2 10 2 10 Perform the following arithmetic operations on X and Y. Show your answers as 8-bit binary numbers in the two s complement number system. To subtract Y from X, find the two s complement of Y and add it to X. Indicate if overflow occurs in performing any of these operations. X+Y X-Y Y-X 10010100 10010100 00101100 00101100 +11010100 +01101100 11000000 01101000 10011000 bne $t4, $t2,loop

Exercise 3.24 The following code segment is stored in memory starting at memory location 0x00012344. What are the two possible values for the contents of the PC after the branch instruction has executed? 0x 00012344 0x 00012354 Add in line pseudocode to describe each instruction. loop: lw $t0, 0($a0) # addi $a0, $a0, 4 # andi $t1, $t0, 1 # beqz $t1, loop # t0 = Mem[a0] a0 = a0 +4 t1 = t1 & 1 Extract LSD if t0 is even go to loop Example Quiz You are given the following two 8 bit binary numbers in the two s complement number system. What values do they represent in decimal? X= 10010100 = 2 Y= 00101100 = 2 Perform the following arithmetic operations on X and Y. Show your answers as 8 bit binary numbers in the two s complement number system. To subtract Y from X find the two s complement of Y and add it to X. Indicate if overflow occurs in performing any of these operations. X+Y X-Y Y-X 10010100 10010100 00101100 00101100