- Inline assembler
In
computer programming , the inline assembler is a feature of somecompiler s that allows very low level code written in assembly to be embedded in ahigh level language like C or Ada. This embedding is usually done for one of three reasons:* Optimization: when assembly language is inlined for optimization, the most performance-sensitive parts of an
algorithm are replaced by hand-written assembly. This allows the programmer to use the full extent of his ingenuity, without being limited by a compiler's higher-level constructs.
* Access to processor specific instructions: some 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. To name a few, specialized instructions are found in theSPARC VIS,Intel MMX and SSE, andMotorola Altivec instruction set s.
*System call s: high-level languages rarely have a direct facility to make system calls, so assembly code is used.Example of optimization and processor-specific instructions
This example of inline assembly is from the
D programming language and computes the tangent of x using thex86 '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 thefldpi
instruction, which loads the closest approximation ofpi possible on the x86 architecture.Example of a system call
Directly calling an operating system is generally impossible 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 sowrapper function s for system calls are written using inline assembler.The following C code are samples including a system call wrapper. They are normally written with the aid of macros; the full code is included for clarity.
The format of basic inline assembly is very much straightforward. Its basic form is
Example:
OR
Both
asm
and__asm__
are valid.__asm__
can be used if the keywordasm
conflicts with something in your program.External links
* [http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html GCC-Inline-Assembly-HOWTO]
* [http://gcc.gnu.org/onlinedocs/gnat_ugn_unw/Inline-Assembler.html GNAT Inline Assembler]
Wikimedia Foundation. 2010.