Using the .macro Directive

The .macro directive is part of the first line of a macro definition. Every macro definition ends with the .endm directive . Macro Definition Syntax: .macro Directive shows the full syntax, and Syntax Elements: .macro Directive explains the syntax elements.

Listing 1. Macro Definition Syntax: .macro Directive
name: .macro  [ 
parameter ] [ ,
parameter ] ...
macro_body

.endm
Table 1. Syntax Elements: .macro Directive
Element Description
name Label that invokes the macro.
parameter Operand the assembler passes to the macro for us in the macro body.
macro_body One or more assembly language statements. Invoking the macro tell the assembler to substitutes these statements.

The body of a simple macro consists of just one or two statements for the assembler to execute. Then, in response to the .endm directive, the assembler resumes program execution at the statement immediately after the macro call.

But not all macros are so simple. For example, a macro can contain a conditional assembly block, The conditional test could lead to the .mexit directive stopping execution early, before it reaches the .endm directive.

Conditional Macro Definition is the definition of macro addto, which includes an .mexit directive. Assembly Code that Calls addto Macro shows the assembly-language code that calls the addto macro. Expanded addto Macro Calls shows the expanded addto macro calls.

Listing 2. Conditional Macro Definition
//define a macro
addto:  .macro dest,val

        .if val==0

        nop

        .elseif val >= -32768 && val <= 32767

        addi dest,dest,val      // use compact instruction

        .else

        addi dest,dest,val@l    // use 32-bit add

        addis dest,dest,val@ha

        .endif

// end macro definition

        .endm
Listing 3. Assembly Code that Calls addto Macro
// specify an executable code section
.text

li      r3,0

// call the addto macro

addto   r3,0

addto   r3,1

addto   r3,2

addto   r3,0x12345678
Listing 4. Expanded addto Macro Calls
li      r3,0
nop

addi    r3,r3,1

addi    r3,r3,2

addi    r3,r3,0x12345678@l

addis   r3,r3,0x12345678@ha