C or C++ References in MIPS Inline Assembly

Inline assembly statements refer to C or C++ expressions and objects in several ways:

  • Arguments in an __asm statement

    Inline assembly statements cannot refer to C or C++ expressions using direct reference such as the following:

    int myint = 0;
    __asm("add v0, a0, myint"); // error: Undefined symbol in expression.
    

    Instead, pass the value of the C or C++ expression as arguments in an __asm statement. The following example shows how to do this.

    int myint = 0;
    __asm("add v0, a0, %0", myint);
    

    You can pass multiple arguments to the __asm statement. The following example shows how to pass multiple arguments.

    #include <stdio.h>
    int sum(a, b)
    {
        return a+b;
    }
    int main()
    {
        int myint = 100;
        int result;
        __asm("add v0, %0, %1", myint, sum(200, 300));
        __asm("sw v0, 0(%0)", &result);
        printf("result = %d\n", result);
        return 0;
    }
    
  • Code label or object

    Any code label or object, except for static labels, can be passed as an argument to an __asm string in which the arguments are represented by the placeholders %0, %1, %2, and so on. . For example, both of the following _asm statements are valid:

    __asm("add %0, %1", sum, val * base); 
    __asm("swl %t0, (%0)", &buffer [3]); 
    

The compiler evaluates an __asm string with arguments in the same way it evaluates a function call. The compiler first generates instructions that load the indicated expressions as arguments. It handles arguments in an __asm statement in the same manner as function arguments, which are defined by a platform's calling standard.

After the compiler generates instructions to load the arguments, if any, it assembles the actual instruction itself. A single instruction in an __asm statement may therefore cause multiple instructions to be generated. Judicious use of the argument placeholders enables you to control the order of evaluation. Expressions are evaluated in the order in which they are passed to the __asm statement. For example, consider the following __asm statement:

__asm("add %1, %0", height * get_coord (&i), arr[i]); 

In this statement, the expression height * get_coord (&i) is evaluated first, and therefore might affect the value of the later expression arr[i]. The placeholders %0 and %1 can appear in any order in the instruction string.

Because the __asm statement follows the standard MIPS calling conventions, and because each individual __asm statement is treated as a function call, you do not need to worry about preserving arguments in the current function. The __asm statements do not corrupt the arguments in the surrounding function.

See Also

The _asm Keyword in MIPS Inline Assembly | MIPS __asm Statement Registers | Restrictions to MIPS __asm Statements

 Last updated on Thursday, April 08, 2004

© 1992-2003 Microsoft Corporation. All rights reserved.