Jump to content

Assembly language

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Autodmc (talk | contribs) at 22:17, 25 September 2006 (Fixed links to C (programming language) [linked to C-letter], and marked for style cleanup). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

You must add a |reason= parameter to this Cleanup template – replace it with {{Cleanup|September 2006|reason=<Fill reason here>}}, or remove the Cleanup template.

Assembly language refers to a class of low-level languages used to write computer programs, or to a particular such language.

Assembly language was once widely used for all aspects of programming. Today it is used in limited situations, primarily when direct hardware manipulation or unusual performance issues are involved.

Key concepts

Assembler

[1] An assembler creates object code by translating assembly instruction mnemonics into opcodes, and by resolving symbolic names for memory locations and other entities. The use of symbolic references is a key feature of assemblers, saving tedious calculations and manual address updates after program modifications. Most assemblers also include macro facilities for performing textual substitution — e.g. to generate common short sequences of instructions to run inline, instead of in a subroutine.

Assemblers are generally simpler to write than compilers for high-level languages, and have been available since the 1950s. (The first assemblers, in the early days of computers, were a breakthrough for a generation of tired programmers.) Modern assemblers, especially for RISC based architectures, such as MIPS, Sun SPARC and HP PA-RISC, optimize instruction scheduling to exploit the CPU pipeline efficiently.

High-level assemblers provide high-level-language abstractions such as:

  • Advanced control structures
  • High-level procedure/function declarations and invocations
  • High-level abstract data types, including structures/records, unions, classes, and sets
  • Sophisticated macro processing

See Language design below for more details.

Assembly language

A program written in assembly language consists of a series of instructions that correspond to a stream of executable instructions that can be loaded into memory and executed.

For example, an x86/IA-32 processor can execute the following binary instruction as expressed in machine language:

  • Binary: 10110000 01100001 (Hexadecimal: 0xb061)

The equivalent assembly language representation is easier to remember (more mnemonic):

  • mov al, 061h

This instruction means:

The mnemonic "mov" is an operation code or opcode, and was chosen by the instruction set designer to abbreviate "move." A comma-separated list of arguments or parameters follows the opcode; this is a typical assembly language statement.

Transforming assembly into machine language is accomplished by an assembler, and the reverse by a disassembler. Unlike in high-level languages, there is usually a 1-to-1 correspondence between simple assembly statements and machine language instructions. However, in some cases, an assembler may provide pseudoinstructions which expand into several machine language instructions to provide commonly needed functionality. For example, for a machine that lacks a "branch if greater or equal" instruction, an assembler may provide a pseudoinstruction that expands to the machine's "set if less than" and "branch if zero (on the result of the set instruction)". Most full-featured assemblers also provide a rich macro language (discussed below) which is used by vendors and programmers to generate more complex code and data sequences.

Every computer architecture has its own machine language, and therefore its own assembly language. Computers differ by the number and type of operations they support. They may also have different sizes and numbers of registers, and different representations of data types in storage. While most general-purpose computers are able to carry out essentially the same functionality, the ways they do so differ; the corresponding assembly languages reflect these differences.

Multiple sets of mnemonics or assembly-language syntax may exist for a single instruction set, typically instantiated in different assembler programs. In these cases, the most popular one is usually that supplied by the manufacturer and used in its documentation.

Machine language

Machine language is built up from discrete statements or instructions. Depending on the processing architecture, a given instruction may specify:

  • Particular registers for arithmetic, addressing, or control functions
  • Particular memory locations or offsets
  • Particular addressing modes used to interpret the operands

More complex operations are built up by combining these simple instructions, which (in a von Neumann machine) are executed sequentially, or as otherwise directed by control flow instructions.

Some operations available in most instruction sets include:

  • moving
    • set a register (a temporary "scratchpad" location in the CPU itself) to a fixed constant value
    • move data from a memory location to a register, or vice versa. This is done to obtain the data to perform a computation on it later, or to store the result of a computation.
    • read and write data from hardware devices
  • computing
    • add, subtract, multiply, or divide the values of two registers, placing the result in a register
    • perform bitwise operations, taking the conjunction/disjunction (and/or) of corresponding bits in a pair of registers, or the negation (not) of each bit in a register
    • compare two values in registers (for example, to see if one is less, or if they are equal)
  • affecting program flow
    • jump to another location in the program and execute instructions there
    • jump to another location if a certain condition holds
    • jump to another location, but save the location of the next instruction as a point to return to (a call)

Some computers include "complex" instructions in their instruction set. A single "complex" instruction does something that may take many instructions on other computers. Such instructions are typified by instructions that take multiple steps, control multiple functional units, or otherwise appear on a larger scale than the bulk of simple instructions implemented by the given processor. Some examples of "complex" instructions include:

  • saving many registers on the stack at once
  • moving large blocks of memory
  • complex and/or floating-point arithmetic (sine, cosine, square root, etc.)
  • performing an atomic test-and-set instruction
  • instructions that combine ALU with an operand from memory rather than a register

A complex instruction type that has become particularly popular recently is the SIMD operation or vector instruction, an operation that performs the same arithmetic operation on multiple pieces of data at the same time. SIMD instructions allow easy parallelization of algorithms commonly involved in sound, image, and video processing. Various SIMD implementations have been brought to market under trade names such as MMX, 3DNow! and AltiVec.

The design of instruction sets is a complex issue. A simpler instruction set may offer the potential for higher speeds, reduced processor size, and reduced power consumption; a more complex one may optimize common operations, improve memory/cache efficiency, or simplify programming. This distinction is generally dissussed in terms of RISC (Reduced Instruction Set Computer) versus CISC (Complex Instruction Set Computer), but this is an oversimplification. (For example, the RISC concept can be thought of as exposing a microprogramming architecture – intended to be exploited by compiler technology, rather than via direct in assembly language programming. Ease of programming and many optimization issues become moot.) See instruction set for related comments.

Language design

Instructions (statements) in assembly language are generally very simple, unlike in a high-level language. Each instruction typically consists of an operation or opcode (or, simply, instruction) plus zero or more operands. Most instructions refer to a single value, or pair of values. An instruction coded in the language usually corresponds directly to a single executable machine language instruction.

Other elements common to most assembly languages include the following:

  • Data definitions. Additional directives let the programmer reserve storage areas for reference by machine language statements. Storage can typically be initialized with literal numbers, strings, and other primitive data types.
  • Labels. Data definitions are referenced using names (labels or symbols) assigned by the programmer, and typically reference constants, variables, or structure elements. Labels can also be assigned to code locations, i.e. subroutine entry points or GOTO destinations. Most assemblers provide flexible symbol management, letting programmers manage different namespaces, automatically calculate offsets within data structures, and assign labels that refer to literal values or the result of simple computations performed by the assembler.
  • Comments. Like most computer languages, comments can be added to assembly source code that are ignored by the assembler.
  • Macros. Most assemblers have an embedded macro language that generate code or data based on a set of arguments. Macros can be coded by the programmer to avoid repetition, e.g. generating a common data structure. Macros are also supplied by a vendor or manufacturer to encapsulate a particular operation. For example:
    • With 8-bit processors, it is common to use a macro that increments or decrements a 16-bit quantity stored in two consecutive bytes – a common operation that would normally require three or four instructions on, for example, the 6502.
    • Manufacturers supply macros for using standard system interfaces, such as I/O operations or low-level operating system requests. On IBM mainframes, enormous macro libraries provide access to the numerous IBM access methods and other system services.
    • Most processor architectures have idiomatic instruction sequences (many assemblers even have built-in macros for common ones). For example, currency formatting on an IBM mainframe commonly used a macro to generate a sequence of four instructions including the Edit and Mark (EDMK) instruction.

Such capabilities are borrowed from higher-level language designs. They can greatly simplify the problems of coding and maintaining low-level code. Raw assembly source code as generated by compilers or disassemblers – i.e. without comments, meaningful symbols, or data definitions – is quite difficult to read.

Most assembly languages share the above basic characteristics. There have been some unusual exceptions, however.

  • Some assemblers include quite sophisticated macro languages, incorporating such high-level language elements as symbolic variables, conditionals, string manipulation, and arithmetic operations, all usable during the execution of a given macro, and allowing macros to save context or exchange information. Thus a macro might emit a large number of assembly language instructions or data definitions, based on the macro arguments. This could be used to generate record-style data structures or "unrolled" loops, for example, or could generate entire algorithms based on complex parameters. An organization using assembly language that has been heavily extended using such a macro suite may arguably be considered to be working in a (slightly) higher-level language – such programmers are not working with a computer's lowest-level conceptual elements.
  • Some assemblers have incorporated structured programming elements to encode execution flow. The earliest example of this approach was in the Concept-14 macro set developed by Marvin Zloof at IBM's Thomas Watson Research Center, which extended the S/370 macro assembler with IF/ELSE/ENDIF and similar control flow blocks. This was a way to reduce or eliminate the use of GOTO operations in assembly code, one of the main factors causing spaghetti code in assembly language. This approach found wide used by the latter days of large-scale assembly language use, i.e. the early 80s.
  • A curious design was A-natural, a "stream-oriented" assembler for 8080/Z80 processors from Whitesmiths Ltd. (developers of the Unix-like Idris and what was reported to be the first commercial C compiler). The language was classified as an assembler, because it worked with raw machine elements such as opcodes, registers, and memory references; but it incorporated an expression syntax to indicate execution order. Parentheses and other special symbols, along with block-oriented structured programming constructs, controlled the sequence of the generated instructions. A-natural was built as the object language of a C compiler, rather than for hand-coding, but its logical syntax won some fans.

There has been little apparent demand for more sophisticated assemblers since the decline of large-scale assembly language development.

Use of assembly language

Historical perspective

Historically, a large number of programs have been written entirely in assembly language. Operating systems were almost exclusively written in assembly language until the widespread acceptance of C in the 70s and early 80s. Many commercial applications were written in assembly language as well, including a large amount of the IBM mainframe software written by large corporations. COBOL and FORTRAN eventually displaced much of this work, although a number of large organizations retained assembly-language application infrastructures well into the 80s.

Most early microcomputers relied on hand-coded assembly language, including most operating systems and large applications. This was because these systems had severe resource constraints, imposed idiosyncratic memory and display architectures, and provided limited, buggy system services. Perhaps more telling was the lack of first-class high-level language compilers suitable for microcomputer use. (A psychological factor may have also played a role: the first generation of microcomputer programmers retained a hobbyist, "wires and pliers" attitude.) Typical examples of large assembler language programs from this period are the CP/M and MS-DOS operating systems, the early IBM PC spreadsheet program Lotus 123, and almost all popular games for the Commodore 64. Even into the 1990s, the majority of console video games were written in assembly language, including most games written for the Mega Drive/Genesis and the Super Nintendo Entertainment System. The popular arcade game NBA Jam (1993) is another example.

Current usage

There has always been debate over the usefulness and performance of assembly language relative to high-level languages, though this gets less attention today. Assembly language has specific niche uses where it is important; see below. But in general, modern optimizing compilers are claimed to render high-level languages into code that runs at least as fast as hand-written assembly, despite some counter-examples that can be created. The complexity of modern processors makes effective hand-optimization increasingly difficult. Moreover, and to the dismay of efficiency lovers, increasing processor performance has meant that most CPUs sit idle most of the time, with delays caused by predictable bottlenecks such as I/O operations and paging. This has made raw code execution speed a non-issue for most programmers (hence the increasing use of interpreted languages without apparent performance impact).

There are really only a handful of situations where today's expert practitioners would choose assembly language:

  • When a stand-alone binary executable is required, i.e. one that must execute without recourse to the run-time components or libraries associated with a high-level language; this is perhaps the most common situation
  • When interacting directly with the hardware, e.g. in a device driver, or when using processor-specific instructions not exploited by or available to the compiler
  • When extreme optimization is required, e.g. in an inner loop in a processor-intensive algorithm
  • When a system with severe resource constraints (e.g. an embedded system) must be hand-coded to maximize the use of limited resources; but this is becoming less common as processor price/performance improves
  • When no high-level language exists, e.g. on a new or specialized processor

Few programmers today need to use assembly language on a day-to-day basis. For performance-critical applications, a low-level language like C would generally be chosen. It is now very difficult to write a C program which is less efficient than an assembly language program. However, a strong case can be made that any serious programmer should learn at least one assembly language – to understand the fine structure of how computers function, to anticipate how application design choices can improve generated code, and to appreciate all the work high-level languages save.

Typical applications

Hand-coded assembly language is typically used in a system's BIOS. This low-level code is used, among other things, to initialize and test the system hardware prior to booting the OS, and is stored in ROM. Once a certain level of hardware initialization has taken place, execution transfers to other code, typically written in higher level languages; but the code running immediately after power is applied is usually written in assembly language. The same is true of most boot loaders.

Many compilers render high-level languages into assembly first before fully compiling, allowing the assembly code to be viewed for debugging and optimization purposes. Relatively low-level languages, such as C, often provide special syntax to embed assembly language directly in the source code. Programs using such facilities, such as the Linux kernel, can then construct abstractions utilizing different assembly language on each hardware platform. The system's portable code can then utilize these processor-specific components through an uniform interface.

Assembly language is also valuable in reverse engineering, since many programs are distributed only in machine code form, and machine code is usually easy to translate into assembly language and carefully examine in this form, but very difficult to translate into a higher-level language. Tools such as the Interactive Disassembler make extensive use of disassembly for such a purpose.

Assembly language or assembler language is commonly called assembler, assembly, ASM, or symbolic machine code. A generation of IBM mainframe programmers called it BAL for Basic Assembly Language.

The computational step where an assembler is run, including all macro processing, is known as assembly time.

This use of the word assembly dates from the early years of computers (cf. short code, speed code/"speedcoding").

A cross assembler (see cross compiler) produces code for one type of processor, but runs on another.

Further details

For any given personal computer, mainframe, embedded system, and game console, both past and present, at least one--possibly dozens--of assemblers have been written. For some examples, see the list of assemblers.

On Unix systems, the assembler is traditionally called as, although it is not a single body of code, being typically written anew for each port. A number of Unix variants use GAS.

Within processor groups, each assembler has its own dialect. Sometimes, some assemblers can read another assembler's dialect, for example, TASM can read old MASM code, but not the reverse. FASM and NASM have similar syntax, but each support different macros that could make them difficult to translate to each other. The basics are all the same, but the advanced features will differ.

Also, assembly can sometimes be portable across different operating systems on the same type of CPU. Calling conventions between operating systems often differ slightly to none at all, and with care it is possible to gain some portability in assembly language, usually by linking with a C library that does not change between operating systems. However, it is not possible to link portably with C libraries that require the caller to use preprocessor macros that may change between operating systems.

For example, many things in libc depend on the preprocessor to do OS-specific, C-specific things to the program before compiling. In fact, some functions and symbols are not even guaranteed to exist outside of the preprocessor. Worse, the size and field order of structs, as well as the size of certain typedefs such as off_t, are entirely unavailable in assembly language, and differ even between versions of Linux, making it impossible to portably call functions in libc other than ones that only take simple integers and pointers as parameters.

Some higher level computer languages, such as C, support Inline assembly where relatively brief sections of assembly code can be embedded into the high level language code. Borland Pascal also had an assembler compiler, which was initialized with a keyword "asm". It was mainly used to create mouse and COM-port drivers.

Many people use an emulator to debug assembly-language programs.

Example listing of assembly language source code

Addr Label Instruction Object code[2]
.begin
.org 2048
a_start .equ 3000
2048 ld length,%r1 11000010 00000000 00101000 00101100
2052 ld address,%r2 11000100 00000000 00101000 00110000
2056 addcc %r3,%r0,%r3 10000110 10001000 11000000 00000000
2060 loop: addcc %r1,%r1,%r0 10000000 10001000 01000000 00000001
2064 be done 00000010 10000000 00000000 00000110
2068 addcc %r1,-4,%r1 10000010 10000000 01111111 11111100
2072 addcc %r1,%r2,%r4 10001000 10000000 01000000 00000010
2076 ld %r4,%r5 11001010 00000001 00000000 00000000
2080 ba loop 00010000 10111111 11111111 11111011
2084 addcc %r3,%r5,%r3 10000110 10000000 11000000 00000101
2088 done: jmpl %r15+4,%r0 10000001 11000011 11100000 00000100
2092 length: 20 00000000 00000000 00000000 00010100
2096 address: a_start 00000000 00000000 00001011 10111000
.org a_start
3000 a: 25 00000000 00000000 00000000 00011001
3004 -10 11111111 11111111 11111111 11110110
3008 33 00000000 00000000 00000000 00100001
3012 -5 11111111 11111111 11111111 11111011
3016 7 00000000 00000000 00000000 00000111
.end

Example of a selection of instructions (for a virtual computer[3]) with the corresponding address in memory where each instruction will be placed. These addresses are not static, see memory management. Accompanying each instruction is the generated (by the assembler) object code that coincides with the virtual computer's architecture (or ISA).

See also

References

  1. ^ David Salomon, Assemblers and Loaders. 1993 [1]
  2. ^ Murdocca, Miles J. (2000). Principles of Computer Architecture. Prentice-Hall. ISBN 0-201-43664-7. {{cite book}}: Unknown parameter |coauthors= ignored (|author= suggested) (help)
  3. ^ Principles of Computer Architecture (POCA) – ARCTools virtual computer available for download to execute referenced code, accessed August 24, 2005

Books