In this lab you are expected to compare the source code and
In this lab, you are expected to compare the source code and assembly code for the following C code. (you can get the assembly code with usually –s flag). Can you see any optimizations that can be done on the assembly code?
int a=1, b=2, c=3;
int proc1 (int a, int b, int c)
{ If (a>0)
return b – c;
else return b + c; }
int main()
{ int w, x, y;
w = proc1 (a, b, c);
switch (w) {
case 0: x=3; break;
case 1: x=4; break;
case 2: x=7; break;
default: x=9; break; }
y= w + x;
return 0; }
- Please include your (well- commented) assembly code and your explanation of what this program does and how assembly code can be optimized.
- Include your test results with several screenshots.
Solution
Answer:
MIPS Assembly Language Code:
L0:
 push rbp
 mov rbp, rsp
 mov DWORD PTR [rbp-4], edi
 mov DWORD PTR [rbp-8], esi
 mov DWORD PTR [rbp-12], edx
 cmp DWORD PTR [rbp-4], 0
 jle .L2
 mov eax, DWORD PTR [rbp-8]
 sub eax, DWORD PTR [rbp-12]
 jmp .L3
 .L2:
 mov edx, DWORD PTR [rbp-8]
 mov eax, DWORD PTR [rbp-12]
 add eax, edx
 .L3:
 pop rbp
 ret
 main:
 push rbp
 mov rbp, rsp
 sub rsp, 32
 mov DWORD PTR [rbp-8], 1
 mov DWORD PTR [rbp-12], 2
 mov DWORD PTR [rbp-16], 3
 mov edx, DWORD PTR [rbp-16]
 mov ecx, DWORD PTR [rbp-12]
 mov eax, DWORD PTR [rbp-8]
 mov esi, ecx
 mov edi, eax
 call L0
 mov DWORD PTR [rbp-20], eax
 mov eax, DWORD PTR [rbp-20]
 cmp eax, 1
 je .L6
 cmp eax, 2
 je .L7
 test eax, eax
 jne .L11
 mov DWORD PTR [rbp-4], 3
 jmp .L9
 .L6:
 mov DWORD PTR [rbp-4], 4
 jmp .L9
 .L7:
 mov DWORD PTR [rbp-4], 7
 jmp .L9
 .L11:
 mov DWORD PTR [rbp-4], 9
 nop
 .L9:
 mov edx, DWORD PTR [rbp-20]
 mov eax, DWORD PTR [rbp-4]
 add eax, edx
 mov DWORD PTR [rbp-24], eax
 mov eax, 0
 leave
 ret


