1. Home
  2. Explore
  3. Computer Science
  4. Compiler Construction Introduction

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Compiler Construction Introduction

Compiler Construction: Introductory Study Notes

1. What Is a Compiler?

A compiler is a system that translates a program written in a high-level programming language into a lower-level representation, eventually producing machine-level code that a computer can execute.

A compiler transforms human-readable source code into machine-oriented code while analyzing, improving, and organizing the program.

The translation process is not usually a single direct conversion. A typical compiler performs several stages:

  1. It reads and analyzes the source program.

  2. It divides the source into meaningful units.

  3. It checks whether the program follows the rules of the language.

  4. It builds one or more intermediate representations.

  5. It checks whether the program has a valid meaning.

  6. It improves the representation through transformations.

  7. It generates assembly or machine code.

  8. It organizes instructions, registers, and memory references.


2. Source Code and Machine Code

Source Code

Source code is a program written in a programming language intended for human programmers. Examples include languages such as Java, C, and similar high-level languages.

Source code is designed to:

  • Be readable and understandable by humans.

  • Express complex operations concisely.

  • Hide many machine-level implementation details.

  • Allow programmers to focus on solving a problem rather than controlling hardware directly.

  • Increase programmer productivity.

For example, a programmer might write:

z = x + y

This single statement expresses the addition of two values and the assignment of the result to z.

Machine Code

Machine code is a low-level representation consisting of instructions that a particular processor can execute directly. Machine code operates close to the hardware and generally refers to:

  • Processor registers.

  • Memory addresses.

  • Load and store operations.

  • Arithmetic and logical instructions.

  • Control-flow instructions.

Machine-level instructions are more difficult for humans to read because they expose details that high-level languages hide.

High-Level and Low-Level Languages

High-Level Languages

High-level languages are relatively close to human reasoning. They allow several machine operations to be expressed using one statement or expression.

For example:

z = x + y

may require several machine-level operations:

  • Retrieve x from memory.

  • Retrieve y from memory.

  • Add the two values.

  • Store the result in z.

Low-Level Languages

Low-level languages are closer to the computer’s hardware. They explicitly describe the operations needed by the processor.

The central difference is that high-level languages are designed for human understanding, while low-level languages are designed for direct execution or close interaction with the machine.


3. Translating a Simple Assignment

Consider the high-level statement:

z = x + y

Assume that x, y, and z are program variables stored in memory. A typical processor cannot usually add two memory locations directly. The values must first be loaded into registers.

A possible sequence is:

  1. Load x from memory into register R1.

  2. Load y from memory into register R2.

  3. Add the values in R1 and R2, placing the result in R3.

  4. Store the value in R3 back into memory location z.

Conceptually:

LOAD x, R1
LOAD y, R2
ADD R1, R2, R3
STORE R3, z

The exact instruction format depends on the processor architecture, but the basic process remains similar.

Variable Names and Memory Addresses

The names x, y, and z are useful to programmers but are not normally used literally by machine instructions.

At the machine or assembly level, a variable name is replaced by a location such as:

  • A memory address.

  • An offset from a base address.

  • An offset from the current function’s activation record.

Local Variables and Activation Records

Local variables are commonly stored in a function’s activation record, also called a stack frame.

An activation record contains information associated with one invocation of a function, such as:

  • Local variables.

  • Parameters.

  • Temporary values.

  • Saved registers.

  • Return information.

Instead of representing a local variable using its source-level name, assembly code may refer to it using an offset from the activation record pointer. The compiler determines these offsets during translation.

For example, a local variable could conceptually be represented as:

offset from activation-record pointer

Thus, the compiler must translate not only the operation x + y, but also the source-level references to x, y, and z into concrete storage locations.


4. The Compiler as More Than a Translator

A compiler does not merely translate source code into machine instructions. It also analyzes the program, builds internal representations, detects errors, improves the code, and produces executable output.

Its major responsibilities include:

  • Scanning: Dividing source text into tokens.

  • Parsing: Determining the grammatical structure of the tokens.

  • Semantic analysis: Checking whether the program has a valid meaning.

  • Intermediate representation: Constructing structured internal forms of the program.

  • Optimization: Applying transformations that improve efficiency.

  • Code generation: Producing assembly or machine-level instructions.

  • Instruction selection: Choosing suitable machine instructions.

  • Register allocation: Deciding which values should reside in registers.

  • Instruction scheduling: Choosing an effective instruction order.


5. Object Files, Linking, and Executables

A program may consist of multiple source files. Each source file can be compiled separately into an object file.

An object file generally contains machine-level or assembly-level code, but it may not yet be a complete executable program.

Linking

Linking combines object files and required library code into an executable program.

A linker performs tasks such as:

  • Combining code from multiple object files.

  • Connecting calls to functions defined in other files.

  • Connecting the program to library functions.

  • Resolving external references.

  • Assigning appropriate locations to code and data.

  • Producing an executable program that can be loaded and run.

For example, a program may call a function whose implementation is located in another source file or in a standard library. The compiler can produce a reference to that function, while the linker later connects the reference to the correct implementation.

Linking resolves relationships between separately compiled pieces of a program and combines them into an executable unit.

Even a program that does not explicitly call user-defined library functions may still depend on system or language libraries.

Compilation Versus Linking

  • Compilation translates an individual source file into an object file.

  • Linking combines object files and libraries into a complete executable.

An object file may contain unresolved references, so it is not necessarily executable by itself.


6. Compiler Optimizations

A compiler may apply optimizations, also called code improvements or enhancements. These are transformations intended to make generated code more efficient.

Possible goals include:

  • Reducing execution time.

  • Reducing memory use.

  • Eliminating redundant calculations.

  • Reducing the number of instructions.

  • Improving the use of registers.

  • Removing unnecessary operations.

The term optimization can be misleading because most compilers do not generate the mathematically optimal code for every program. Instead, compilers generally apply effective transformations that produce good code within practical limits.

Compiler optimization usually means improving code quality, not guaranteeing the absolute best possible code.

Optimization is important, but introductory compiler construction generally emphasizes the basic translation process first. A compiler must correctly understand and translate a program before it can attempt to improve the generated code.


7. Intermediate Representations

A compiler normally does not translate directly from a high-level language into final machine code in one step. Instead, it uses one or more intermediate representations, or IRs.

An intermediate representation is an internal form of a program that lies between the original source code and the final target code.

Intermediate representations make it easier to:

  • Analyze the program.

  • Detect errors.

  • Apply optimizations.

  • Separate language-specific processing from machine-specific processing.

  • Support multiple target machines.

  • Reuse compiler components.

A typical flow is:

High-level source code
        ↓
Intermediate representation
        ↓
Optimized intermediate representation
        ↓
Assembly or machine code

A compiler may use several different intermediate representations rather than only one.


8. Abstract Syntax Trees

An abstract syntax tree, or AST, is a hierarchical tree representation of a program’s structure.

The AST records the essential relationships between operations and operands while omitting unnecessary surface details such as punctuation and formatting.

Consider an expression of the general form:

x = a * b + c * d

The structure can be represented as:

  1. Multiply a and b.

  2. Multiply c and d.

  3. Add the two multiplication results.

  4. Assign the final result to x.

A conceptual tree has:

  • An assignment at the top.

  • x as the destination.

  • Addition as the right-hand-side operation.

  • Two multiplication operations below the addition.

  • Variables a, b, c, and d as leaves.

The tree preserves operator precedence. The multiplication operations occur below the addition because multiplication must be performed first.

Abstract Syntax Tree and Intermediate Code

The AST is one possible intermediate representation. It is more structured than the original source text but still more abstract than assembly.

The compiler can apply transformations to the AST or to another intermediate representation derived from it. After analysis and optimization, the compiler generates lower-level instructions.


9. Compiler Front End and Back End

A compiler is often divided into a front end and a back end.

Front End

The front end processes the source language. It is primarily concerned with understanding the program and determining whether it is valid.

Its responsibilities include:

  • Scanning.

  • Parsing.

  • Semantic analysis.

  • Building intermediate representations.

  • Reporting source-level errors.

The front end is generally more dependent on the source programming language than on the target machine.

Back End

The back end transforms an intermediate representation into target-machine code.

Its responsibilities include:

  • Applying or completing optimizations.

  • Selecting target instructions.

  • Allocating registers.

  • Scheduling instructions.

  • Generating assembly or machine code.

The back end is generally more dependent on the target processor architecture than on the source language.

Overall Structure

A simplified compiler organization is:

Source program
      ↓
Front end
  - Scanning
  - Parsing
  - Semantic analysis
      ↓
Intermediate representation
      ↓
Optimization
      ↓
Back end
  - Instruction selection
  - Register allocation
  - Instruction scheduling
      ↓
Assembly or machine code

10. Scanning

Scanning, also called lexical analysis, converts the sequence of characters in a source program into a sequence of tokens.

A token is a meaningful lexical unit, such as:

  • An identifier.

  • A keyword.

  • A number.

  • An operator.

  • A punctuation symbol.

  • A delimiter.

For example:

xy23 = x + y

could be divided into tokens such as:

  1. Identifier: xy23

  2. Assignment operator: =

  3. Identifier: x

  4. Addition operator: +

  5. Identifier: y

The complete identifier xy23 is treated as one token rather than as separate characters.

Main Purpose of Scanning

Scanning answers the question:

How should the raw character sequence be divided into meaningful words or symbols?

Scanning does not usually determine the full grammatical structure of the program. It prepares the input for the parser.

Scanning and Regular Languages

Scanning is commonly described using:

  • Regular expressions, which specify patterns for tokens.

  • Finite automata, which recognize those patterns.

For example, a rule for identifiers might describe a letter followed by zero or more letters or digits. A scanner can use such rules to determine whether a character sequence is a valid identifier.


11. Parsing

Parsing takes the tokens produced by scanning and determines how they fit together according to the grammar of the programming language.

Parsing constructs a structural representation such as:

  • A parse tree.

  • An abstract syntax tree.

  • Another syntactic intermediate representation.

Scanning Versus Parsing

The distinction can be summarized as follows:

  • Scanning works at the word level: It forms tokens from characters.

  • Parsing works at the sentence level: It forms program structures from tokens.

For example, scanning identifies:

x
=
a
+
b

Parsing determines that this sequence represents an assignment statement whose right-hand side is an addition expression.

Grammar

A programming-language grammar specifies which sequences of tokens form valid programs.

A grammar can define:

  • Expressions.

  • Statements.

  • Assignments.

  • Conditional statements.

  • Loops.

  • Function declarations.

  • Blocks of statements.

Parsing detects syntactic errors, such as:

  • Missing parentheses.

  • Incorrect operator placement.

  • Missing operands.

  • Invalid statement structure.

  • Unmatched delimiters.

A syntactically valid program is not necessarily meaningful. That distinction is handled by semantic analysis.


12. Semantic Analysis

Semantic analysis checks whether a syntactically valid program makes sense according to the rules of the programming language.

The word semantic refers to meaning. A sentence can be grammatically correct while still being meaningless. Programming languages have a similar distinction.

Syntax and Semantics

  • Syntax concerns form and structure.

  • Semantics concerns meaning and validity.

For example, an expression may have a valid grammatical structure but attempt to perform an invalid operation.

Type Checking

A major part of semantic analysis is type checking.

A type error may occur when a program tries to:

  • Add incompatible types.

  • Assign an object to an integer variable.

  • Use a value in a context where its type is not allowed.

  • Pass an argument of the wrong type to a function.

  • Return a value inconsistent with a function’s return type.

For example, a statement that attempts to add two incompatible objects and assign the result to an integer may be syntactically correct but semantically invalid.

Other Semantic Checks

Semantic analysis may also check:

  • Whether a variable has been declared.

  • Whether a variable is used within its valid scope.

  • Whether a function is called with the correct number of arguments.

  • Whether a break statement appears inside a loop.

  • Whether an assignment has a valid destination.

  • Whether control-flow constructs are used appropriately.

A program can be syntactically correct but semantically incorrect.


13. The Back End: Generating Machine Code

After the front end creates and validates an intermediate representation, the back end converts it into target-specific instructions.

For an expression such as:

x = a * b + c * d

the back end may perform operations conceptually like:

  1. Load a into a register.

  2. Load b into another register.

  3. Multiply the two values.

  4. Store the first product in a temporary register.

  5. Load c.

  6. Load d.

  7. Multiply the second pair.

  8. Store the second product in another temporary register.

  9. Add the two products.

  10. Store the final result in x.

The exact register and instruction choices depend on the target machine.


14. Instruction Selection

Instruction selection determines which target-machine instructions should implement each operation in the intermediate representation.

For example, an addition in the IR could potentially be implemented using:

  • A direct add instruction.

  • An add-immediate instruction if one operand is a constant.

  • A specialized instruction if the target architecture provides one.

  • A sequence of instructions if no single instruction directly represents the operation.

Instruction selection attempts to produce correct and efficient target code.

Factors that may influence the choice include:

  • Available machine instructions.

  • Operand types.

  • Register contents.

  • Memory-access costs.

  • Instruction size.

  • Processor capabilities.


15. Register Allocation

Processors have a limited number of registers, while programs may contain many variables and temporary values.

Register allocation determines which values should be placed in registers and which values must remain in memory.

Registers are valuable because access to them is generally faster than access to memory. However, there are usually fewer registers than active program values.

Register allocation must decide:

  • Which variables should receive registers.

  • Which temporary values should receive registers.

  • When a value can be removed from a register.

  • Which values must be moved to memory.

  • Which values should be reloaded later.

Moving a value from a register to memory is called spilling. A spilled value may later need to be loaded back into a register.

The compiler must balance limited register resources against the cost of memory operations.


16. Instruction Scheduling

Instruction scheduling determines the order in which machine instructions should execute.

A compiler may reorder instructions when doing so preserves program meaning and improves performance.

Scheduling can help:

  • Avoid processor delays.

  • Expose parallelism.

  • Reduce pipeline stalls.

  • Place independent instructions between dependent instructions.

  • Make better use of processor execution units.

For example, if one instruction must wait for a memory operation, the compiler may schedule an unrelated instruction during that waiting period.

Instruction scheduling must respect dependencies. An instruction cannot be moved before another instruction if doing so changes the program’s result.


17. Basic Programming Constructs

A basic compiler can support a small but useful programming language. The essential constructs include expressions, assignments, conditionals, and loops.

Expressions

An expression computes a value.

Examples include:

x + y
a * b
x < y

Expressions may contain:

  • Variables.

  • Constants.

  • Arithmetic operators.

  • Relational operators.

  • Boolean operators.

  • Function calls.

  • Nested subexpressions.

Expressions form the computational building blocks of programs.

Assignments

An assignment stores the value of an expression into a variable.

Example:

x = a + b

The compiler must:

  1. Evaluate the right-hand-side expression.

  2. Determine the destination variable.

  3. Store the computed result in the destination.

Conditionals

A conditional selects between alternative actions based on a condition.

Example:

if (x < y) {
    z = x;
} else {
    z = y;
}

The compiler must translate this into control-flow instructions involving:

  • Evaluation of the condition.

  • A conditional branch.

  • One or more labeled code regions.

  • A possible jump over the alternative branch.

Loops

A loop repeatedly executes a block of code while a condition remains satisfied or until a termination condition occurs.

Examples include:

  • while loops.

  • for loops.

  • do-while loops.

The compiler translates loops into control-flow structures involving:

  • A loop condition.

  • A conditional branch.

  • The loop body.

  • A jump back to the condition.

  • An exit target.

These four constructs are sufficient to express many meaningful algorithms:

  • Expressions perform calculations.

  • Assignments store results.

  • Conditionals make decisions.

  • Loops repeat actions.

Advanced language features such as objects and inheritance require additional compiler mechanisms and are not necessary for understanding the basic translation process.


18. Theoretical Foundations of Compiler Construction

Compiler construction applies ideas from the theory of computation, especially:

  • Regular expressions.

  • Finite automata.

  • Context-free grammars.

  • Pushdown automata.

Regular Expressions

Regular expressions describe patterns in character sequences. They are useful for specifying tokens such as:

  • Identifiers.

  • Integer literals.

  • Keywords.

  • Operators.

  • Whitespace.

  • Comments.

Finite Automata

Finite automata recognize regular patterns. A scanner can use a finite automaton to determine whether a sequence of characters forms a valid token.

Grammars

Grammars describe the hierarchical structure of programming languages. They specify how tokens can be combined into:

  • Expressions.

  • Statements.

  • Blocks.

  • Declarations.

  • Complete programs.

Pushdown Automata

Pushdown automata extend finite automata with a stack. The stack allows them to handle nested structures, such as:

  • Parenthesized expressions.

  • Nested blocks.

  • Nested conditionals.

  • Recursive syntactic patterns.

Parsing techniques are closely related to context-free grammars and pushdown automata.

Applying Theory Rather Than Proving It

Compiler construction uses these theoretical concepts to build real systems. The focus is on applying them to:

  • Recognize valid tokens.

  • Parse valid program structures.

  • Construct syntax trees.

  • Detect invalid input.

  • Generate executable code.

The theory remains important even when a course emphasizes implementation rather than formal proofs. Theoretical ideas often become the foundation for technologies whose practical applications emerge later.


19. A Complete Compiler Pipeline

A simplified complete pipeline can be represented as follows:

  1. Source program

    • Human-readable code written in a high-level language.

  2. Scanning

    • Converts characters into tokens.

  3. Parsing

    • Arranges tokens according to the grammar.

    • Builds a syntax tree or similar structure.

  4. Semantic analysis

    • Checks types, declarations, scopes, and other meaning-related rules.

  5. Intermediate representation

    • Stores the program in a structured internal form.

  6. Optimization

    • Applies transformations to improve efficiency and remove redundancy.

  7. Instruction selection

    • Chooses target-machine instructions.

  8. Register allocation

    • Assigns variables and temporary values to registers or memory.

  9. Instruction scheduling

    • Orders instructions while preserving dependencies.

  10. Assembly generation

    • Produces target-specific assembly or machine code.

  11. Object-file creation

    • Stores the compiled code for an individual source file.

  12. Linking

    • Combines object files and libraries.

  13. Executable program

    • Produces a complete program that can be loaded and executed.


20. Key Distinctions

Source Code Versus Machine Code

  • Source code: Human-readable, high-level, problem-oriented.

  • Machine code: Processor-readable, low-level, hardware-oriented.

Scanning Versus Parsing

  • Scanning: Characters →\rightarrow→ tokens.

  • Parsing: Tokens →\rightarrow→ grammatical structures.

Parsing Versus Semantic Analysis

  • Parsing: Determines whether the structure follows the grammar.

  • Semantic analysis: Determines whether the structurally valid program makes sense.

Compilation Versus Linking

  • Compilation: Source file →\rightarrow→ object file.

  • Linking: Object files and libraries →\rightarrow→ executable.

Front End Versus Back End

  • Front end: Understands and validates the source language.

  • Back end: Converts an intermediate representation into target-machine code.

Optimization Versus Correctness

  • Correctness: Ensures that generated code behaves according to the source program.

  • Optimization: Attempts to improve efficiency without changing behavior.

21. Central Takeaways

A compiler is an intelligent software system that combines formal language theory, program analysis, data structures, and machine-level code generation.

  • High-level languages improve human productivity by hiding machine details.

  • Machine code operates directly on registers, memory, and processor instructions.

  • A compiler uses several stages rather than performing one direct translation.

  • Scanning recognizes tokens, while parsing builds grammatical structure.

  • Semantic analysis checks whether a syntactically valid program has a valid meaning.

  • Abstract syntax trees provide a structured intermediate representation.

  • Optimization improves generated code but does not necessarily produce mathematically optimal code.

  • Instruction selection chooses machine instructions.

  • Register allocation manages the limited number of processor registers.

  • Instruction scheduling arranges instructions to improve execution efficiency.

  • Linking combines separately compiled object files and libraries into an executable.

  • Regular expressions, finite automata, grammars, and pushdown automata provide important theoretical foundations for compiler construction.

  • Expressions, assignments, conditionals, and loops form the essential features of a basic programming language.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent