Neha Patil (Editor)

Inline assembler

Updated on
Edit
Like
Comment
Share on FacebookTweet on TwitterShare on LinkedInShare on Reddit

In computer programming, the Inline Assembler is a feature of some compilers that allows low-level code written in Assembly Language to be embedded within the existing program code that would otherwise have been created using a High-Level Language like C or Ada. This embedding is usually done for one of three reasons:

Contents

Optimization
To use assembly language for inline optimisation, programmers code the most performance-sensitive parts of their program's algorithms using hand-coded assembly language. This allows programmers to create highly efficient sections of code that might otherwise be inefficiently created by a compiler's higher-level constructs.
Access to processor specific instructions
Most processors offer special instructions, such as Compare and Swap and Test and Set — instructions which may be used to construct semaphores or other synchronization and locking primitives. Nearly every modern processor has these or similar instructions, as they are necessary to implement multitasking. Examples of specialized instructions are found in the SPARC VIS, Intel MMX and SSE, and Motorola Altivec instruction sets.
System calls
High-level languages rarely have a direct facility to make arbitrary system calls, so assembly code is used.

Syntax in language standards

The ISO C+ standard and ISO C standards (annex J) specify a conditionally supported syntax for inline assembler:

<block-quote>

</block-quote>

Example of a system call

Calling an operating system directly is generally not possible in the presence of protected memory. The OS runs at a more privileged level (kernel mode) than the user (user mode); a (software) interrupt is used to make requests to the operating system. This is rarely a feature in a higher-level language, and so wrapper functions for system calls are written using inline assembler.

The following C code comprises samples including a system call wrapper in AT&T assembler syntax with the GNU Assembler. They are normally written with the aid of macros; the full code is included for clarity.

The format of basic inline assembly is very straightforward and shown below.

Example:

OR

Both asm and __asm__ are valid. __asm__ can be used if the keyword asm conflicts with something else in the program.

Example of optimization and processor-specific instructions

This example of the inline assembly is from the D programming language and computes the tangent of x using the x86's FPU instructions. This is faster than using the floating-point operations that would be emitted by the compiler, and it allows the programmer to make use of the fldpi instruction, which loads the closest approximation of pi possible on the x86 architecture.

References

Inline assembler Wikipedia