gcc Inline assembly in macros

suggest change

We can put assembly instructions inside a macro and use the macro like you would call a function.

#define mov(x,y) \
{ \
    __asm__ ("l.cmov %0,%1,%2" : "=r" (x) : "r" (y), "r" (0x0000000F)); \
}

/// some definition and assignment
unsigned char sbox[256][256];

///Using
mov(state[0][1], sbox[si][sj]);

Using inline assembly instructions embedded in C code can improve the run time of a program. This is very helpful in time critical situations like cryptographic algorithms such as AES. For example, for a simple shift operation that is needed in the AES algorithm, we can substitute a direct Rotate Right assembly instruction with C shift operator >>.

In an implementation of ‘AES256’, in ‘AddRoundKey()’ function we have some statements like this:

unsigned int w;          // 32-bit
unsigned char subkey[4]; // 8-bit, 4*8 = 32 

subkey[0] = w >> 24;     // hold 8 bit, MSB, leftmost group of 8-bits 
subkey[1] = w >> 16;     // hold 8 bit, second group of 8-bit from left    
subkey[2] = w >> 8;      // hold 8 bit, second group of 8-bit from right
subkey[3] = w;           // hold 8 bit, LSB, rightmost group of 8-bits

/// subkey <- w

They simply assign the bit value of w to subkey array.

Replacing those shifts with one rotate is not equivalent. The shifts above extract bytes independently of host endianness. A 16-bit rotate does not produce the same four bytes, and converting unsigned char * to unsigned int * is undefined behavior when the array is not correctly aligned or when the store violates effective-type rules. Keep the shifts, or copy the word with memcpy into an unsigned int before using assembly.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents