SlideShare ist ein Scribd-Unternehmen logo
1 von 4
Downloaden Sie, um offline zu lesen
Course Overview                                                     Chapter 3 Compilation
PART I: overview material                                                 So far we have treated language processors (including
     1    Introduction                                                      compilers) as “black boxes”
     2    Language processors (tombstone diagrams, bootstrapping)
     3    Architecture of a compiler                                      GOAL this lecture:
PART II: inside a compiler                                                  – A first look "inside the box": how to build compilers.
     4    Syntax analysis                                                   – Different “phases” and their relationships.
     5    Contextual analysis
     6    Runtime organization
     7    Code generation
PART III: conclusion
     8    Interpretation
     9    Review
Compilation (Chapter 3)                                             1   Compilation (Chapter 3)                                                      2




               The Major “Phases” of a Compiler                                           Different Phases of a Compiler
                                                                         The different phases can be seen as different
            Source Program                                                 transformation steps to transform source code into
                                                                           object code.
            Syntax Analysis                        Error Reports         The different phases correspond roughly to the different
                          Abstract Syntax Tree                             parts of the language specification:
          Contextual Analysis                      Error Reports         • Syntax analysis <-> Syntax
                                                                         • Contextual analysis <-> Contextual constraints
                          Decorated Abstract Syntax Tree
                                                                         • Code generation <-> Semantics
           Code Generation


              Object Code

Compilation (Chapter 3)                                             3   Compilation (Chapter 3)                                                      4




                             Example Program                                                       1) Syntax Analysis
 We now look at each of the three different phases in a little
  more detail. We look at each of the steps in transforming                   Source Program
  an example Triangle program into TAM code.
                                                                             Syntax Analysis                        Error Reports
  ! This program is useless except for
  ! This program is useless except for
  ! illustration
  ! illustration
  let var n: integer;
  let var n: integer;                                                       Abstract Syntax Tree      Note: Not all compilers construct an
                                                                                                       Note: Not all compilers construct an
       var c: char
       var c: char                                                                                    explicit representation of an AST. (e.g. on
                                                                                                       explicit representation of an AST. (e.g. on
  in begin
  in begin                                                                                            a “single pass compiler” generally no need
                                                                                                       a “single pass compiler” generally no need
     c := ‘&’;
      c := ‘&’;                                                                                       to construct an AST)
                                                                                                       to construct an AST)
     n := n+1
      n := n+1
  end
  end



Compilation (Chapter 3)                                             5   Compilation (Chapter 3)                                                      6




                                                                                                                                                         1
1) Syntax Analysis --> AST                                                                   2) Contextual Analysis --> Decorated AST
                                       Program                                                                           Abstract Syntax Tree
                                    LetCommand
                                                                                                           Contextual Analysis                       Error Reports
                                                          SequentialCommand
                                                                                                                         Decorated Abstract Syntax Tree
           SequentialDeclaration                                      AssignCommand
                                                                                                          Contextual analysis:
                                            AssignCommand                    BinaryExpr
                                                                                                             • Scope checking: verify that all applied occurrences of
                                                                                                               identifiers are declared
        VarDecl                VarDecl              Char.Expr         VNameExp Int.Expr                      • Type checking: verify that all operations in the program are
                                                                                                               used according to their type rules.
           SimpleT                SimpleT SimpleV                     SimpleV
                                                                                                          Annotate AST:
 Ident      Ident         Ident    Ident     Ident Char.Lit Ident       Ident Op Int.Lit                     • Applied identifier occurrences => declaration
                                                                                                             • Expressions => Type
    n     Integer          c      Char        c       ‘&’         n          n      +    1
Compilation (Chapter 3)                                                                              7   Compilation (Chapter 3)                                                  8




         2) Contextual Analysis --> Decorated AST                                                                                      Contextual Analysis
                                       Program                                                             Finds scope and type errors.
                                    LetCommand                                                            Example 1:
                                                                                                                   AssignCommand         ***TYPE ERROR
                                                          SequentialCommand                                                              (incompatible types in AssignCommand)
                                                                                                                        :char :int
           SequentialDeclaration                                      AssignCommand

                                           AssignCommand SimpleV BinaryExpr :int                          Example 2:
                                                                      :int
        VarDecl                VarDecl              Char.Expr         VNameExp Int.Expr                    foo not found
                                                          :char                  :int        :int
           SimpleT                SimpleT SimpleV                     SimpleV                                                 SimpleV      ***SCOPE ERROR
                                                  :char                          :int
 Ident      Ident         Ident    Ident     Ident Char.Lit Ident       Ident Op Int.Lit                                       Ident       (undeclared variable foo)

    n Integer               c Char            c       ‘&’         n          n          + 1                                    foo
Compilation (Chapter 3)                                                                              9   Compilation (Chapter 3)                                                 10




                               3) Code Generation                                                                                      3) Code Generation

                          Decorated Abstract Syntax Tree                                                  let var n: integer;                     PUSH 2
                                                                                                              var c: char                         LOADL 38
            Code Generation                                                                               in begin                                STORE 1[SB]
                                                                                                             c := ‘&’;                            LOAD 0[SB]
              Object Code                                                                                    n := n+1                             LOADL 1
                                                                                                          end                                     CALL add
                                                                                                                                                  STORE 0[SB]
 • Assumes that program has been thoroughly                                                                                                       POP 2
                                                                                                               VarDecl address = 0[SB]            HALT
   checked and is well formed (scope & type rules)
                                                                                                                    SimpleT
 • Takes into account semantics of the source
                                                                                                          Ident     Ident
   language as well as the target language.
 • Transforms source program into target code.                                                               n Integer
Compilation (Chapter 3)                                                                             11   Compilation (Chapter 3)                                                 12




                                                                                                                                                                                      2
Compiler Passes                                                                 Single Pass Compiler
  • A “pass” is a complete traversal of the source program,                         A single pass compiler makes a single pass over the source text,
    or a complete traversal of some internal representation                         parsing, analyzing, and generating code all at once.
    of the source program (such as an AST).
  • A pass can correspond to a “phase” but it does not have
                                                                                   Dependency diagram of a typical Single Pass Compiler:
    to!
                                                                                                                Compiler Driver
  • Sometimes a single pass corresponds to several phases
    that are interleaved in time.                                                                                       calls
  • What and how many passes a compiler does over the
                                                                                                               Syntactic Analyzer
    source program is an important design decision.
                                                                                                               calls                calls

                                                                                                  Contextual Analyzer     Code Generator

Compilation (Chapter 3)                                                       13   Compilation (Chapter 3)                                             14




                           Multi Pass Compiler                                                Example: Single Pass Compilation of ...

 A multi pass compiler makes several passes over the program. The                    let var n: integer;
 output of a preceding phase is stored in a data structure and used by                   var c: char
 subsequent phases.                                                                  in begin
                                                                                        c := ‘&’;
Dependency diagram of a typical Multi Pass Compiler:                                                                        PUSH 2
                                                                                        n := n+1
                                                                                                                            LOADL 38
                                Compiler Driver                                      end
                                                                                                                            STORE 1[SB]
                  calls                             calls                                                                   LOAD 0[SB]
                                   calls                                                                                    LOADL 1
  Syntactic Analyzer       Contextual Analyzer   Code Generator                                                             CALL add
                                                                                      Ident      Type        Address        STORE 0[SB]
 input               output input         output input     output                     n          int         0[SB]          POP 2
                                                                                      c          char        1[SB]          HALT
Source Text               AST              Decorated AST          Object Code

Compilation (Chapter 3)                                                       15   Compilation (Chapter 3)                                             16




                          Compiler Design Issues                                                               Language Issues

                                Single Pass           Multi Pass                     Example Pascal:
                                                                                     Pascal was explicitly designed to be easy to implement
 Speed                           better                worse                           with a single pass compiler:
                                                                                         – Every identifier must be declared before its first use.
 Memory                          better for            (potentially) better
                                 large programs        for small programs                                                       ?
 Modularity                      worse                 better                       var n:integer;                       procedure inc;
                                                                                                                         begin
 Flexibility                     worse                 better                       procedure inc;                          n:=n+1
                                                                                    begin
                                                                                                                         end; Undeclared Variable!
 “Global” optimization            impossible           possible                        n:=n+1
                                                                                    end                                  var n:integer;
 Source Language                  single pass compilers are not possible
                                  for many programming languages
Compilation (Chapter 3)                                                       17   Compilation (Chapter 3)                                             18




                                                                                                                                                            3
Language Issues                                                           Language Issues
  Example Pascal:                                                           Example Pascal:
       – Every identifier must be declared before it is used.                   – Every identifier must be declared before it is used.
       – How to handle mutual recursion then?                                   – How to handle mutual recursion then?

   procedure ping(x:integer)                                                 forward procedure pong(x:integer)
   begin
                                                                             procedure ping(x:integer)
      ... pong(x-1); ...
                                                                             begin
   end;
                                                                                ... pong(x-1); ...
   procedure pong(x:integer)                                                 end;
                                                                                                 OK!
   begin
                                                                             procedure pong(x:integer)
      ... ping(x–1); ...
                                                                             begin
   end;
                                                                                ... ping(x–1); ...
                                                                             end;
Compilation (Chapter 3)                                              19   Compilation (Chapter 3)                                        20




           Example: The Triangle Compiler Driver
  public class Compiler {
  public class Compiler {
    public static void compileProgram(...) {
    public static void compileProgram(...) {
        Parser parser = new Parser(...);
        Parser parser = new Parser(...);
        Checker checker = new Checker(...);
        Checker checker = new Checker(...);
        Encoder generator = new Encoder(...);
        Encoder generator = new Encoder(...);

           Program theAST = parser.parse( );
           Program theAST = parser.parse( );        // first pass
                                                     // first pass
           checker.check(theAST );
           checker.check(theAST );         // second pass
                                            // second pass
           generator.encode(theAST );
           generator.encode(theAST );      // third pass
                                            // third pass
      }
      }
      public static void main(String[ ]] args )) {
      public static void main(String[ args {
         ... compileProgram(...); ...
          ... compileProgram(...); ...
      }
      }
  }
  }

Compilation (Chapter 3)                                              21




                                                                                                                                              4

Weitere ähnliche Inhalte

Was ist angesagt?

Spr ch-05-compilers
Spr ch-05-compilersSpr ch-05-compilers
Spr ch-05-compilers
Vasim Pathan
 
Chapter 1 1
Chapter 1 1Chapter 1 1
Chapter 1 1
bolovv
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
Mir Majid
 

Was ist angesagt? (20)

Unit 1 cd
Unit 1 cdUnit 1 cd
Unit 1 cd
 
Compiler unit 1
Compiler unit 1Compiler unit 1
Compiler unit 1
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler Construction
 
Spr ch-05-compilers
Spr ch-05-compilersSpr ch-05-compilers
Spr ch-05-compilers
 
Compiler Design Material
Compiler Design MaterialCompiler Design Material
Compiler Design Material
 
Lecture2 general structure of a compiler
Lecture2 general structure of a compilerLecture2 general structure of a compiler
Lecture2 general structure of a compiler
 
Chapter 1 1
Chapter 1 1Chapter 1 1
Chapter 1 1
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Compiler Design Introduction
Compiler Design IntroductionCompiler Design Introduction
Compiler Design Introduction
 
Compiler
CompilerCompiler
Compiler
 
what is compiler and five phases of compiler
what is compiler and five phases of compilerwhat is compiler and five phases of compiler
what is compiler and five phases of compiler
 
Compiler designs presentation final
Compiler designs presentation  finalCompiler designs presentation  final
Compiler designs presentation final
 
Compiler Chapter 1
Compiler Chapter 1Compiler Chapter 1
Compiler Chapter 1
 
Phases of compiler
Phases of compilerPhases of compiler
Phases of compiler
 
Lecture 01 introduction to compiler
Lecture 01 introduction to compilerLecture 01 introduction to compiler
Lecture 01 introduction to compiler
 
Lecture1 introduction compilers
Lecture1 introduction compilersLecture1 introduction compilers
Lecture1 introduction compilers
 
Compiler Design Lecture Notes
Compiler Design Lecture NotesCompiler Design Lecture Notes
Compiler Design Lecture Notes
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler Construction
 
phases of a compiler
 phases of a compiler phases of a compiler
phases of a compiler
 
Techniques & applications of Compiler
Techniques & applications of CompilerTechniques & applications of Compiler
Techniques & applications of Compiler
 

Andere mochten auch

Introduction to compiler
Introduction to compilerIntroduction to compiler
Introduction to compiler
Abha Damani
 
System Programming Unit III
System Programming Unit IIISystem Programming Unit III
System Programming Unit III
Manoj Patil
 
System Programming Unit II
System Programming Unit IISystem Programming Unit II
System Programming Unit II
Manoj Patil
 
The analysis synthesis model of compilation
The analysis synthesis model of compilationThe analysis synthesis model of compilation
The analysis synthesis model of compilation
Huawei Technologies
 

Andere mochten auch (20)

Phases of Compiler
Phases of CompilerPhases of Compiler
Phases of Compiler
 
Phases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingPhases of the Compiler - Systems Programming
Phases of the Compiler - Systems Programming
 
Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 
Compilers
CompilersCompilers
Compilers
 
What is Compiler?
What is Compiler?What is Compiler?
What is Compiler?
 
Interpreter
InterpreterInterpreter
Interpreter
 
Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 
phases of compiler-analysis phase
phases of compiler-analysis phasephases of compiler-analysis phase
phases of compiler-analysis phase
 
Classification of Compilers
Classification of CompilersClassification of Compilers
Classification of Compilers
 
Compiler vs interpreter
Compiler vs interpreterCompiler vs interpreter
Compiler vs interpreter
 
Introduction to compiler
Introduction to compilerIntroduction to compiler
Introduction to compiler
 
System Programming Unit III
System Programming Unit IIISystem Programming Unit III
System Programming Unit III
 
Compiler vs Interpreter-Compiler design ppt.
Compiler vs Interpreter-Compiler design ppt.Compiler vs Interpreter-Compiler design ppt.
Compiler vs Interpreter-Compiler design ppt.
 
System Programming Unit II
System Programming Unit IISystem Programming Unit II
System Programming Unit II
 
The analysis synthesis model of compilation
The analysis synthesis model of compilationThe analysis synthesis model of compilation
The analysis synthesis model of compilation
 
Slideshare ppt
Slideshare pptSlideshare ppt
Slideshare ppt
 
1 Unix basics. Part 1
1 Unix basics. Part 11 Unix basics. Part 1
1 Unix basics. Part 1
 
compiladores
compiladorescompiladores
compiladores
 
Phases of a Compiler
Phases of a CompilerPhases of a Compiler
Phases of a Compiler
 
Parallel language &amp; compilers
Parallel language &amp; compilersParallel language &amp; compilers
Parallel language &amp; compilers
 

Ähnlich wie Different phases of a compiler

In-depth look at the Flex compiler and HFCD
In-depth look at the Flex compiler and HFCDIn-depth look at the Flex compiler and HFCD
In-depth look at the Flex compiler and HFCD
Stop Coding
 
Supercharging Cassandra - GOTO Amsterdam
Supercharging Cassandra - GOTO AmsterdamSupercharging Cassandra - GOTO Amsterdam
Supercharging Cassandra - GOTO Amsterdam
Acunu
 
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
venkatapranaykumarGa
 

Ähnlich wie Different phases of a compiler (20)

Unit1 cd
Unit1 cdUnit1 cd
Unit1 cd
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
 
Inside Python
Inside PythonInside Python
Inside Python
 
Inside Python [OSCON 2012]
Inside Python [OSCON 2012]Inside Python [OSCON 2012]
Inside Python [OSCON 2012]
 
In-depth look at the Flex compiler and HFCD
In-depth look at the Flex compiler and HFCDIn-depth look at the Flex compiler and HFCD
In-depth look at the Flex compiler and HFCD
 
Opal compiler
Opal compilerOpal compiler
Opal compiler
 
Custom Detectors for FindBugs (London Java Community Unconference 2)
Custom Detectors for FindBugs (London Java Community Unconference 2)Custom Detectors for FindBugs (London Java Community Unconference 2)
Custom Detectors for FindBugs (London Java Community Unconference 2)
 
Plc part 2
Plc  part 2Plc  part 2
Plc part 2
 
EventStudio: Sequence Diagram Based System Modeling Tool
EventStudio: Sequence Diagram Based System Modeling ToolEventStudio: Sequence Diagram Based System Modeling Tool
EventStudio: Sequence Diagram Based System Modeling Tool
 
Phases of Compiler
Phases of CompilerPhases of Compiler
Phases of Compiler
 
1 cc
1 cc1 cc
1 cc
 
Generacion de codigo ensamblado
Generacion de codigo ensambladoGeneracion de codigo ensamblado
Generacion de codigo ensamblado
 
LANGUAGE TRANSLATOR
LANGUAGE TRANSLATORLANGUAGE TRANSLATOR
LANGUAGE TRANSLATOR
 
Compiler design
Compiler designCompiler design
Compiler design
 
Supercharging Cassandra - GOTO Amsterdam
Supercharging Cassandra - GOTO AmsterdamSupercharging Cassandra - GOTO Amsterdam
Supercharging Cassandra - GOTO Amsterdam
 
Inside PHP [OSCON 2012]
Inside PHP [OSCON 2012]Inside PHP [OSCON 2012]
Inside PHP [OSCON 2012]
 
1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdf1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdf
 
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
 
Viva
VivaViva
Viva
 
Viva
VivaViva
Viva
 

Kürzlich hochgeladen

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Kürzlich hochgeladen (20)

Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 

Different phases of a compiler

  • 1. Course Overview Chapter 3 Compilation PART I: overview material So far we have treated language processors (including 1 Introduction compilers) as “black boxes” 2 Language processors (tombstone diagrams, bootstrapping) 3 Architecture of a compiler GOAL this lecture: PART II: inside a compiler – A first look "inside the box": how to build compilers. 4 Syntax analysis – Different “phases” and their relationships. 5 Contextual analysis 6 Runtime organization 7 Code generation PART III: conclusion 8 Interpretation 9 Review Compilation (Chapter 3) 1 Compilation (Chapter 3) 2 The Major “Phases” of a Compiler Different Phases of a Compiler The different phases can be seen as different Source Program transformation steps to transform source code into object code. Syntax Analysis Error Reports The different phases correspond roughly to the different Abstract Syntax Tree parts of the language specification: Contextual Analysis Error Reports • Syntax analysis <-> Syntax • Contextual analysis <-> Contextual constraints Decorated Abstract Syntax Tree • Code generation <-> Semantics Code Generation Object Code Compilation (Chapter 3) 3 Compilation (Chapter 3) 4 Example Program 1) Syntax Analysis We now look at each of the three different phases in a little more detail. We look at each of the steps in transforming Source Program an example Triangle program into TAM code. Syntax Analysis Error Reports ! This program is useless except for ! This program is useless except for ! illustration ! illustration let var n: integer; let var n: integer; Abstract Syntax Tree Note: Not all compilers construct an Note: Not all compilers construct an var c: char var c: char explicit representation of an AST. (e.g. on explicit representation of an AST. (e.g. on in begin in begin a “single pass compiler” generally no need a “single pass compiler” generally no need c := ‘&’; c := ‘&’; to construct an AST) to construct an AST) n := n+1 n := n+1 end end Compilation (Chapter 3) 5 Compilation (Chapter 3) 6 1
  • 2. 1) Syntax Analysis --> AST 2) Contextual Analysis --> Decorated AST Program Abstract Syntax Tree LetCommand Contextual Analysis Error Reports SequentialCommand Decorated Abstract Syntax Tree SequentialDeclaration AssignCommand Contextual analysis: AssignCommand BinaryExpr • Scope checking: verify that all applied occurrences of identifiers are declared VarDecl VarDecl Char.Expr VNameExp Int.Expr • Type checking: verify that all operations in the program are used according to their type rules. SimpleT SimpleT SimpleV SimpleV Annotate AST: Ident Ident Ident Ident Ident Char.Lit Ident Ident Op Int.Lit • Applied identifier occurrences => declaration • Expressions => Type n Integer c Char c ‘&’ n n + 1 Compilation (Chapter 3) 7 Compilation (Chapter 3) 8 2) Contextual Analysis --> Decorated AST Contextual Analysis Program Finds scope and type errors. LetCommand Example 1: AssignCommand ***TYPE ERROR SequentialCommand (incompatible types in AssignCommand) :char :int SequentialDeclaration AssignCommand AssignCommand SimpleV BinaryExpr :int Example 2: :int VarDecl VarDecl Char.Expr VNameExp Int.Expr foo not found :char :int :int SimpleT SimpleT SimpleV SimpleV SimpleV ***SCOPE ERROR :char :int Ident Ident Ident Ident Ident Char.Lit Ident Ident Op Int.Lit Ident (undeclared variable foo) n Integer c Char c ‘&’ n n + 1 foo Compilation (Chapter 3) 9 Compilation (Chapter 3) 10 3) Code Generation 3) Code Generation Decorated Abstract Syntax Tree let var n: integer; PUSH 2 var c: char LOADL 38 Code Generation in begin STORE 1[SB] c := ‘&’; LOAD 0[SB] Object Code n := n+1 LOADL 1 end CALL add STORE 0[SB] • Assumes that program has been thoroughly POP 2 VarDecl address = 0[SB] HALT checked and is well formed (scope & type rules) SimpleT • Takes into account semantics of the source Ident Ident language as well as the target language. • Transforms source program into target code. n Integer Compilation (Chapter 3) 11 Compilation (Chapter 3) 12 2
  • 3. Compiler Passes Single Pass Compiler • A “pass” is a complete traversal of the source program, A single pass compiler makes a single pass over the source text, or a complete traversal of some internal representation parsing, analyzing, and generating code all at once. of the source program (such as an AST). • A pass can correspond to a “phase” but it does not have Dependency diagram of a typical Single Pass Compiler: to! Compiler Driver • Sometimes a single pass corresponds to several phases that are interleaved in time. calls • What and how many passes a compiler does over the Syntactic Analyzer source program is an important design decision. calls calls Contextual Analyzer Code Generator Compilation (Chapter 3) 13 Compilation (Chapter 3) 14 Multi Pass Compiler Example: Single Pass Compilation of ... A multi pass compiler makes several passes over the program. The let var n: integer; output of a preceding phase is stored in a data structure and used by var c: char subsequent phases. in begin c := ‘&’; Dependency diagram of a typical Multi Pass Compiler: PUSH 2 n := n+1 LOADL 38 Compiler Driver end STORE 1[SB] calls calls LOAD 0[SB] calls LOADL 1 Syntactic Analyzer Contextual Analyzer Code Generator CALL add Ident Type Address STORE 0[SB] input output input output input output n int 0[SB] POP 2 c char 1[SB] HALT Source Text AST Decorated AST Object Code Compilation (Chapter 3) 15 Compilation (Chapter 3) 16 Compiler Design Issues Language Issues Single Pass Multi Pass Example Pascal: Pascal was explicitly designed to be easy to implement Speed better worse with a single pass compiler: – Every identifier must be declared before its first use. Memory better for (potentially) better large programs for small programs ? Modularity worse better var n:integer; procedure inc; begin Flexibility worse better procedure inc; n:=n+1 begin end; Undeclared Variable! “Global” optimization impossible possible n:=n+1 end var n:integer; Source Language single pass compilers are not possible for many programming languages Compilation (Chapter 3) 17 Compilation (Chapter 3) 18 3
  • 4. Language Issues Language Issues Example Pascal: Example Pascal: – Every identifier must be declared before it is used. – Every identifier must be declared before it is used. – How to handle mutual recursion then? – How to handle mutual recursion then? procedure ping(x:integer) forward procedure pong(x:integer) begin procedure ping(x:integer) ... pong(x-1); ... begin end; ... pong(x-1); ... procedure pong(x:integer) end; OK! begin procedure pong(x:integer) ... ping(x–1); ... begin end; ... ping(x–1); ... end; Compilation (Chapter 3) 19 Compilation (Chapter 3) 20 Example: The Triangle Compiler Driver public class Compiler { public class Compiler { public static void compileProgram(...) { public static void compileProgram(...) { Parser parser = new Parser(...); Parser parser = new Parser(...); Checker checker = new Checker(...); Checker checker = new Checker(...); Encoder generator = new Encoder(...); Encoder generator = new Encoder(...); Program theAST = parser.parse( ); Program theAST = parser.parse( ); // first pass // first pass checker.check(theAST ); checker.check(theAST ); // second pass // second pass generator.encode(theAST ); generator.encode(theAST ); // third pass // third pass } } public static void main(String[ ]] args )) { public static void main(String[ args { ... compileProgram(...); ... ... compileProgram(...); ... } } } } Compilation (Chapter 3) 21 4