@shijitht

Inline assembly basics

leave a comment »

Inline assembly functionality allows embedding assembly code in C program. This is like an inline function, where the corresponding value gets substituted. Here assembler substitutes our assembly code in proper place with no change. GCC follows AT&T systax for assembly code.

AT&T syntax

  1. Register prefixed with % and $ for immediate/constant.(%eax and $10)
  2. Source operand comes first.(opcode source destination)
  3. Size of operand as a suffix to opcode. i.e. b -> byte, w -> word,
    l -> long.(movl)
  4. Indirect memory reference using parenthesis, ‘( ‘ and ‘ )’.(  (eax)  )

In C

syntax:   asm(” assembly code “);
function asm is used to write assembly code in C.

test.c
-------
#include<stdio.h>
int fun()
{
 asm("mov $24, %eax");
}
int main()
{
 int n = fun();
 printf("%d\n", n);
 return 0;
}

In test.c function fun has no return statement. But it returns 24. When a function returns, its return value is places in eax register. But we can explicitly set eax using asm. So a value can be returned without a return statement. The move instruction used is darkened above.

Operation which are very difficult or unable to perform in C can be achieved easily using inline assembly. Rotation of a block of bytes is done in a single step using  asm.( ror or rol ). But in C, it takes an effort. And all machine level instructions can be used, which can’t be produced with gcc. eg: logical and arithmetic shift. Architecture dependent coding and optimization is done using inline assembly. Speed of code can be further improved with hand written assembly.

Advertisement

Written by shijitht

October 21, 2010 at 1:34 am

Posted in C

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.