From Wikipedia, the free encyclopedia
  (Redirected from Compilers)
Jump to: navigation, search
This article is about the computing term. For the anime, see Compiler (anime).
"Compile" and "compiling" redirect here. For the software company, see Compile (company). For other uses, see compilation.

A compiler is a computer program (or a set of programs) that transforms source code written in a programming language (the source language) into another computer language (the target language), with the latter often having a binary form known as object code.[1] The most common reason for converting source code is to create an executable program.

The name "compiler" is primarily used for programs that translate source code from a high-level programming language to a lower level language (e.g., assembly language or machine code). If the compiled program can run on a computer whose CPU or operating system is different from the one on which the compiler runs, the compiler is known as a cross-compiler. More generally, compilers are a specific type of translator.

While all programs that take a set of programming specifications and translate them, i.e. create a means to execute those specifications, are technically "compilers", the term generally means a program that produces a separate executable from the compiler (that may require a run time library or subsystem to operate), a compiler that merely executes the original specifications is usually referred to as an "interpreter", although because of differing methods of analyzing what represents compilation and what represents interpretation, there is some overlap between the two terms.

A program that translates from a low-level language to a higher level one is a decompiler. A program that translates between high-level languages is usually called a source-to-source compiler or transpiler. A language rewriter is usually a program that translates the form of expressions without a change of language. The term compiler-compiler is sometimes used to refer to a parser generator, a tool often used to help create the lexer and parser. A compiler is likely to perform many or all of the following operations: lexical analysis, preprocessing, parsing, semantic analysis (syntax-directed translation), code generation, and code optimization. Program faults caused by incorrect compiler behavior can be very difficult to track down and work around; therefore, compiler implementors invest significant effort to ensure compiler correctness.


A diagram of the operation of a typical multi-language, multi-target compiler

Software for early computers was primarily written in assembly language. Although the first high-level language is nearly as old as the first computer, the limited memory capacity of early computers led to substantial technical challenges when the first compilers were designed.[discuss]

The first high-level programming language (Plankalkül) was proposed by Konrad Zuse, in 1943. The first compiler was written by Grace Hopper, in 1952, for the A-0 programming language; the A-0 functioned more as a loader or linker than the modern notion of a compiler. The first autocode and its compiler were developed by Alick Glennie, in 1952, for the Mark 1 computer at the University of Manchester and is considered by some to be the first compiled programming language.[2] The FORTRAN team led by John Backus at IBM is generally credited as having introduced the first complete compiler, in 1957. COBOL was an early language to be compiled on multiple architectures, in 1960.[3]

In many application domains the idea of using a higher level language quickly caught on. Because of the expanding functionality supported by newer programming languages and the increasing complexity of computer architectures, compilers have become more complex.

Early compilers were written in assembly language. The first self-hosting compiler – capable of compiling its own source code in a high-level language – was created, in 1962, for Lisp by Tim Hart and Mike Levin at MIT.[4] Since the 1970s, it has become common practice to implement a compiler in the language it compiles, although both Pascal and C have been popular choices for implementation language. Building a self-hosting compiler is a bootstrapping problem—the first such compiler for a language must be compiled either by hand or by a compiler written in a different language, or (as in Hart and Levin's Lisp compiler) compiled by running the compiler in an interpreter.


Compilers enabled the development of programs that are machine-independent. Before the development of FORTRAN, the first high-level language, in the 1950s,[5] machine-dependent assembly language was widely used. While assembly language produces more abstraction than machine code on the same architecture, just as with machine code, it has to be modified or rewritten if the program is to be executed on different computer hardware architecture.

With the advent of high-level programming languages that followed FORTRAN, such as COBOL, C, and BASIC, programmers could write machine-independent source programs. A compiler translates the high-level source programs into target programs in machine languages for the specific hardware. Once the target program is generated, the user can execute the program.

Compilers in education[edit]

Compiler construction and compiler optimization are taught at universities and schools as part of a computer science curriculum.[6] Such courses are usually supplemented with the implementation of a compiler for an educational programming language. A well-documented example is Niklaus Wirth's PL/0 compiler, which Wirth used to teach compiler construction in the 1970s.[7] In spite of its simplicity, the PL/0 compiler introduced several influential concepts to the field:

  1. Program development by stepwise refinement (also the title of a 1971 paper by Wirth)[8]
  2. The use of a recursive descent parser
  3. The use of Extended Backus–Naur Form (EBNF) to specify the syntax of a language
  4. A code generator producing portable P-code
  5. The use of tombstone diagrams in the formal description of the bootstrapping problem.

Compiler output[edit]

One classification of compilers is by the platform on which their generated code executes. This is known as the target platform.

A native or hosted compiler is one which output is intended to directly run on the same type of computer and operating system that the compiler itself runs on. The output of a cross compiler is designed to run on a different platform. Cross compilers are often used when developing software for embedded systems that are not intended to support a software development environment.

The output of a compiler that produces code for a virtual machine (VM) may or may not be executed on the same platform as the compiler that produced it. For this reason such compilers are not usually classified as native or cross compilers.

The lower level language that is the target of a compiler may itself be a high-level programming language. C, often viewed as some sort of portable assembler, can also be the target language of a compiler. E.g.: Cfront, the original compiler for C++ used C as target language. The C created by such a compiler is usually not intended to be read and maintained by humans. So indent style and pretty C intermediate code are irrelevant. Some features of C turn it into a good target language. E.g.: C code with #line directives can be generated to support debugging of the original source.

Compiled versus interpreted languages[edit]

Higher-level programming languages usually appear with a type of translation in mind: either designed as compiled language or interpreted language. However, in practice there is rarely anything about a language that requires it to be exclusively compiled or exclusively interpreted, although it is possible to design languages that rely on re-interpretation at run time. The categorization usually reflects the most popular or widespread implementations of a language — for instance, BASIC is sometimes called an interpreted language, and C a compiled one, despite the existence of BASIC compilers and C interpreters.

Interpretation does not replace compilation completely. It only hides it from the user and makes it gradual. Even though an interpreter can itself be interpreted, a directly executed program is needed somewhere at the bottom of the stack (see machine language). Modern trends toward just-in-time compilation and bytecode interpretation at times blur the traditional categorizations of compilers and interpreters.

Some language specifications spell out that implementations must include a compilation facility; for example, Common Lisp. However, there is nothing inherent in the definition of Common Lisp that stops it from being interpreted. Other languages have features that are very easy to implement in an interpreter, but make writing a compiler much harder; for example, APL, SNOBOL4, and many scripting languages allow programs to construct arbitrary source code at runtime with regular string operations, and then execute that code by passing it to a special evaluation function. To implement these features in a compiled language, programs must usually be shipped with a runtime library that includes a version of the compiler itself.

Special type of compilers[edit]

While the typical compiler outputs machine code, there are several other types:

  • A source-to-source compiler is a type of compiler that takes a high-level language as its input and outputs a high-level language. For example, an automatic parallelizing compiler will frequently take in a high-level language program as an input and then transform the code and annotate it with parallel code annotations (e.g. OpenMP) or language constructs (e.g. Fortran's DOALL statements).
  • Bytecode compilers that compile to assembly language of a theoretical machine, like some Prolog implementations
  • Just-in-time compiler (JIT compiler) is the last part of a multi-pass compiler chain in which some compilation stages are deferred to run-time. Examples are implemented in Smalltalk, Java and Microsoft .NET's Common Intermediate Language (CIL) systems.
    • Applications are first compiled using a bytecode compiler and delivered in a machine-independent intermediate representation. This bytecode is then compiled using a JIT compiler to native machine code just when the execution of the program is required.[9]
  • hardware compilers (also known as syntheses tools) are compilers whose output is a description of the hardware configuration instead of a sequence of instructions.
    • The output of these compilers target computer hardware at a very low level, for example a field-programmable gate array (FPGA) or structured application-specific integrated circuit (ASIC).[10] Such compilers are said to be hardware compilers, because the source code they compile effectively controls the final configuration of the hardware and how it operates. The output of the compilation is only an interconnection of transistors or lookup tables.
    • An example of hardware compiler is XST,[11][12] the Xilinx Synthesis Tool used for configuring FPGAs. Similar tools are available from Altera,[13] Synplicity, Synopsys and other hardware vendors.

Compiler construction[edit]

Compilers bridge source programs in high-level languages with the underlying hardware. A compiler verifies code syntax, generates efficient object code, performs run-time organization, and formats the output according to assembler and linker conventions.

In the early days, the approach taken to compiler design used to be directly affected by the complexity of the processing, the experience of the person(s) designing it, and the resources available.

A compiler for a relatively simple language written by one person might be a single, monolithic piece of software. When the source language is large and complex, and high quality output is required, the design may be split into a number of relatively independent phases. Having separate phases means development can be parceled up into small parts and given to different people. It also becomes much easier to replace a single phase by an improved one, or to insert new phases later (e.g., additional optimizations).

The division of the compilation processes into phases was championed by the Production Quality Compiler-Compiler Project (PQCC) at Carnegie Mellon University. This project introduced the terms front end, middle end, and back end.

All but the smallest of compilers have more than two phases. The point at which these ends meet is not always clearly defined.

One-pass versus multi-pass compilers[edit]

Classifying compilers by number of passes has its background in the hardware resource limitations of computers. Compiling involves performing lots of work and early computers did not have enough memory to contain one program that did all of this work. So compilers were split up into smaller programs which each made a pass over the source (or some representation of it) performing some of the required analysis and translations.

The ability to compile in a single pass has classically been seen as a benefit because it simplifies the job of writing a compiler and one-pass compilers generally perform compilations faster than multi-pass compilers. Thus, partly driven by the resource limitations of early systems, many early languages were specifically designed so that they could be compiled in a single pass (e.g., Pascal).

In some cases the design of a language feature may require a compiler to perform more than one pass over the source. For instance, consider a declaration appearing on line 20 of the source which affects the translation of a statement appearing on line 10. In this case, the first pass needs to gather information about declarations appearing after statements that they affect, with the actual translation happening during a subsequent pass.

The disadvantage of compiling in a single pass is that it is not possible to perform many of the sophisticated optimizations needed to generate high quality code. It can be difficult to count exactly how many passes an optimizing compiler makes. For instance, different phases of optimization may analyse one expression many times but only analyse another expression once.

Splitting a compiler up into small programs is a technique used by researchers interested in producing provably correct compilers. Proving the correctness of a set of small programs often requires less effort than proving the correctness of a larger, single, equivalent program.

Three phases compiler structure[edit]

Regardless of the exact number of stages which a compiler is built of, it is common practice to classify them into three phases. These phases are named after the Production Quality Compiler-Compiler Project phases mentioned before.

Compiler design
  • The front end verifies syntax and semantics according to a specific source language. Performs type checking by collecting type information. Generates errors and warnings, if any, highlighting[dubious ] them on the source code. Aspects of the front end include lexical analysis, syntax analysis, and semantic analysis. Eventually generates an intermediate representation or IR of the source code for processing by the middle-end. This IR is usually a lower level of representation of the program with respect to the source code.
  • The middle end performs optimizations on a form other than the source code or machine code. This source code/machine code independence is intended to enable generic optimizations to be shared between versions of the compiler supporting different languages and target processors. Examples of middle end optimizations are removal of useless (dead code elimination) or unreachable code (reachability analysis), discovery and propagation of constant values (constant propagation), relocation of computation to a less frequently executed place (e.g., out of a loop), or specialization of computation based on the context. Eventually it may[clarification needed] generate another IR for to be used in the back end.
  • The back end takes the output from the middle end. It may perform more analysis, transformations and optimizations that are for a particular computer. Generates the target-dependent assembly code, performing register allocation in process. Performs optimizations of the target code utilization of the hardware, like figuring out how to keep parallel execution units busy by filling delay slots. Although most algorithms for optimization are NP-hard, heuristic techniques are well-developed and currently implemented in production-quality compilers.[14] Typically the output of a back end is machine code specialized for a particular processor and operating system.

This front/middle/back-end approach makes it possible to combine front ends for different languages with back ends for different CPUs. Practical examples of this approach are the GNU Compiler Collection, LLVM,[15] and the Amsterdam Compiler Kit, which have multiple front-ends, shared analysis and multiple back-ends.

Front end[edit]

Lexer and parser example for C. Starting from the sequence of characters "if(net>0.0)total+=net*(1.0+tax/100.0);", the scanner composes a sequence of tokens, and categorizes each of them, for example as identifier, reserved word, number literal, or operator. The latter sequence is transformed by the parser into a syntax tree, which is then treated by the remaining compiler phases. The scanner and parser handles the regular and properly context-free parts of the grammar for C, respectively.

The compiler frontend analyzes the source code to build an internal representation of the program, called the intermediate representation or IR. It also manages the symbol table, a data structure mapping each symbol in the source code to associated information such as location, type and scope.

While the frontend can be a single monolithic function or program, as in a scannerless parser, it is more commonly implemented and analyzed as several phases, which may execute sequentially or concurrently. This method is favored due to its modularity and separation of concerns. Most commonly today, the frontend is broken into three phases: lexical analysis (also known as lexing), syntax analysis (also known as parsing), and semantic analysis. Lexical analysis and parsing comprise the syntactic analysis (word syntax and phrase syntax, respectively), and in simple cases these modules (the lexer and parser) can be automatically generated from a grammar for the language, though in more complex cases these require manual modification. The lexical grammar and phrase grammar are usually context-free grammars, which simplifies analysis significantly, with context-sensitivity handled at the semantic analysis phase. The semantic analysis phase is generally more complex and written by hand, but can be partially or fully automated using attribute grammars. These phases themselves can be further broken down – lexing as scanning and evaluating, parsing as first building a concrete syntax tree (CST, parse tree), and then transforming it into an abstract syntax tree (AST, syntax tree).

In some cases additional phases are used, notably line reconstruction and preprocessing, but these are rare. A detailed list of possible phases includes:

  1. Line reconstruction: Languages which strop their keywords or allow arbitrary spaces within identifiers require a phase before parsing, which converts the input character sequence to a canonical form ready for the parser. The top-down, recursive-descent, table-driven parsers used in the 1960s typically read the source one character at a time and did not require a separate tokenizing phase. Atlas Autocode, and Imp (and some implementations of ALGOL and Coral 66) are examples of stropped languages which compilers would have a Line Reconstruction phase.
  2. Lexical analysis breaks the source code text into small pieces called tokens. Each token is a single atomic unit of the language, for instance a keyword, identifier or symbol name. The token syntax is typically a regular language, so a finite state automaton constructed from a regular expression can be used to recognize it. This phase is also called lexing or scanning, and the software doing lexical analysis is called a lexical analyzer or scanner. This may not be a separate step – it can be combined with the parsing step in scannerless parsing, in which case parsing is done at the character level, not the token level.
  3. Preprocessing. Some languages, e.g., C, require a preprocessing phase which supports macro substitution and conditional compilation. Typically the preprocessing phase occurs before syntactic or semantic analysis; e.g. in the case of C, the preprocessor manipulates lexical tokens rather than syntactic forms. However, some languages such as Scheme support macro substitutions based on syntactic forms.
  4. Syntax analysis involves parsing the token sequence to identify the syntactic structure of the program. This phase typically builds a parse tree, which replaces the linear sequence of tokens with a tree structure built according to the rules of a formal grammar which define the language's syntax. The parse tree is often analyzed, augmented, and transformed by later phases in the compiler.
  5. Semantic analysis is the phase in which the compiler adds semantic information to the parse tree and builds the symbol table. This phase performs semantic checks such as type checking (checking for type errors), or object binding (associating variable and function references with their definitions), or definite assignment (requiring all local variables to be initialized before use), rejecting incorrect programs or issuing warnings. Semantic analysis usually requires a complete parse tree, meaning that this phase logically follows the parsing phase, and logically precedes the code generation phase, though it is often possible to fold multiple phases into one pass over the code in a compiler implementation.

Middle end[edit]

Back end[edit]

The term back end is sometimes confused with code generator because of the overlapped functionality of generating assembly code. Some literature uses middle end to distinguish the generic analysis and optimization phases in the back end from the machine-dependent code generators.

The main phases of the back end include the following:

  1. Analysis: This is the gathering of program information from the intermediate representation derived from the input; data-flow analysis is used to build use-define chains, together with dependence analysis, alias analysis, pointer analysis, escape analysis, etc. Accurate analysis is the basis for any compiler optimization. The call graph and control flow graph are usually also built during the analysis phase.
  2. Optimization: the intermediate language representation is transformed into functionally equivalent but faster (or smaller) forms. Popular optimizations are inline expansion, dead code elimination, constant propagation, loop transformation, register allocation and even automatic parallelization.
  3. Code generation: the transformed intermediate language is translated into the output language, usually the native machine language of the system. This involves resource and storage decisions, such as deciding which variables to fit into registers and memory and the selection and scheduling of appropriate machine instructions along with their associated addressing modes (see also Sethi-Ullman algorithm). Debug data may also need to be generated to facilitate debugging.

Compiler analysis is the prerequisite for any compiler optimization, and they tightly work together. For example, dependence analysis is crucial for loop transformation.

In addition, the scope of compiler analysis and optimizations vary greatly, from as small as a basic block to the procedure/function level, or even over the whole program (interprocedural optimization). Obviously,[clarification needed] a compiler can potentially do a better job using a broader view. But that broad view is not free: large scope analysis and optimizations are very costly in terms of compilation time and memory space; this is especially true for interprocedural analysis and optimizations.

Interprocedural analysis and optimizations are common in modern commercial compilers from HP, IBM, SGI, Intel, Microsoft, and Sun Microsystems. The open source GCC was criticized for a long time for lacking powerful interprocedural optimizations, but it is changing in this respect. Another open source compiler with full analysis and optimization infrastructure is Open64, which is used by many organizations for research and commercial purposes.

Due to the extra time and space needed for compiler analysis and optimizations, some compilers skip them by default. Users have to use compilation options to explicitly tell the compiler which optimizations should be enabled.

Compiler correctness[edit]

Main article: Compiler correctness

Compiler correctness is the branch of software engineering that deals with trying to show that a compiler behaves according to its language specification.[16] Techniques include developing the compiler using formal methods and using rigorous testing (often called compiler validation) on an existing compiler.

Conferences and organizations[edit]

A number of conferences in the field of programming languages present advances in compiler construction as one of their main topics.

ACM SIGPLAN supports a number of conferences, including:

The European Joint Conferences on Theory and Practice of Software (ETAPS) sponsors the International Conference on Compiler Construction, with papers from both the academic and industrial sectors.[17]

Asian Symposium on Programming Languages and Systems (APLAS) is organized by the Asian Association for Foundation of Software (AAFS).

Related techniques[edit]

Assembly language is a type of low-level language and a program that compiles it is more commonly known as an assembler, with the inverse program known as a disassembler.

A program that translates from a low-level language to a higher level one is a decompiler.

A program that translates between high-level languages is usually called a language translator, source-to-source compiler, language converter, or language rewriter. The last term is usually applied to translations that do not involve a change of language.

A program that translates into an object code format that is not supported on the compilation machine is called a cross compiler and is commonly used to prepare code for embedded applications.

See also[edit]


  1. ^ "Definition of:compiler". PC Magazine. 
  2. ^ Knuth, D. E., & Pardo, L. T. (1980). The early development of programming languages. A history of computing in the twentieth century, 197–273.
  3. ^ "IP: The World's First COBOL Compilers". 12 June 1997. Archived from the original on 20 February 2012. 
  4. ^ T. Hart and M. Levin. "The New Compiler, AIM-39 - CSAIL Digital Archive - Artificial Intelligence Laboratory Series" (PDF). 
  5. ^ Sheridan, Peter B (1959). "The arithmetic translator-compiler of the IBM FORTRAN automatic coding system". Communications of the ACM. ACM. 2 (2): 9–21. doi:10.1145/368280.368289. 
  6. ^ Chakraborty, P., Saxena, P. C., Katti, C. P., Pahwa, G., Taneja, S. A new practicum in compiler construction. Computer Applications in Engineering Education, In Press.
  7. ^ "The PL/0 compiler/interpreter". 
  8. ^ "The ACM Digital Library". 
  9. ^ Aycock, John (June 2003). "A Brief History of Just-in-time". ACM Comput. Surv. New York, NY, USA. 35 (2): 93–113. doi:10.1145/857076.857077. 
  10. ^ Swartz, Jordan S.; Betz, Vaugh; Rose, Jonathan. "A Fast Routability-Driven Router for FPGAs" (PDF). Department of Electrical and Computer Engineering, University of Toronto. 
  11. ^ Lysaght, Patrick; Blodget, Brandon; Mason, Jeff; Young, Jay; Bridgford, Brendan (2006). "Invited paper: Enhanced architectures, design methodologies and cad tools for dynamic reconfiguration of xilinx fpgas". 2006 International Conference on Field Programmable Logic and Applications. IEEE. 
  12. ^ Xilinx® Inc. "XST Synthesis Overview". Xilinx® Inc. Retrieved 20 June 2016. 
  13. ^ Altera Corporation. "Spectra-Q™ Engine". Altera Corporation. Retrieved 20 June 2016. 
  14. ^ LLVM community. "The LLVM Target-Independent Code Generator". LLVM Documentation. Retrieved 17 June 2016. 
  15. ^ Lattner, Chris. "LLVM". In Brown, Amy; Wilson, Greg. The Architecture of Open Source Applications (1 ed.). 
  16. ^ Chlipala, Adam. "Syntactic Proofs of Compositional Compiler Correctness" (PDF). Harvard University Cambridge, Massachusetts, USA. 
  17. ^ ETAPS – European Joint Conferences on Theory and Practice of Software. Cf. "CC" (Compiler Construction) subsection.


  1. Compiler textbook references A collection of references to mainstream Compiler Construction Textbooks
  2. Aho, Alfred V.; Sethi, Ravi; Ullman, Jeffrey D. (1986). Compilers: Principles, Techniques, and Tools (1st ed.). Addison-Wesley. ISBN 9780201100884. 
  3. Allen, Frances E. (September 1981). "A History of Language Processor Technology in IBM" (PDF). IBM Journal of Research and Development. IBM. 25 (5). doi:10.1147/rd.255.0535. (subscription required (help)). 
  4. Allen, Randy; Kennedy, Ken (2001). Optimizing Compilers for Modern Architectures. Morgan Kaufmann Publishers. ISBN 1-55860-286-0. 
  5. Appel, Andrew Wilson (2002). Modern Compiler Implementation in Java (2nd ed.). Cambridge University Press. ISBN 0-521-82060-X. 
  6. Appel, Andrew Wilson (1998). Modern Compiler Implementation in ML. Cambridge University Press. ISBN 0-521-58274-1. 
  7. Bornat, Richard (1979). Understanding and Writing Compilers: A Do It Yourself Guide (PDF). Macmillan Publishing. ISBN 0-333-21732-2. 
  8. Cooper, Keith D.; Torczon, Linda (2004). Engineering a Compiler. Morgan Kaufmann. ISBN 1-55860-699-8. 
  9. Leverett, Bruce W.; Cattell, R. G. G.; Newcomer, Joseph M.; Hobbs, S.O.; Reiner, A.H.; Schatz, B.R.; Wulf, W.A. (August 1980). "An Overview of the Production – Quality Compiler – Compiler Project". Computer. Carnegie-Mellon University. 13 (8): 38–49. doi:10.1109/MC.1980.1653748. ISSN 0018-9162. (subscription required (help)). 
  10. McKeeman, William Marshall; Horning, James J.; Wortman, David B. (1970). A Compiler Generator. Englewood Cliffs, NJ: Prentice-Hall. ISBN 0-13-155077-2. 
  11. Muchnick, Steven (1997). Advanced Compiler Design and Implementation. Morgan Kaufmann Publishers. ISBN 1-55860-320-4. 
  12. Scott, Michael Lee (2005). Programming Language Pragmatics (2nd ed.). Morgan Kaufmann. ISBN 0-12-633951-1. 
  13. Srikant, Y. N.; Shankar, Priti (2003). The Compiler Design Handbook: Optimizations and Machine Code Generation. CRC Press. ISBN 0-8493-1240-X. 
  14. Terry, Patrick D. (1997). Compilers and Compiler Generators: An Introduction with C++. International Thomson Computer Press. ISBN 1-85032-298-8. 
  15. Wirth, Niklaus (1996). Compiler Construction (PDF). Addison-Wesley. ISBN 0-201-40353-6. 

External links[edit]