what compiler is

Upload: chanakkaya

Post on 08-Apr-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 What Compiler Is

    1/16

    1

    What compiler is?

    The role of computers in daily life is growing each year. Modern microprocessors are found in cars,microwave ovens, dishwashers, mobile telephones, GPSS navigation systems, video games and personalcomputers. Each of these devices must be programmed to pe rform its job. Those programs are written insome programming language a formal language with mathematical properties and well-de ned

    meanings rather than a natural language with evolved properties and many ambiguities. Programminglanguages are designed for expressiveness, conciseness, and clarity. A program written in a programminglanguage must be translated before it can execute directly on a computer; this translation is accomplishedby a software system called a compiler.

    A compiler is just a computer program that takes as input an executable program and produces as outputan equivalent executable program.

    Definition (Compiler)

    While many issues in compiler design are amenable to several di erent solutions, there are two principlesthat should not be compromised.

    y The rst principle that a well- designed compiler must observe is inviolable.Th e compiler must preserve t h e meaning of t h e program being compiled.

    The code produced by the compiler must faithfully implement t he meaning of the source-codeprogram being compiled. If the compiler can take liberties with meaning, then it can always generate thesame code, independent of input. For example, the compiler could simply emit a nop or a returninstruction.

    y The second principle that a well-designed compiler must observe is quite practical.Th e compiler must improve t h e source code in some discernible way.

    If the compiler does not improve the code in some way, why should any -one invoke it? Atraditional compiler improves the code by making it directly executable on some target machine. Other

    compilers improve their input in di erent ways. For example, tpic is a program that takes thespeci cation for a drawing written in the graphics language pic, and converts it i nto L A TEX; the

    improvement lies in L A TEX s greater availability and generality. Some compilers produce output

    programs in the same language as their input; we call these source -to-source translators. In general,these systems try to restate the program in a way that will lead, eventually, to an improvement.

    Why study compilers?

    You may never write a commercial compiler, but that's not why we study compilers. We studycompiler construction for the following reasons:

    y Writing a compiler gives a student experience with large-scale applications development. Yourcompiler program may be the largest program you write as a student. Experience working with

  • 8/6/2019 What Compiler Is

    2/16

    2

    really big data structures and complex interactions between algorithms will help you out on yournext big programming project.

    y Compiler writing is one of the shining triumphs of CS theory. It demonstrates the value of theoryover the impulse to just "hack up" a solution.

    y Compiler writing is a basic element of programming language research. Many language researcherswrite compilers for the languages they design.

    y Many applications have similar properties to one or more phases of a compiler, and compilerexpertise and tools can help an application programmer working on other projects besides

    compilers.

    The name "compiler" is primarily used for programs that translate source code from a high-levelprogramming language to a lower level language (e.g., assembly language or machine language).

    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 translator , or language converter .

    A language rewriter is usually a program that translates the form of expressions without a change

    of language.

    H istory

    Software for early computers was exclusively written in assembly language for many years. Higher levelprogramming languages were not invented until the benefits of being able to reuse software on differentkinds of CPUs started to become significantly greater than the cost of writing a compiler. The very limitedmemory capacity of early computers also created many technical problems when implementing acompiler.

    Towards the end of the 1950s, machine -independent programming languages were first proposed.Subsequently, several experimental compilers were developed. The first compiler was written by GraceHopper, in 1952, for the A-0 programming language. The FORTRAN team led by John Backus at IBM isgenerally credited as having introduced the first complete compiler, in 1957. COBOL was an early languageto be compiled on multiple architectures, in 1960.

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

    Early compilers were written in assembly language. The first self-hosting compiler capable of compilingits own source code in a high-level language was created for Lisp by Hart and Levin at MIT in 1962. Sincethe 1970s it has become common practice to implement a compiler in the language it compiles, althoughboth Pascal and C have been popular choices for implementation language. Building a self -hosting compileris a bootstrapping problem -- the first such compiler for a language must be compiled either by a

  • 8/6/2019 What Compiler Is

    3/16

    3

    c e writt e in a diff e rent languag e or (a s in Hart and L evin' s Lis compil er) compil ed b y running th e compil er in an int e rpr e ter.

    Co pil s in du tion

    Compil er con stru ction and compil er optimization ar e taught at uni ve rsities as part of th e comput er science curri culum. Such cour ses ar e usuall y suppl ement ed with th e impl ementation of a compil er for an

    edu cational programming languag e. A well-do cum ent ed e

    ampl e is Niklau s Wirth' s PL/0 compil e r, whi chWirth u se d to t e ach compil er con stru ction in th e 1970s .[3] In spit e of it s simplicity, th e PL/0 compil erintrodu ce d seve ral influ ential con ce pt s to th e field:

    1. Program d eve lopm e nt b y stepwi se re fine ment (al so th e titl e ofa 1971 pap e r b y Wirth)2. The use of a r ec ur sive desce nt par se r3. The use of EBNF to spec if y th e syntax of a languag e 4. A cod e generator produ cing portabl e P-cod e 5. The use of T-diagram s in th e formal d esc ription of th e boot strapping probl e m

    Co pil output

    O ne method u se d to classif y compil ers is by th e platform on whi ch th e generat ed cod e th ey produ ce exec ut es . This is known a s th e targ e t platform.

    A na v or ho d compil e r is on e who se output i s int end ed to dir ec tly run on th e sam e type of comput e rand op erating sys tem a s th e compil er it se lf run s on. Th e output of a cro ss compil er is des ign ed to run on adiff e rent platform. C ro ss compil e rs ar e oft en u se d wh en d eve loping softwar e fore mb edd ed sys te ms thatar e not int end ed to support a softwar e deve lopm ent environm e nt.

  • 8/6/2019 What Compiler Is

    4/16

    4

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

    Compiled versus interpreted languages

    Higher-level programming languages are generally divided for convenience into compiled languages andinterpreted languages. However, there is rarely anything about a language that requires it to be exclusively

    compiled, or exclusively interpreted. The categorization usually reflects the most popular or widespreadimplementations of a language for instance, BASI C is thought of as an interpreted language, and C acompiled one, despi te the existence of BASI C compilers and C interpreters.

    In a sense, all languages are interpreted, with "execution" being merely a special case of interpretationperformed by transistors switching on a CPU. Modern trends toward just-in-time compilation and bytecodeinterpretation also blur the traditional categorizations.

    There are exceptions. Some language specifications spell out that implementations must include acompilation facility; for example, Common Lisp. Other languages have features that are very easy toimplement in an interpreter, but make writing a compiler much harder; for example, APL, SNOBOL 4, and

    many scripting languages allow programs to construct arbitrary source code at runtime with regular stringoperations, and then execute that code by passing it to a special evaluation function. To implement thesefeatures in a compiled language, programs must usually be shipped with a runtime library that includes aversion of the compiler itself.

    H ardware compilation

    The output of some compilers may target hardware at a very low level. For example a Field ProgrammableGate Array (FPGA) or structured Application-specific integrated circuit (ASI C). Such compilers are said to behardware compilers or synthesis tools because the programs they compile effectively control the finalconfiguration of the hardware and how it operates; the output of the compilation are not instructions thatare executed in sequence - only an interconnection of transistors or lookup tables. For example, XST is theXilinx Synthesis Tool used for configuring FPGAs. Similar tools are available from Altera, Synplicity,Synopsys and other vendors.

    Compiler design

    The approach taken to compiler design is affected by the complexity of the processing that needs to bedone, the experience of the person(s) designing it, and the resources (eg, people and tools) 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 designmay be split into a number of relatively independent phases, or passes. Having separate phases meansdevelopment can be parceled up into small parts and given to different people. It also becomes mucheasier to replace a single phase by an improved one, or to insert new phases later (eg, additionaloptimizations).

    The division of the compilation processes in phases (or passes) was championed by the Production QualityCompiler- Compiler Project (PQ CC) at Carnegie Mellon University. This project introduced the terms front end , middle end (rarely heard today), and back end .

  • 8/6/2019 What Compiler Is

    5/16

    5

    All but the smallest of compilers have more than two phases. However, these phases are usually regardedas being part of the front end or the back end. The point at where these two ends meet is always open todebate. The front end is generally considered to be where syntactic and semantic processing takes place,along with translation to a lower level of representation (than source code).

    The middle end is usually designed to perform optimizations on a form other than the source code ormachine code. This source code/machine code independence is intended to enable generic optimizationsto be shared between versions of the compiler supporting different languages and target processors.

    The back end takes the output from the middle. It may perform more analysis, transformations andoptimizations that are for a particular computer. Then, it generates code for a particular processor and OS.

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

    O ne-pass versus multi-pass 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 memoryto contain one program that did all of this work. So compilers were split up into smaller programs whicheach made a pass over the source (or some representation of it) performing some of the required analysisand translations.

    The ability to compile in a single pass is often seen as a benefit because it simplifies the job of writing acompiler and one pass compilers are generally faster than multi-pass compilers. Many languages weredesigned 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 passover the source. For instance, consider a declaration appearing on line 20 of the source which affects thetranslation of a statement appearing on line 10. In this case, the first pass needs to gather informationabout declarations appearing after statements that they affect, with the actual translation happeningduring a subsequent pass.

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

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

    While the typical multi-pass compiler outputs machine code from its final pass, there are several othertypes:

    y A "source-to-source compiler" is a type of compiler that takes a high level language as its input andoutputs a high level language. For example, an automatic parallelizing compiler will frequently takein a high level language program as an input and then transform the code and annotate it withparallel code annotations (e.g. OpenMP) or language constructs (e.g. Fortran's DOALL statements).

  • 8/6/2019 What Compiler Is

    6/16

    6

    y Stage compiler that compiles to assembly language of a theoretical machine, like some Prologimplementations

    o This Prolog machine is also known as the Warren Abstract Machine (or WAM). Bytecodecompilers for Java, Python, and many more are also a subtype of this.

    y Just-in-time compiler, used by Smalltalk and Java systems, and also by Microsoft .Net's CommonIntermediate Language ( CIL)

    o Applications are delivered in bytecode, which is compiled to native machine code just priorto execution.

    H ow does a compiler work?

    From the diagram on the next page, you can see there are two main stages in the compiling process:analysis and synthesis. The analysis stage breaks up the source program into pieces, and creates ageneric (language-independent) intermediate representation of the program. Then, the synthesis stageconstructs the desired target program from the intermediate representation. Typically, a compiler sanalysis stage is called its front-end and the synthesis stage its back-end. Each of the stages is brokendown into a set of "phases" that handle different parts of the tasks. (Why do you think typicalcompilersseparate the compilation process into front and back -end phases?)

    Front-End Analysis Stage

    There are four phases in the analysis stage of compiling:

    1) Lexical Analysis or Scanning: The stream of characters making up a source program is read from left toright and grouped into tokens, which are sequences of characters that have a collective meaning.Examples of tokens are identifiers (user-defined names), reserved words, integers, doubles or floats,delimiters, operators, and special symbols.

  • 8/6/2019 What Compiler Is

    7/16

    7

    Example of lexical analysis:int a;a = a + 2;

    A lexical analyzer scanning the code fragment above might return:

    2) Syntax Analysis or Parsing: The tokens found during scanning are grouped together

    using a context-free grammar. A grammar is a set of rules that define valid structures in the programminglanguage. Each token is associated with a specific rule, and grouped together accordingly. This process iscalled parsing. The output of this phase is called a parse tree or a derivation, i.e., a record of whichgrammar rules were used to create the source program.

    Example of syntax analysis:

    Part of a grammar for simple arithmetic expressions in C might look like this:

    The symbol on the left side of the "->" in each rule can be replaced by the symbols on the right. To parse a+ 2, we would apply the following ru les:

    When we reach a point in the parse where we have only tokens, we have finished.

    By knowing which rules are used to parse, we can determine the structures present in the source program.A source program which can be parsed is syntactically correct.

  • 8/6/2019 What Compiler Is

    8/16

    8

    3) Semantic Analysis: The parse tree or derivation is checked for semantic errors i.e., a statement that issyntactically correct (associates with a grammar rule correctly).

    However, a syntactically correct statement may disobey the semantic rules of the source language.Semantic analysis is the phase where we detect such things as use of an undeclared variable, a functioncalled with improper arguments, access violations, and incompatible operands and type mismatches.

    Example of semantic analysis:

    int arr [2], c;c = arr * 10;

    A lot of the semantic analysis work pertains to type checking. Although the C fragment above will scan intovalid tokens and successfully match the rules for a valid expression, it isn't semantically valid. In thesemantic analysis phase, the compiler checks the types and reports that you cannot use an array variable ina multiplication expression.

    4 ) Intermediate Code Generation: This is where the intermediate representation of the source program iscreated. We want this representation to be easy to generate, and easy to translate into the target

    program. The representation can have a variety of forms, but a common one is called three-address code(TAC), which is a lot like a generic assembly language. Three-address code is a sequence of simpleinstructions, each of which can have at most three operands.

    Example of intermediate code generation:

    The single C statement on the left is translated into a sequence of four instructions in three -address code

    on the right. Note the use of temp variables that are created by the compiler as needed to keep thenumber of operands down to three. Of course, it's a little more complicated than this, because we have totranslate branching and looping instructions, as well as function calls. Here is some TA C for a branchingtranslation:

    The synthesis stage (back-end)

    There can be up to three phases in the synthesis stage of compiling:

    1) Intermediate Code Optimization: The optimizer accepts input in the intermediate repr esentation (e.g.,TAC) and outputs a streamlined version still in the intermediate representation. In this phase, the compilerattempts to produce the smallest, fastest and most efficient running result by applying various techniquessuch as:

  • 8/6/2019 What Compiler Is

    9/16

    9

    inhibiting code generation of unreachable code segmentsgetting rid of unused variableseliminating multiplication by 1 and addition by 0loop optimization (e.g., remove statements that are not modified in the loop)common sub-expression eliminationstrength reduction

    .....

    The optimization phase can really slow down a compiler, so most compilers allow this feature to besuppressed. The compiler may have fine-grain controls that allow a developer to make tradeoffs betweencompilation time and optimization quality.

    Example of code optimization:

    In the example shown above, the optimizer eliminated an addition to the zero and a re -evaluation of thesame expression, allowing the original five TA C statements to be re-written in just three statements anduse two fewer temporary variables.

    2) O bject Code Generation: This is where the target program is generated. The output of this phase isusually machine code or assembly code. Memory locations are selected for each variable. Instructions arechosen for each operation. The three-address code is translated into a sequence of assembly or machinelanguage instructions that perform the same tasks.

    Example of code generation:

    In the example above, the code generator translated the TA C input into Sparc assembly output.

    3) O bject Code O ptimization: There may also be another optimization pass that follows code generation,this time transforming the object code into tighter, more efficient object code. This is where we considerfeatures of the hardware itself to make efficient usage of the processor(s) and registers. The compiler cantake advantage of machine-specific idioms (specialized instructions, pipelining, branch prediction, andother peephole optimizations) in reorganizing and streamlining the object code itself. As with IRoptimization, this phase of the compi ler is usually configurable or can be skipped entirely.

  • 8/6/2019 What Compiler Is

    10/16

    10

    Front end

    The front end analyzes the source code to build an internal representation of the program, called theintermediate representation or IR . It also manages the symbol table, a data structure mapping each symbolin the source code to associated information such as location, type and scope. This is done over severalphases, which includes some of the following:

    1. Line reconstruction . Languages which strop their keywords or allow arbitrary spaces withinidentifiers require a phase before parsing, which converts the input character sequence to acanonical form ready for the parser. The top-down, recursive-descent, table-driven parsers used inthe 1960s typically read the source one character at a time and did not require a separatetokenizing phase. Atlas Autocode, and Imp (and some implementations of Algol and Coral66) areexamples of stropped languages whose compilers would have a Line R econstruction phase.

    2. Lexical analysis breaks the source code text into small pieces called tokens . Each token is a singleatomic unit of the language, for instance a keyword, identifier or symbol name. The token syntax istypically a regular language, so a finite state automaton constructed from a regular expression canbe 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.3. Preprocessing. Some languages, e.g., C, require a preprocessing phase which supports macrosubstitution and conditional compilation. Typically the preprocessing phase occurs before syntacticor semantic analysis; e.g. in the case of C, the preprocessor manipulates lexical tokens rather thansyntactic forms. However, some languages such as Scheme support macro substitutions based onsyntactic forms.

    4. Syntax analysis involves parsing the token sequence to identify the syntactic structure of theprogram. This phase typically builds a parse tree, which replaces the linear sequence of tokens witha tree structure built according to the rules of a formal grammar which define the language'ssyntax. The parse tree is often analyzed, augmented, and transformed by later phases in thecompiler.

    5.

    Semantic analysis is the phase in which the compiler adds semantic information to the parse treeand builds the symbol table. This phase performs semantic checks such as type checking (checkingfor type errors), or object binding (associating variable and function references with theirdefinitions), or definite assignment (requiring all local variables to be initialized before use),rejecting incorrect programs or issuing warnings. Semantic analysis usually requires a completeparse tree, meaning that this phase logically follows the parsing phase, and logically precedes thecode generation phase, though it is often possible to fold multiple phases into one pass over thecode in a compiler implementation.

    Back end

    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 andoptimization phases in the back end from the machine -dependent code generators.

    The main phases of the back end include the following:

  • 8/6/2019 What Compiler Is

    11/16

    11

    1. Analysis: This is the gathering of program information from the intermediate representationderived from the input. Typical analyses are data flow analysis to build use-define chains,dependence analysis, alias analysis, pointer analysis, escape analysis etc. Accurate analysis is thebasis for any compiler optimization. The call graph and control flow graph are usually also builtduring the analysis phase.

    2. Optimization: the intermediate language representation is transformed into functionally equivalentbut faster (or smaller) forms. Popular optimizations are inline expansion, dead code elimination,constant propagation, loop transformation, register allocation or 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 schedulingof appropriate machine instructions along with their associated addressing modes (see also Sethi-Ullman algorithm).

    Compiler analysis is the prerequisite for any compiler optimization, and they tightly work together. Forexample, 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 tothe procedure/function 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 scopeanalysis and optimizations are very costly in terms of compilation time and memory space; this is especiallytrue 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 G CC was criticized for a long time for lackingpowerful interprocedural optimizations, but it is changing in this respect. Another good open sourcecompiler with full analysis and optimization infrastructure is Open6 4, which is used by many organizationsfor research and commercial purposes.

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

    R elated techniques

    Assembly language is not a high-level language and a program that compiles it is more commonly known asan 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 tosource translator , language converter , or language rewriter . The last term is usually applied to translationsthat do not involve a change of language.

    Cross compiler

    A cross compiler is a compiler capable of creating executable code for a platform other than the one onwhich the compiler is run. Cross compiler tools are generally found in use to generate compiles forembedded system or multiple platforms. It is a tool that one must use for a platform where it isinconvenient or impossible to compile on that platform, like microcontrollers that run with a minimal

  • 8/6/2019 What Compiler Is

    12/16

    1 2

    amount of memory for their own purpose. It has become more common to use this tool forparavirtualization where a system may have one or more platforms in use.

    Not targeted by this definition are source to source translators, which are often called by the name of crosscompiler.

    U ses of cross compilers

    The fundamental use of a cross compiler is to separate the build environment from the targetenvironment. This is useful in a number of situations:

    y Embedded computers where a device has extremely limited resources. For example, a microwaveoven will have an extremely small computer to read its touchpad and door sensor, provide outputto a digital display and speaker, and to control the machinery for cooking food. This computer willnot be powerful enough to run a compiler, a file system, or a development environment. Sincedebugging and testing may also require more resources than are available on an embedded system,cross-compilation can be less involved and less prone to errors than native co mpilation.

    y Compiling for multiple machines. For example, a company may wish to support several differentversions of an operating system or to support several different operating systems. By using a cross

    compiler, a single build environment can be set up to compile for each of these targets.y Compiling on a server farm. Similar to compiling for multiple machines, a complicated build that

    involves many compile operations can be executed across any machine that is free regardless of itsbrand or current version of an operating system.

    y Bootstrapping to a new platform. When developing software for a new platform, or the em ulator of a future platform, one uses a cross compiler to compile necessary tools such as the operatingsystem and a native compiler.

    y Compiling native code for emulators for older now-obsolete platforms like the Commdore 6 4 orApple II by enthusiasts who use cross compilers that run on a current platform (such as Aztec C'sMS DOS 6502 cross compilers running under Windows XP).

    Use of virtual machines (such as Java's JVM) resolves some of the reasons for which cross compilers weredeveloped. The virtual machine paradigm allows the same compiler output to be used across multipletarget systems.

    Typically the hardware architecture differs (e.g. compiling a program destined for the MIPS architecture onan x86 computer) but cross-compilation is also applicable when only the operating system environmentdiffers, as when compiling a FreeBSD program under Linux, or even just the system library, as whencompiling programs with u Clibc on a glibc host.

    Bootstrapping (compilers)

    From Wikipedia, the free encyclopedia

    Bootstrapping is a term used in computer science to describe the techniques involved in writing a compiler(or assembler) in the target programming language which it is intended to compile.

    One may then wonder how the chicken and egg problem of creating the compiler was solved: if one needsa compiler for language X to obtain a compiler for language X, how did the first compiler get written?Possible methods include:

  • 8/6/2019 What Compiler Is

    13/16

    13

    y Implementing an interpreter or compiler for language X in language Y. Niklaus Wirth reported thathe wrote the first Pascal compiler in Fortran. Language Ycould also be hand coded machine code orassembly language.

    y Another interpreter or compiler for X has already been written in another language Y; this is howScheme is often bootstrapped.

    y Earlier versions of the compiler were written in a subset of X for which there existed some othercompiler; this is how some supersets of Java are bootstrapped.

    y The compiler for X is cross compiled from another architecture where there exists a compiler for X;

    this is how compilers for C are usually ported to other platformsy Writing the compiler in X; then hand -compiling it from source (most likely in a non-optimized way)

    and running that on the code to get an optimized compiler. Donald Knuth used this for his WEBliterate programming system.

    Methods for distributing compilers in source code include providing a portable bytecode version of thecompiler, so as to bootstrap the process of compiling the compiler with itself.

    The first language to provide such a bootstrap was NELIA C. The first commercial language to do so wasPL/I. Today, a large proportion of programming languages are bootstrapped, including Basic, C, Pascal,Factor, Haskell, Modula-2, Oberon, O Caml, Common Lisp, Scheme and more.

    Assembler

    Typically a modern assembler creates object code by translating assembly instruction mnemonics intoopcodes, and by resolving symbolic names for memory locations and other entities. [1] The use of symbolicreferences is a key feature of assemblers, saving tedious calculations and manual address updates afterprogram modifications. Most assemblers also include macro facilities for performing textual substitutione.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 availablesince the 1950s. Modern assemblers, especially for RIS C based architectures, such as MIPS, Sun SPAR C andHP PA-RISC, optimize instruction scheduling to exploit the CPU pipeline efficiently.

    More sophisticated high-level assemblers provide language abstractions such as:

    y Advanced control structuresy High-level procedure/function declara tions and invocationsy High-level abstract data types, including structures/records, unions, classes, and setsy Sophisticated macro processingy Object-Oriented features such as encapsulation, polymorphism, inheritance, interfaces

    See Language design below for more details.

    Note that, in normal professional usage, the term assembler is often used ambiguously: It is frequentlyused to refer to an assembly language itself, rather than to the assembler utility. Thus: " CP/ CMS waswritten in S/ 360 assembler" as opposed to "ASM-H was a widely-used S/ 370 assembler."

    linker or link editor

  • 8/6/2019 What Compiler Is

    14/16

    1 4

    In computer science, a linker or link editor is a program that takes one or more objects generated by acompiler and assembles them into a single executable program.

    In IBM mainframe environments such as OS/ 360 this program is known as a linkage editor .

    On Unix variants the term loader is often used as a synonym for linker . Because this usage blurs thedistinction between the compile-time process and the run-time process, this article will use linking for theformer and loading for the latter. However, in some operating systems the same program handles both the

    jobs of linking and loading a program; see dynamic linking .

    Computer programs are typically comprised of several parts or modules; these parts, if not all containedwithin a single object file, refer to each other by means of symbols. Typically, an object file can containthree kinds of symbols:

    y defined symbols, which allow it to be called by other modules,y undefined symbols, which call the other modules where these symbols are defined, andy local symbols, used internally within the object file to facilitate relocation.

    When a program comprises multiple object files, the linker combines these files into a unified executable

    program, resolving the symbols as it goes along.

    Linkers can take objects from a collection called a library . Some linkers do not include the whole library inthe output; they only include its symbols that are referenced from other object files or libraries. Librariesexist for diverse purposes, and one o r more system libraries are usually linked in by default.

    The linker also takes care of arranging the objects in a program's address space. This may involve relocating code that assumes a specific base address to another base. Since a compiler seldom knows where anobject will reside, it often assumes a fixed base location (for example, zero). Relocating machine code mayinvolve re-targeting of absolute jumps, loads and stores.

    The executable output by the linker may need another relocation pass when it is finally loaded intomemory (just before execution). This pass is usually omitted on hardware offering virtual memory everyprogram is put into its own address space, so there is no conflict even if all programs load at the same baseaddress. This pass may also be omitted if the executable is a position independent executable.

    Contents

    y 1 Dynamic linkingy 2 Relaxationy 3 Referencesy 4 See alsoy 5 External links

    D ynamic linking

    Modern operating system environments allow dynamic linking , that is the postponing of the resolving of some undefined symbols until a program is run. That means that the executable still contains undefinedsymbols, plus a list of objects or libraries that will provide definitions for these. Loading the program willload these objects/libraries as well, and perform a final linking.

  • 8/6/2019 What Compiler Is

    15/16

    1 5

    This approach offers two advantages:

    y Often-used libraries (for example the standard system libraries) need to be stored in only onelocation, not duplicated in every single binary.

    y If an error in a library function is corrected by replacing the library, all programs using it dynamicallywill benefit from the correction after restarting them. Programs that included this function by staticlinking would have to be re -linked first.

    loader

    In computing, a loader is the part of an operating system that is responsible for loading programs fromexecutables (i.e., executable files) into memory, preparing them for execution and then executing them.The loader is usually a part of the operating system's kernel and usually is loaded at system boot time andstays in memory until the system is rebooted, shut down, or powered off. Some operating systems thathave a pageable kernel may have the loader in the pageable part of memory and thus the loadersometimes may be swapped out of memory. All operating systems that support program loading haveloaders. Some embedded operating systems in highly specialized computers run only one program andhave no program loading capabilities and thus no loaders, for example embedded systems in cars or stereoequipment.

    In Unix, the loader is the handler for the system call execve() .[1] The loader's tasks under Unix include: (1)validation (permissions, memory requirements etc.); (2) copying the program image from the disk intomain memory; ( 3) copying the command-line arguments on the stack; ( 4) initializing registers (e.g., thestack pointer); (5) jumping to the program entry point (_start).

    Loader programs are useful for prototyping, testing, and one-off applications. One such program was anintegral part of Gene Amdahl's original OS/ 360 operating system, and this loader facility was continuedthrough OS/ 360's descendants including MVT, MVS and z/OS.

    In computer science, runtime or run time describes the operation of a computer program, the duration of its execution, from beginning to termination (compare compile time). The term runtime can also refer to avirtual machine to manage a program written in a computer language while it is running. R un time issometimes used to mean runtime library, a library of basic code that is used by a particular compiler butwhen used in this fashion, runtime library is more accurate.

    A runtime environment is a virtual machine state which provides software services for processes orprograms while a computer is running. It may pertain to the operating system itself, or the software thatruns beneath it. The primary purpose is to accomplish the objective of "platform independent"programming.

    Runtime activities include loading and linking of the classes needed to execute a program, optionalmachine code generation and dynamic optimization of the program, and actual program execution.

  • 8/6/2019 What Compiler Is

    16/16

    1 6

    For example, a program written in Java would receive services from the Java Runtime Environment byissuing commands from which the expected result is returned by the Java software. By providing theseservices, the Java software is considered the runtime environment of the program. Both the program andthe Java software combined request services from the operating system. The operating system kernelprovides services for itself and all processes and software running under its control. The Operating Systemmay be considered as providing a runtime environment for itself.

    In computer science, compile time refers to either the operations performed by a compiler (the "compile-

    time operations") or programming language requirements that must be met by source code for it to besuccessfully compiled (the "compile-time requirements").

    The operations performed at compile time usually include syntax analysis, various kinds of semanticanalysis (e.g., type checks and instantiation of template) and code generation.

    The definition of a programming language will specify compile-time requirements that source code mustmeet to be successfully compiled.

    Compile time occurs before link time (when the output of one or more compiled files are joined together)and runtime (when a program is executed). In some programming languages it may be necessary for some

    compilation and linking to occur at runtime.