Back to CSCI 255
In the Fall 2015 offering of CSCI 255,
Homework 10 required a few of you to
rewrite a C routine, bubblepass
,
into MIPS32 assembly language.
Here’s a copy of the C version of bubblepass
.
int bubblePass(int V[], int n) { int i ; int swappedCount = 0 ; for (i=0; i < n-1; ++i) { if (V[i] > V[i+1]) { int tmpSwapVar; tmpSwapVar = V[i] ; V[i] = V[i+1] ; V[i+1] = tmpSwapVar ; swappedCount++ ; } } return swappedCount ; }
A compiler-generated solution
If you use gcc on a MIPS32processor
running Linux
to generate MIPS32 assembly language
for this routine, the following
code is obtained. (In this example, registers have been renamed
from their numeric names, $5
, to their symbolic
names, $a1
.
Also, this code was generated at optimization level 2.)
.file 1 "bubblepass.c" .section .mdebug.abi32 .previous .gnu_attribute 4, 3 .abicalls .text .align 2 .globl bubblePass .set nomips16 .ent bubblePass .type bubblePass, @function bubblePass: .frame $sp,0,$ra # vars= 0, regs= 0/0, args= 0, gp= 0 .mask 0x00000000,0 .fmask 0x00000000,0 .set noreorder .set nomacro addiu $a1,$a1,-1 blez $a1,$L9 move $v0,$zero move $v1,$zero $L4: lw $a2,0($a0) lw $a3,4($a0) addiu $v1,$v1,1 slt $t1,$a3,$a2 beq $t1,$zero,$L3 slt $t0,$v1,$a1 sw $a3,0($a0) sw $a2,4($a0) addiu $v0,$v0,1 $L3: bne $t0,$zero,$L4 addiu $a0,$a0,4 $L9: j $ra nop .set macro .set reorder .end bubblePass .size bubblePass, .-bubblePass .ident "GCC: (GNU) 4.6.2"
Compiler-generated x86-64 code
You can also ask gcc to generate, also at optimization level 2, x86-64 assembly code.
.file "bubblepass.c" .text .p2align 4,,15 .globl bubblePass .type bubblePass, @function bubblePass: .LFB0: .cfi_startproc subl $1, %esi testl %esi, %esi jle .L5 xorl %edx, %edx xorl %eax, %eax .p2align 4,,10 .p2align 3 .L4: movl (%rdi,%rdx,4), %ecx movl 4(%rdi,%rdx,4), %r8d cmpl %r8d, %ecx jle .L3 movl %r8d, (%rdi,%rdx,4) movl %ecx, 4(%rdi,%rdx,4) addl $1, %eax .L3: addq $1, %rdx cmpl %edx, %esi jg .L4 rep ret .L5: xorl %eax, %eax ret .cfi_endproc .LFE0: .size bubblePass, .-bubblePass .ident "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4" .section .note.GNU-stack,"",@progbits
Now that is pretty succinct: only eighteen instructions!
The Task
It’s not as hard as you might think. Look at the C code. Look at the x86-64 assembly code. Figure out how the registers of the x86-64 code correspond to the variables of the C code. Figure out how the instructions of the x86-64 code implement the statements of the C code.
Download a copy of the x86-64 code, load it into your favorite text editor, and annotate the x86-64 code with what you figured out in the previous paragraph. Finally upload your annotated x86-64 code to the Homework 11 moodle page. You can upload a text file or a PDF file.