Sunday, November 7, 2010

Translation of common C constructs to MSP430 assembly code

Local Variable

                                                   
        Consider a C program which contain only one statement, assigning a local variable i to 100. The assembly code also contain only one statement. Move the value 100 to the stack.

Static Variables
         In this C program a variable i is declared as static and assign a value 100 to it. Then another value 200 assign to this value. In the assembly code we can find that the value 100 is stored in RAM and when assigning value 200, this value is replaced.
        In the assembly code mov #200, &i.1194 moves the value 200 to the address of &i.1194. If we check the address of i.1194 we can find that it is the address of RAM. And importantly the variable declared as static is defined outside the main in assembly code.
Function with Parameters

        This is the C program. There is a function fun which accepts two integers and return their sum. In the main we are calling fun(1,2).
Now go through the assembly code. First consider the main:
Here the value 1 and 2 are moved to registers r15 and r14 respectively. Then calling the address of fun. In the fun:
first moving the value in register r15 to the address in r4( r4 contain the address of stack).Then taking another position of stack to store the value of r14 and adding these two values of stack and store it in r15.Then returning this address to the main.


POINTER TO INTEGER
        This is the C program. An integer i is assigned to 10 and a pointer to an integer pointing to the address of i. Then assigning a value 20 to i using the pointer. The assembly code is given below.
        R4 contain the starting address of stack. At first the value 10 is moved to  2 positions next to the address in r4. Then the value in r4 is copied to r15. Adding 2 with the address of r15 gives the address of the variable i and moving the value 20 to the address stored in r15.

POINTER TO FUNCTION

        This is the C program. In this there is a pointer to a function 'fun' which returns void and taking no arguments. The function fun is not doing anything.
 Following is the assembly code.
        Here r4 contain the address of stack. To this address the address of the function fun is copied. The address in r4 is then moved to register r15. Then calling r15 will actually calls the function fun. Since there is nothing to do in the fun it just pushes the return address and then pop the return address and go back to main.

No comments:

Post a Comment