mtrn
mtrn

Reputation: 35

C to MIPS translate

Here i have been given an exam question that i partly solved but do not understand it completely why it is used volatile here? and the missing expression i have must be switches >>8. when it comes to translation i have some difficulty.

Eight switches are memory mapped to the memory address 0xabab0020, where the least significant bit (index 0) represents switch number 1 and the bit with index 7 represents switch number 8. A bit value 1 indicates that the switch is on and 0 means that it is off. Write down the missing C code expression, such that the while loop exits if the toggle switch number 8 is off.

 volatile int * switches = (volatile int *) 0xabab0020;
 volatile int * leds = (volatile int *) 0xabab0040;
 while(/* MISSING C CODE EXPRESSION */){
   *leds = (*switches >> 4) & 1;
}

Translate the complete C code above into MIPS assembly code, including the missing C code expression. You are not allowed to use pseudo instructions.

Upvotes: 0

Views: 391

Answers (3)

Adam
Adam

Reputation: 846

volatile int * switches = (volatile int *) 0xabab0020;
volatile int * leds = (volatile int *) 0xabab0040;
  while((*switches >> 8) & 1){
    *leds = (*switches >> 4) & 1;
}

To mips

     lui   $s0,0xabab    #load the upper half
     ori   $s0,0x0020

     lui   $s1,0xabab
     ori   $s1,0x0040
while:
     lw    $t0,0x20($s0)
     srl   $t0,$t0,8     #only the 8th bit is important
     andi  $t0,$t0,1     # clear other bit keep the LSB
     beq   $t0,$0, done
     lw    $t1,0x40($s1)
     srl   $t1,$t1,4
     andi  $t1,$t1,1
     sw    $t1,0x40($s1) 
     j     while
done:
     sw    $t0,0x20($s0)  

Upvotes: 0

old_timer
old_timer

Reputation: 71526

without volatile your code can legally be interpreted by the compiler as:

int * switches = (volatile int *) 0xabab0020;
int * leds = (volatile int *) 0xabab0040;
*leds = (*switches >> 4) & 1;
while(/* MISSING C CODE EXPRESSION */){
}

Upvotes: 2

markgz
markgz

Reputation: 6266

The volatile qualifier is an indication to the C compiler that the data at addresses switches and leds can be changed by another agent in the system. Without the volatile qualifier, the compiler would be allowed to optimize references to these variables away.

The problem description says the loop should run while bit 7 of *switches is set, i.e: while (*switches & 0x80 != 0)

Translating the code is left as an exercise for the reader.

Upvotes: 1

Related Questions