Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Today’s Lecture • Homework #2 • Midterm I Feb 22 (in class closed book) Outline • Assembly Programming Reading Chapter 2, Appendix B MIPS Assembly Language Computer Science 104 Lecture 6 © Alvin R. Lebeck Review: A Program CPS 104 Review: What Must be Specified? 2n-1 #include <iostream.h> Instruction Stack main() { int *a = new int[100]; int *p = a; int k; Fetch Instruction .cc file Fetch Data CPS 104 Store Rs 3 26 25 © Alvin R. Lebeck Op Rt Rs 11 10 6 5 shamt Rd • Logical func AND, OR, SHIFT 16 15 • Data Transfer 0 load, store MIPS is LOAD/STORE architecture immediate Rt • Conditional Branch 26 25 Op implement if, for, while… statements 0 target • Unconditional Jump support method invocation (procedure calls) Terminology Op = opcode Rs, Rt, Rd = register specifier © Alvin R. Lebeck 4 add, sub, mul, etc 0 J-type: Jump / Call 31 CPS 104 • Arithmetic 16 15 21 20 jumps, conditions, branches • fetch-decode-execute is implicit! Review: MIPS ISA Categories I-type: Register-Immediate 31 what are supported • Successor instruction Instruction R-type: Register-Register Op • Data type and Size • Operations Next Reserved Review: MIPS Instruction Formats 21 20 where other than memory? how many explicit operands? how are memory operands located? which can or cannot be in memory? Result Text 0 © Alvin R. Lebeck Execute add r,s1,s2 } 26 25 how do we tell what operation to perform? • Location of operands and result Operand bits cout << "entry 3 = " << a[3] << endl; 31 • Instruction Format Decode for (k = 0; k < 100; k++) { *p = k; p++; } 2 CPS 104 5 © Alvin R. Lebeck CPS 104 6 Instructions for Procedure Call and Return MIPS Arithmetic Instructions 0x10000 addi $1, $0, 43 0x10004 addi $2, $0, 2 0x10008 jal 0x30408 0x1000c ?? int equal(int a1, int a2) { int tsame; tsame = 0; if (a1 == a2) tsame = 1; return(tsame); } main() { int x,y,same; x = 43; y = 2; same = equal(x,y); // other computation } 0x30408 0x3040c 0x30410 0x30414 addi $3, $0, 0 bne $1, $2, 4 addi $3, $0, 1 jr $31 PC 0x10000 0x10004 0x10008 0x30408 0x3040c 0x30410 0x30414 0x1000c © Alvin R. Lebeck $31 ?? ?? ?? 0x1000c 0x1000c 0x1000c 0x1000c 0x1000c CPS 104 Instruction Example Meaning Comments add subtract add immediate add unsigned subtract unsigned add imm. unsign. multiply multiply unsigned divide add $1,$2,$3 sub $1,$2,$3 addi $1,$2,100 addu $1,$2,$3 subu $1,$2,$3 addiu $1,$2,100 mult $2,$3 multu $2,$3 div $2,$3 divide unsigned divu $2,$3 Move from Hi Move from Lo mfhi $1 mflo $1 $1 = $2 + $3 $1 = $2 – $3 $1 = $2 + 100 $1 = $2 + $3 $1 = $2 – $3 $1 = $2 + 100 Hi, Lo = $2 x $3 Hi, Lo = $2 x $3 Lo = $2 ÷ $3, Hi = $2 mod $3 Lo = $2 ÷ $3, Hi = $2 mod $3 $1 = Hi $1 = Lo 3 operands 3 operands + constant 3 operands 3 operands + constant 64-bit signed product 64-bit unsigned product Lo = quotient, Hi = remainder Unsigned quotient Usigned remainder Used to get copy of Hi Used to get copy of Lo Which add for address arithmetic? Which for integers? 7 © Alvin R. Lebeck MIPS Logical Instructions Instruction and or xor nor and immediate or immediate Example and $1,$2,$3 or $1,$2,$3 xor $1,$2,$3 nor $1,$2,$3 andi $1,$2,10 ori $1,$2,10 Meaning $1 = $2 & $3 $1 = $2 | $3 $1 = $2 ⊕ $3 $1 = ~($2 | $3) $1 = $2 & 10 $1 = $2 | 10 Comment Bitwise AND Bitwise OR Bitwise XOR Bitwise NOR Bitwise AND reg, const Bitwise OR reg, const xor immediate shift left logical shift right logical shift right arithm. shift left logical shift right logical shift right arithm. xori $1, $2,10 sll $1,$2,10 srl $1,$2,10 sra $1,$2,10 sllv $1,$2,$3 srlv $1,$2, $3 srav $1,$2, $3 $1 = ~$2 &~10 $1 = $2 << 10 $1 = $2 >> 10 $1 = $2 >> 10 $1 = $2 << $3 $1 = $2 >> $3 $1 = $2 >> $3 Bitwise XOR reg, const Shift left by constant Shift right by constant Shift right (sign extend) Shift left by var Shift right by var Shift right arith. by var CPS 104 8 MIPS Data Transfer Instructions Instruction SW R3, 500(R4) SH R3, 502(R2) SB R2, 41(R3) Comment Store word Store half Store byte LW R1, 30(R2) LH R1, 40(R3) LHU R1, 40(R3) LB R1, 40(R3) LBU R1, 40(R3) LUI R1, 40 Load word Load halfword Load halfword unsigned Load byte Load byte unsigned Load Upper Immediate (16 bits shifted left by 16) Why do we need LUI? LUI R5 R5 © Alvin R. Lebeck CPS 104 9 MIPS Compare and Branch if R[rs] == R[rt] then PC-relative branch bne rs, rt, offset branch on not eq. <> set on less than Compare to zero and Branch blez bgtz rs, offset rs, offset bltz rs, offset bgez rs, offset bltzal rs, offset bgeal rs, offset if R[rs] <= 0 then PC-relative branch > set less than imm. set less than uns. < set l. t. imm. uns. >= if R[rs] < 0 then branch and link (into R 31) >= jump jump register • Remaining set of compare and branch take two instructions • Almost all comparisons are against zero! © Alvin R. Lebeck CPS 104 CPS 104 10 MIPS jump, branch, compare instructions Instruction branch on equal Compare and Branch beq rs, rt, offset © Alvin R. Lebeck 0000 … 0000 jump and link 11 © Alvin R. Lebeck Example Meaning beq $1,$2,100 if ($1 == $2) go to PC+4+100 Equal test; PC relative branch bne $1,$2,100 if ($1!= $2) go to PC+4+100 Not equal test; PC relative slt $1,$2,$3 if ($2 < $3) $1=1; else $1=0 Compare less than; 2’s comp. slti $1,$2,100 if ($2 < 100) $1=1; else $1=0 Compare < constant; 2’s comp. sltu $1,$2,$3 if ($2 < $3) $1=1; else $1=0 Compare less than; natural numbers sltiu $1,$2,100 if ($2 < 100) $1=1; else $1=0 Compare < constant; natural numbers j 10000 go to 10000 Jump to target address jr $31 go to $31 For switch, procedure return jal 10000 $31 = PC + 4; go to 10000 For procedure call CPS 104 12 Signed v.s. Unsigned Comparison Assembler and Assembly Language R1= 0…00 0000 0000 0000 0001 R2= 0…00 0000 0000 0000 0010 R3= 1…11 1111 1111 1111 1111 • After executing these instructions: slt r4,r2,r1 slt r5,r3,r1 sltu r6,r2,r1 sltu r7,r3,r1 • Machine language is a sequence of binary words. • What are values of registers r4 - r7? Why? r4 = ; r5 = ; r6 = ; r7 = ; program © Alvin R. Lebeck • Assembly language is a text representation for machine language plus extras that make assembly language programming easier (more readable too!). CPS 104 13 CPS 104 move $2, $4 add $2, $4, $0 15 li $8, 40 addi $8, $0, 40 # $8 = 40, (load 40 into $8) sd $4, 0($29) sw $4, 0 ($29) sw $5, 4($29) # mem[$29] = $4; Mem[$29+4] = $5 la $4, 0x1000056c lui $4, 0x1000 ori $4, $4, 0x056c # Load address $4 = <address> © Alvin R. Lebeck CPS 104 16 A Simple Program • Directives: tell the assembler what to do... • Format “.”<string> [arg1], [arg2] . . . • Add two numbers x & y together .text .align 2 main: la $3, lw $4, la $7, lw $5, add $6, st $6, jr $31 • Examples .data [address] # start a data segment. # [optional begining address] .text [address] # start a code segment. .align n # align segment on 2n byte boundary. .ascii <string> # store a string in memory. .asciiz <string> # store a null terminated string in memory .word w1, w2, . . . , wn # store n words in memory. CPS 104 14 # $2 = $4, (copy $4 to $2) Tranlates to: Assembly Language (cont.) © Alvin R. Lebeck executable code • Pseudo-instructions: extend the instruction set for convenience (not real hardware primitives) • Examples [# comment] [# comment] CPS 104 Linker Assembly Language (cont.) • One instruction per line. • Numbers are base-10 integers or Hex w/ leading 0x. • Identifiers: alphanumeric, _, . string starting in a letter or _ • Labels: identifiers starting at the beginning of a line followed by “:” • Comments: everything following # till end-of-line. • Instruction format: Space and “,” separated fields. © Alvin R. Lebeck Assembler © Alvin R. Lebeck MIPS Assembly Language [Label:] <op> reg1, [reg2], [reg3] [Label:] <op> reg1, offset(reg2) .Directive [arg1], [arg2], . . . compiler .data .align 2 x: .word 10 y: .word 3 17 © Alvin R. Lebeck x 0($3) y 0($7) $4, $5 0($3) # # # # # # # # # # declare text segment align it on 4-byte boundary label for main load address of x into R3 (pseudo-inst) load value of x into R4 load address of y into R3 (pseudo-inst) load value of y into R5 compute x+y store value to x return to calling routine # declare data segment # align it on 4-byte boundary # initialize x to 10 # initialize y to 3 CPS 104 18 Typical Code Segments-IF Typical Code Segments-IF Else if (x != y) then x = x + y; else x = x-y; if (x != y) then x = x + y; # $4 has x $5 has y beq $4, $5, eq eq: add st jr $6, $4, $5 $6, 0($3) $31 © Alvin R. Lebeck # check if x != y # $4 has x $5 beq add b done eq: sub done: st jr # compute x+y # store value to x # return to calling routine CPS 104 19 has y $4, $5, eq $6, $4, $5 $6, $5, $4 $6, 0($3) $31 © Alvin R. Lebeck The C code # check if x != y # compute x+y # compute x-y # store value to x # return to calling routine CPS 104 20 System Call Instruction • System call is used to communicate with the operating system, and request services (memory allocation, I/O) • Load system call code (value) into Register $v0 • Load arguments (if any) into registers $a0, $a1 or $f12 (for floating point). • do: syscall • Results returned in registers $v0 or $f0. • Note: $v0 = $2, $a0=$4, $a1 = $5 #include <iostream.h> int main ( ) { int i; int sum = 0; for(i=0; i <= 100; i++) sum = sum + i*i ; printf(“The answer is %d\n“, sum); } Let’s write the assembly … :) © Alvin R. Lebeck CPS 104 21 © Alvin R. Lebeck SPIM System Call Support code 1 2 3 4 5 6 7 8 9 10 service print print print print read read read read sbrk exit © Alvin R. Lebeck Arguments int float double string integer float double string $a0=amount CPS 104 CPS 104 23 Echo number and string Result $a0 $f12 $f12 $a0 (string address) integer in $v0 float in $f0 double in $f0 $a0=buffer, $a1=length address in $v0 .text main: li $v0, 5 syscall move $a0, $v0 24 # code to read an integer # do the read (invokes the OS) # copy result from v0 to a0 li $v0, 1 syscall # code to print an integer # print the integer li $v0, 4 la $a0, nln syscall # code to print string # address of string (newline) © Alvin R. Lebeck CPS 104 25 Example2 Echo Continued li $v0, la $a0, li $a1, syscall la $a0, li $v0, syscall jr 8 name 8 # code to read a string # address of buffer (name) # size of buffer (8 bytes) name 4 # address of string to print # code to print a string $31 Task: sum together the integers stored in memory .text .align .globl main: list: msg: nln: .data .align 2 name: .word 0,0 nln: .asciiz "\n" CPS 104 26 © Alvin R. Lebeck change tsame to same • Recursion • Arguments and Return Value (functions) Assembly Level • Must bridge gap between HLL and ISA • Supporting Local Names • Passing Arguments (arbitrary number?) $31 ?? ?? ?? 0x1000c 0x1000c 0x1000c 0x1000c 0x1000c CPS 104 27 ISA Level • call and return instructions C++ Level • Local Name Scope addi $3, $0, 0 bne $1, $2, 4 addi $3, $0, 1 jr $31 PC 0x10000 0x10004 0x10008 0x30408 0x3040c 0x30410 0x30414 0x1000c CPS 104 Procedure Call GAP 0x10000 addi $1, $0, 43 0x10004 addi $2, $0, 2 0x10008 jal 0x30408 0x1000c ?? 0x30408 0x3040c 0x30410 0x30414 .data # Start of data segment .word 35, 16, 42, 19, 55, 91, 24, 61, 53 .asciiz "The sum is " .asciiz "\n" © Alvin R. Lebeck Review: Procedure Call and Return int equal(int a1, int a2) { int tsame; tsame = 0; if (a1 == a2) tsame = 1; return(tsame); } main() { int x,y,same; x = 43; y = 2; same = equal(x,y); // other computation } # Code # align on word boundary # declare main # MAIN procedure Entrance # fill in what goes here # return © Alvin R. Lebeck 2 main 28 © Alvin R. Lebeck Supporting Procedures CPS 104 29 Procedure Call (Stack) Frame • What data structure? • Procedures use a frame in the stack to: Hold values passed to procedures as arguments. Save registers that a procedure may modify, but which the procedure’s caller does not want changed. To provide space for local variables. (variables with local scope) To evaluate complex expressions. © Alvin R. Lebeck CPS 104 30 © Alvin R. Lebeck CPS 104 31 Call-Return Linkage: Stack Frames ARGS Review: A Program Argument 6 Argument 5 Callee Save Registers (old FP, RA) for (k = 0; k < 100; k++) { *p = k; p++; } Local Variables Grows and shrinks during expression evaluation Dynamic area SP CPS 104 MIPS Register Naming Conventions zero constant 0 16 s0 callee saves 1 at ... 2 v0 expression evaluation & 23 s7 3 v1 function results 24 t8 4 a0 arguments 25 t9 5 a1 26 k0 reserved for OS kernel 6 a2 27 k1 7 a3 28 gp Pointer to global area 8 t0 reserved for assembler temporary: caller saves 0 © Alvin R. Lebeck Reserved CPS 104 33 Calling Procedure • Step-1: Setup the arguments: The first four arguments (arg0-arg3) are passed in registers $a0-$a3 Remaining arguments are pushed onto the stack (in reverse order arg5 is at the top of the stack). • Step-2: Save caller-saved registers • Step-3: Execute a jal instruction. 29 sp Stack pointer 30 fp frame pointer 31 ra Return Address (HW) CPS 104 34 MIPS/GCC Procedure Calling Conventions (cont.) Called Routine • Step-1: Establish stack frame. © Alvin R. Lebeck CPS 104 35 MIPS/GCC Procedure Calling Conventions (cont.) On return from a call • Step-1: Put returned values in registers $v0, [$v1]. (if values are returned) • Step-2: Restore callee-saved registers. Subtract the frame size from the stack pointer. subiu $sp, $sp, <frame-size> Typically, minimum frame size is 32 bytes (8 words). Restore $fp and other saved registers. [$ra, $s0 - $s7] • Step-2: Save callee saved registers in the frame. • Step-3: Pop the stack Register $fp is always saved. Register $ra is saved if routine makes a call. Registers $s0-$s7 are saved if they are used. Add the frame size to $sp. addiu $sp, $sp, <frame-size> • Step-4: Return • Step-3: Establish Frame pointer Jump to the address in $ra. jr $ra Add the stack <frame size> - 4 to the address in $sp addiu $fp, $sp, <frame-size> - 4 CPS 104 Text add r,s1,s2 Save registers $t0-$t9 if they contain live values at the call site. 15 t7 © Alvin R. Lebeck Data MIPS/GCC Procedure Calling Conventions temporary (cont’d) ... © Alvin R. Lebeck bits cout << "entry 3 = " << a[3] << endl; 32 0 .cc file } Low Mem © Alvin R. Lebeck Stack main() { int *a = new int[100]; int *p = a; int k; Arguments and local variables at fixed offset from FP FP 2n-1 #include <iostream.h> High Mem 36 © Alvin R. Lebeck CPS 104 37 Example2 (cont.) Example2 # # Example for CPS 104 # Program to add together list of 9 numbers. .text # Code .align 2 .globl main main: # MAIN procedure Entrance subu $sp, 40 #\ Push the stack sw $ra, 36($sp) # \ Save return address sw $s3, 32($sp) # \ sw $s2, 28($sp) # > Entry Housekeeping sw $s1, 24($sp) # / save registers on stack sw $s0, 20($sp) # / move $v0, $0 #/ initialize exit code to 0 move $s1, $0 #\ la $s0, list # \ Initialization la $s2, msg # / la $s3, list+36 #/ © Alvin R. Lebeck CPS 104 38 Example2 (cont.) # # list: msg: nln: © Alvin R. Lebeck $v0, $s0, $s1, $s2, $s3, $ra, $sp, $ra main $t6, 0($s0) $s1, $s1, $t6 li move syscall li move syscall li la syscall $v0, 4 $a0, $s2 addu bne $s0, $s0, 4 $s0, $s3, again $v0, 1 $a0, $s1 $v0, 4 $a0, nln © Alvin R. Lebeck $0 20($sp) 24($sp) 28($sp) 32($sp) 36($sp) 40 #\ index update and #/ end of loop CPS 104 39 • Register zero always has the value zero even if you try to write it #\ # \ # \ # \ Closing Housekeeping # / restore registers # / load return address # / Pop the stack #/ exit(0) ; # end of program • Branch (al) and jal instructions put the return address PC+4 into the link register • All instructions change all 32 bits of the destination register (lui, lb, lh) and read all 32 bits of sources (add, sub, and, or, …) • Immediate arithmetic and logical instructions are extended as follows: Data Segment logical immediates are zero extended to 32 bits arithmetic immediates are sign extended to 32 bits .data # Start of data segment .word 35, 16, 42, 19, 55, 91, 24, 61, 53 .asciiz "The sum is " .asciiz "\n" CPS 104 • lb and lh extend data as follows: lbu, lhu are zero extended lb, lh are sign extended 40 © Alvin R. Lebeck Miscellaneous MIPS Instructions CPS 104 CPS 104 41 Summary break A breakpoint trap occurs, transfers control to exception handler syscall A system trap occurs, transfers control to exception handler coprocessor instrs Support for floating point. TLB instructions Support for virtual memory: discussed later restore from exception Restores previous interrupt mask & kernel/user mode bits into status register load word left/right Supports unaligned word loads store word left/right Supports unaligned word stores © Alvin R. Lebeck # Begin main loop #\ #/ Actual "work" # SPIM I/O #\ # > Print a string #/ #\ # > Print a number #/ #\ # > Print a string (eol) #/ lw addu Details of the MIPS instruction sets Exit Code move lw lw lw lw lw addu jr .end Main code segment again: 42 • Assembler Translates Assembly to Machine code • Pseudo Instructions • System Call • Procedure Calls Next Time • Recursion, Other Instruction Sets Reading • Ch. 2, Appendix B © Alvin R. Lebeck CPS 104 43