Search code examples
cmipsmips32

C to Mips conversion nested functions which registers to save on stack?


Im trying to work on my school project but Im having difficulty translating nested functions from c to mips , Im specifically confused about which variables considered will be trashed by the inside function get New so that I need to save them on stack . So in example I have this function I need to translate :

which variables I need to save on stack while translating this function since there is another function called get New inside . I know that get New will be trashing $ r a return address so I need to save $ r a on stack for sure . What about p t r X , p t r Y and arguments ? how do I know which ones will be trashed by get New ?

int moveRobots(int *arg0, int *arg1, int arg2, int arg3)
{
  int i, *ptrX, *ptrY, alive = 1;

ptrX = arg0;
ptrY = arg1;

for (i=0;i<4;i++) {
*ptrX = getNew(*ptrX,arg2);  
*ptrY = getNew(*ptrY,arg3); 


if ((*ptrX == arg2) && (*ptrY == arg3)) {
  alive = 0;
  break;
}
ptrX++;
ptrY++;
   }
    return alive;
 }

and here is the getNew function

 int getNew(int arg0, int arg1)
 {
 int temp, result;

 temp = arg0 - arg1;
  if (temp >= 10)
    result = arg0 - 10;
  else if (temp > 0)
    result = arg0 - 1;
  else if (temp == 0)
    result = arg0;
  else if (temp > -10)
    result = arg0 + 1;
   else if (temp <= -10)
    result = arg0 + 10;

   return result;
    } 

Solution

  • First of all, welcome to stackoverflow!

    It looks like you are talking about a calling convention.

    As Michael said in comments, if you are translating getNew code then it will be up to you. If not, you will have to know which convention is getNew following.

    If your case is the first one: Then, according to this calling convention, in MIPS32 you must preserve $fp and $gp and if you use $s registers (s stands for saved temporaries) you MUST preserve them on the callee to avoid unexpected behaviours. In addition to this, if you are using $t registers (t stands for temporaries) the caller must save them before calling to another function.

    So, in your case, getNew should save $s registers if it's using them and moveRobots should save $t registers if it's using them.

    For a more complete explanation read this: link.

    Hope this helps!