compiler this article is about software to translate computer languages for the anime see compiler anime compile and compiling redirect here for the software company see compile company for other uses see compilation program execution general concepts code translation compiler compiletime optimizing compiler intermediate representation ir execution runtime system runtime executable interpreter virtual machine types of code source code object code bytecode machine code microcode compilation strategies justintime jit tracing justintime aheadoftime aot transcompilation recompilation notable runtimes android runtime art common language runtime clr mono crt0 hhvm java virtual machine jvm objectivec v8 nodejs pypy zend engine notable compilers toolchains gnu compiler collection gcc llvm clang vte a compiler is computer software that transforms computer code written in one programming language the source language into another programming language the target language compilers are a type of translator that support digital devices primarily computers the name compiler is primarily used for programs that translate source code from a highlevel programming language to a lower level language eg assembly language object code or machine code to create an executable program however there are many different types of compilers 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 a crosscompiler a bootstrap compiler is written in the language that it intends to compile a program that translates from a lowlevel language to a higher level one is a decompiler a program that translates between highlevel languages is usually called a sourcetosource compiler or transpiler a language rewriter is usually a program that translates the form of expressions without a change of language the term compilercompiler refers to tools used to create parsers that perform syntax analysis a compiler is likely to perform many or all of the following operations preprocessing lexical analysis parsing semantic analysis syntaxdirected translation conversion of input programs to an intermediate representation code optimization and code generation compilers implement these operations in phases that promote efficient design and correct transformations of source input to target output program faults caused by incorrect compiler behavior can be very difficult to track down and work around therefore compiler implementers invest significant effort to ensure compiler correctness compilers are not the only translators used to transform source programs an interpreter is computer software that transforms and then executes the indicated operations the translation process influences the design of computer languages which leads to a preference of compilation or interpretation in practice an interpreter can be implemented for compiled languages and compilers can be implemented for interpreted languages history history of compiler construction a diagram of the operation of a typical multilanguage multitarget compiler theoretical computing concepts developed by scientists mathematicians and engineers formed the basis of digital modern computing development during world war ii primitive binary languages evolved because digital devices only understand ones and zeros and the circuit patterns in the underlying machine architecture in the late 1940s assembly languages were created to offer a more workable abstraction of the computer architectures limited memory capacity of early computers led to substantial technical challenges when the first compilers were designed therefore the compilation process needed to be divided into several small programs the front end programs produce the analysis products used by the back end programs to generate target code as computer technology provided more resources compiler designs could align better with the compilation process the human mind can design better solutions as the language moves from the machine to a higher level so the development of highlevel languages followed naturally from the capabilities offered by the digital computers highlevel languages are formal languages that are strictly defined by their syntax and semantics which form the highlevel language architecture elements of these formal languages include alphabet any finite set of symbols string a finite sequence of symbols language any set of strings on an alphabet the sentences in a language may be defined by a set of rules called a grammar backusnaur form bnf describes the syntax of sentences of a language and was used for the syntax of algol 60 by john backus in the 1940s konrad zuse designed an algorithmic programming language called plankalkl plan calculus while no actual implementation occurred until the 1970s it presented concepts later seen in apl designed by ken iverson in the late 1950s apl is a language for mathematical computations highlevel language design during the formative years of digital computing provided useful programming tools for a variety of applications fortran formula translation for engineering and science applications is considered to be the first highlevel language cobol common businessoriented language evolved from a0 and flowmatic to become the dominant highlevel language for business applications lisp list processor for symbolic computation compiler technology evolved from the need for a strictly defined transformation of the highlevel source program into a lowlevel target program for the digital computer the compiler could be viewed as a front end to deal with analysis of the source code and a back end to synthesize the analysis into the target code optimization between the front end and back end could produce more efficient target code some early milestones in the development of compiler technology 1952 an autocode compiler developed by alick glennie for the manchester mark i computer at the university of manchester is considered by some to be the first compiled programming language 1952 grace hoppers team at remington rand wrote the compiler for the a0 programming language and coined the term compiler to describe it although the a0 compiler functioned more as a loader or linker than the modern notion of a full compiler 19541957 a team led by john backus at ibm developed fortran which is usually considered the first highlevel language in 1957 they completed a fortran compiler that is generally credited as having introduced the first unambiguously complete compiler 1959 the conference on data systems language codasyl initiated development of cobol the cobol design drew on a0 and flowmatic by the early 1960s cobol was compiled on multiple architectures 19581962 john mccarthy at mit designed lisp early operating systems and software were written in assembly language in the 60s and early 70s the use of highlevel languages for system programming was still controversial due to resource limitations however several research and industry efforts began the shift toward highlevel systems programming languages for example bcpl bliss b and c bcpl basic combined programming language designed in 1966 by martin richards at the university of cambridge was originally developed as a compiler writing tool but also provided a basis for the design of b and c languages bliss basic language for implementation of system software was developed for a digital equipment corporation dec pdp10 computer by wa wulfs carnegie mellon university cmu research team the cmu team went on to develop bliss11 compiler one year later in 1970 multics multiplexed information and computing service a timesharing operating system project involved mit bell labs general electric later honeywell and was led by fernando corbat from mit bell labs left the multics project in 1969 over time hope was replaced by frustration as the group effort initially failed to produce an economically useful system continued participation would drive up project support costs so researchers turned to other development efforts a system programming language b based on bcpl concepts was written by dennis ritchie and ken thompson ritchie created a bootstrapping compiler for b and wrote unics uniplexed information and computing service operating system for a pdp7 in b unics eventually became spelled unix bell labs started development and expansion of c based on b and bcpl the bcpl compiler had been transported to multics by bell labs and bcpl was a preferred language at bell labs objectoriented programming oop offered some interesting possibilities for application development and maintenance oop concepts go further back but were part of lisp and simula language science the cfront program implemented a c frontend for c84 language compiler in subsequent years several c compilers were developed as c popularity grew in many application domains the idea of using a higherlevel language quickly caught on because of the expanding functionality supported by newer programming languages and the increasing complexity of computer architectures compilers became more complex darpa defense advanced research projects agency sponsored a compiler project with wulfs cmu research team in 1970 the production quality compilercompiler pqcc design would produce a production quality compiler pqc from formal definitions of source language and the target pqcc tried to extend the term compilercompiler beyond the traditional meaning as a parser generator eg yacc without much success pqcc might more properly be referred to as a compiler generator pqcc research into code generation process sought to build a truly automatic compilerwriting system the effort discovered and designed the phase structure of the pqc the bliss11 compiler provided the initial structure variations of tcol supported various languages the pqcc project investigated techniques of automated compiler construction the design concepts proved useful in optimizing compilers and compilers for the objectoriented programming language ada the ada stoneman document formalized the program support environment apse along with the kernel kapse and minimal mapse an ada interpreter nyued supported development and standardization efforts with american national standards institute ansi and the international standards organization iso initial ada compiler development by the us military services included the compilers in a complete integrated design environment along the lines of the stoneman document army and navy worked on the ada language system als project targeted to decvax architecture while the air force started on the ada integrated environment aie targeted to ibm 370 series while the projects did not provide the desired results they did contribute to the overal effort on ada development other ada compiler efforts got under way in britain at university of york and in germany at university of karlsruhe in the u s verdix later acquired by rational delivered the verdix ada development system vads to the army vads provided a set of development tools including a compiler unixvads could be hosted on a variety of unix platforms such as dec ultrix and the sun 360 solaris targeted to motorola 68020 in an army cecom evaluation there were soon many ada compilers available that passed the ada validation tests the free software foundation gnu project developed the gnu compiler collection gcc which provides a core capability to support multiple languages and targets the ada version gnat is one of the most widely used ada compilers gnat is free but there is also commercial support for example adacore was founded in 1994 to provide commercial software solutions for ada gnat pro includes the gnu gcc based gnat with a tool suite to provide an integrated development environment highlevel languages continued to drive compiler research and development focus areas included optimization and automatic code generation trends in programming languages and development environments influenced compiler technology more compilers became included in language distributions perl java development kit and as a component of an ide vads eclipse ada pro the interrelationship and interdependence of technologies grew the advent of web services promoted growth of web languages and scripting languages scripts trace back to the early days of command line interfaces cli where the user could enter commands to be executed by the system user shell concepts developed with languages to write shell programs early windows designs offered a simple batch programming capability the conventional transformation of these language used an interpreter while not widely used bash and batch compilers have been written more recently sophisticated interpreted languages became part of the developers tool kit modern scripting languages include php python ruby and lua lua is widely used in game development all of these have interpreter and compiler support when the field of compiling began in the late 50s its focus was limited to the translation of highlevel language programs into machine code the compiler field is increasingly intertwined with other disciplines including computer architecture programming languages formal methods software engineering and computer security the compiler research the next 50 years article noted the importance of objectoriented languages and java security and parallel computing were cited among the future research targets compiler construction this section does not cite any sources please help improve this section by adding citations to reliable sources unsourced material may be challenged and removed september 2010 learn how and when to remove this template message a compiler implements a formal transformation from a highlevel source program to a lowlevel target program compiler design can define an end to end solution or tackle a defined subset that interfaces with other compilation tools eg preprocessors assemblers linkers design requirements include rigorously defined interfaces both internally between compiler components and externally between supporting toolsets in the early days the approach taken to compiler design was directly affected by the complexity of the computer language to be processed the experience of the persons designing it and the resources available resource limitations led to the need to pass through the source code more than once a compiler for a relatively simple language written by one person might be a single monolithic piece of software however as the source language grows in complexity the design may be split into a number of interdependent phases separate phases provide design improvements that focus development on the functions in the compilation process onepass versus multipass compilers 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 onepass compilers generally perform compilations faster than multipass 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 eg 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 threestage compiler structure compiler design regardless of the exact number of phases in the compiler design the phases can be assigned to one of three stages the stages include a front end a middle end and a back end the front end verifies syntax and semantics according to a specific source language for statically typed languages it performs type checking by collecting type information if the input program is syntactically incorrect or has a type error it generates errors and warnings highlighting them on the source code aspects of the front end include lexical analysis syntax analysis and semantic analysis the front end transforms the input program into an intermediate representation ir for further processing by the middle end this ir is usually a lowerlevel representation of the program with respect to the source code the middle end performs optimizations on the ir that are independent of the cpu architecture being targeted this source codemachine 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 eg out of a loop or specialization of computation based on the context eventually producing the optimized ir that is used by the back end the back end takes the optimized ir from the middle end it may perform more analysis transformations and optimizations that are specific for the target cpu architecture the back end generates the targetdependent assembly code performing register allocation in the process the back end performs instruction scheduling which reorders instructions to keep parallel execution units busy by filling delay slots although most algorithms for optimization are nphard heuristic techniques are welldeveloped and currently implemented in productionquality compilers typically the output of a back end is machine code specialized for a particular processor and operating system this frontmiddlebackend approach makes it possible to combine front ends for different languages with back ends for different cpus while sharing the optimizations of the middle end and the amsterdam compiler kit which have multiple frontends shared optimizations and multiple backends front end lexer and parser example for c starting from the sequence of characters ifnet00totalnet10tax1000 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 contextfree parts of the grammar for c respectively the front end analyzes the source code to build an internal representation of the program called the intermediate representation 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 scanning or parsing and semantic analysis lexing 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 contextfree grammars which simplifies analysis significantly with contextsensitivity 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 and parsing as 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 the main phases of the front end include the following line reconstruction converts the input character sequence to a canonical form ready for the parser languages which strop their keywords or allow arbitrary spaces within identifiers require this phase the topdown recursivedescent tabledriven 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 preprocessing supports macro substitution and conditional compilation typically the preprocessing phase occurs before syntactic or semantic analysis eg 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 lexical analysis also known as lexing or tokenization breaks the source code text into a sequence of small pieces called lexical tokens common token categories may include identifiers keywords separators operators literals and comments although the set of token categories varies in different programming languages the lexeme syntax is typically a regular language so a finite state automaton constructed from a regular expression can be used to recognize it the software doing lexical analysis is called a lexical analyzer this may not be a separate stepit can be combined with the parsing step in scannerless parsing in which case parsing is done at the character level not the token level syntax analysis also known as parsing 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 languages syntax the parse tree is often analyzed augmented and transformed by later phases in the compiler semantic analysis 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 the middle end performs optimizations on the intermediate representation in order to improve the performance and the quality of the produced machine code the middle end contains those optimizations that are independent of the cpu architecture being targeted the main phases of the middle end include the following analysis this is the gathering of program information from the intermediate representation derived from the input dataflow analysis is used to build usedefine chains together with dependence analysis alias analysis pointer analysis escape analysis etc accurate analysis is the basis for any compiler optimization the control flow graph of every compiled function and the call graph of the program are usually also built during the analysis phase 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 and even automatic parallelization compiler analysis is the prerequisite for any compiler optimization and they tightly work together for example dependence analysis is crucial for loop transformation the scope of compiler analysis and optimizations vary greatly from as small as a basic block to the procedurefunction level or even over the whole program interprocedural optimization obviously 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 free software 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 back end the back end is responsible for the cpu architecture specific optimizations and for code generation the main phases of the back end include the following machine dependent optimizations optimizations that depend on the details of the cpu architecture that the compiler targets a prominent example is peephole optimizations which rewrites short sequences of assembler instructions into more efficient instructions 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 sethiullman algorithm debug data may also need to be generated to facilitate debugging compiler correctness 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 techniques include developing the compiler using formal methods and using rigorous testing often called compiler validation on an existing compiler compiled versus interpreted languages this section does not cite any sources please help improve this section by adding citations to reliable sources unsourced material may be challenged and removed october 2018 learn how and when to remove this template message higherlevel 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 reinterpretation 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 further compilers can contain interpreters for optimization reasons for example where an expression can be executed during compilation and the results inserted into the output program then it prevents it having to be recalculated each time the program runs which can greatly speed up the final program modern trends toward justintime compilation and bytecode interpretation at times blur the traditional categorizations of compilers and interpreters even further 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 types 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 whose 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 highlevel programming language c often viewed as some sort of portable assembler can also be the target language of a compiler eg 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 eg c code with line directives can be generated to support debugging of the original source while a common compiler type outputs machine code there are many other types a sourcetosource compiler is a type of compiler that takes a highlevel language as its input and outputs a highlevel language for example an automatic parallelizing compiler will frequently take in a highlevel language program as an input and then transform the code and annotate it with parallel code annotations eg openmp or language constructs eg fortrans doall statements bytecode compilers that compile to assembly language of a theoretical machine like some prolog implementations this prolog machine is also known as the warren abstract machine or wam bytecode compilers for java python are also examples of this category justintime compiler jit compiler is the last part of a multipass compiler chain in which some compilation stages are deferred to runtime examples are implemented in smalltalk java and microsoft nets common intermediate language cil systems applications are first compiled using a bytecode compiler and delivered in a machineindependent intermediate representation this bytecode is then compiled using a jit compiler to native machine code just when the execution of the program is required 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 fieldprogrammable gate array fpga or structured applicationspecific integrated circuit asic 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 the xilinx synthesis tool used for configuring fpgas an assembler is a program that compiles assembly language a type of lowlevel language with the inverse program known as a disassembler a program that translates from a lowlevel language to a higher level one is a decompiler a program that translates between highlevel languages is usually called a language translator sourcetosource compiler language converter or language rewriter 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 a program that rewrites object code back into the same type of object code while applying optimisations and transformations is a binary recompiler computer programming portal book compiler construction abstract interpretation bottomup parsing compile and go loader compile farm list of compilers list of important publications in computer science compilers metacompilation notes llvm community the llvm targetindependent code generator llvm documentation retrieved 17 june 2016 compiler textbook references a collection of references to mainstream compiler construction textbooks aho alfred v sethi ravi ullman jeffrey d 1986 compilers principles techniques and tools 1st ed addisonwesley isbn9780201100884 allen frances e september 1981 a history of language processor technology in ibm pdf ibm journal of research and development ibm 25 5 doi101147rd2550535 subscription required help allen randy kennedy ken 2001 optimizing compilers for modern architectures morgan kaufmann publishers isbn1558602860 appel andrew wilson 2002 modern compiler implementation in java 2nd ed cambridge university press isbn052182060x appel andrew wilson 1998 modern compiler implementation in ml cambridge university press isbn0521582741 bornat richard 1979 understanding and writing compilers a do it yourself guide pdf macmillan publishing isbn0333217322 cooper keith daniel torczon linda 2012 engineering a compiler 2nd ed amsterdam elseviermorgan kaufmann p8 isbn9780120884780 oclc714113472 mckeeman william marshall horning james j wortman david b 1970 a compiler generator englewood cliffs nj prenticehall isbn0131550772 muchnick steven 1997 advanced compiler design and implementation morgan kaufmann publishers isbn1558603204 scott michael lee 2005 programming language pragmatics 2nd ed morgan kaufmann isbn0126339511 srikant y n shankar priti 2003 the compiler design handbook optimizations and machine code generation crc press isbn084931240x terry patrick d 1997 compilers and compiler generators an introduction with c international thomson computer press isbn1850322988 wirth niklaus 1996 compiler construction pdf addisonwesley isbn0201403536 look up compiler in wiktionary the free dictionary wikibooks has a book on the topic of compiler construction wikimedia commons has media related to compilers compilers at curlie incremental approach to compiler construction a pdf tutorial compilehowto basics of compiler design by torben gidius mogensen short animation on youtube explaining the key conceptual difference between compilers and interpreters syntax analysis ll1 parsing on youtube lets build a compiler by jack crenshaw forum about compiler development authority control bne xx532454 bnf cb120631538 data gnd 41482487 lccn sh86007588 ndl 01191219 