Simple C function to MIPS instructions

2019-08-04 09:47发布

问题:

I have a simple c function that I need to convert to MIPS instructions for a homework assignment.

The function is:

int load(int *ptr) {
     return *ptr;
}

my MIPS instruction I've come up with is:

load:
     move $v0,$a0
     jr $ra

Is this correct?

回答1:

Let's analyze the function for a second.

First of all, what are the types of everything involved here?

  • ptr is a pointer to an int.
  • the return value should be of type int.

Next, what does the function do with this?

  • dereferences the int pointer (i.e., reads the int value that the pointer is pointing to) ptr and returns that value.

Next consider what your code is doing.

  • you moved the argument to the return value.
  • return from the function.

Is this correct?

I'd say no. You've essentially returned the pointer, not the value that the pointer was pointing to.

What can you do about it?

Well remember the types that we're dealing with here and what you did with it. You have your argument (of type int *) and you return that (of type int). The types do not match. What did we do in the C program? We dereferenced the pointer to get the value. In other words, converted the int * to an int. You need to do the same.



标签: c assembly mips