SlideShare a Scribd company logo
1 of 48
Download to read offline
Lecture 10: Data-Flow Analysis
Jeff Smits
CS4200 Compiler Construction
TU Delft
November 2018
Title Text
2
Source
Code
Editor
Parse
Abstract
Syntax
Tree
Type Check
Check that names are used correctly and that expressions are well-typed
Errors
Earlier Lecture
Title Text
3
Source
Code
Editor
Parse
Abstract
Syntax
Tree
Other Check
Check that variables are initialised, statements are reached, etc.
Errors
This Lecture
Title Text
4
Source
Code
Editor
Parse
Abstract
Syntax
Tree
Optimise
Eliminate common subexpressions, reduce loop strength, etc.
Optimised
Abstract
Syntax
Tree
This Lecture
Reading Material
5
The following papers add background, conceptual exposition,
and examples to the material from the slides. Some notation and
technical details have been changed; check the documentation.
6
This paper introduces FlowSpec, the declarative data-flow
analysis specification language in Spoofax. Although the
design of the language described in this paper is still current,
the syntax used is already dated, i.e. the current FlowSpec
syntax in Spoofax is slightly different.
https://doi.org/10.1145/3136014.3136029
SLE 2017
7
Documentation for FlowSpec
at the metaborg.org website.
http://www.metaborg.org/en/latest/source/langdev/meta/lang/flowspec/index.html
Control-Flow
8
What is Control-Flow?
- “Order of evaluation”
Discuss a series of example programs
- What is the control flow?
- What constructs in the program determine that?
Control-Flow
9
What is Control-Flow?
10
function id(x) { return x; }
id(4); id(true);
- Calling a function passes control to that function

- A return passes control back to the caller
Function calls
What is Control-Flow?
11
if (c) { a = 5 } else { a = "four" }
- Control is passed to one of the two branches

- This is dependent on the value of the condition
Branching
What is Control-Flow?
12
while (c) { a = 5 }
- Control is passed to the loop body depending on the condition

- After the body we start over
Looping
What is Control-Flow?
13
float distance = 12.0;
float velocity = time / distance;
- No conditions or anything complicated

- But still order of execution
Sequence
What is Control-Flow?
14
distance = distance + 1;
- The expression needs to be evaluated, 

before we can save its result
Writes and reads
What is Control-Flow?
15
counter.next() / counter.next()
- Order in sub-expressions is usually undefined

- Side-effects make sub-expression order relevant
Expressions & side-effects
- Sequential	 statements

- Conditional	 if / switch / case

- Looping	 while / do while / for / foreach / loop

- Exceptions	 throw / try / catch / finally

- Continuations	 call/cc

- Async-await	 threading

- Coroutines / Generators	 yield

- Dispatch	 function calls / method calls

- Loop jumps	 break / continue

- ... many more ...	
What kind of Control-Flow?
16
Shorter code
- No need to repeat the same statement 10 times
Parametric code
- Extract reusable patterns
- Let user decide repetition amount
Expressive power
- Playing with the Turing Machines
Reason about program execution
- What happens when?
- In what order?
Why Control-Flow?
17
Imperative programming
- Explicit control-flow constructs
Declarative programming
- What, not how
- Less explicit control-flow

- More options for compilers to choose order
- Great if your compiler is often smarter than the programmer
Control-Flow and language design
18
Representation
- Represent control-flow of a program
- Conduct and represent results of data-flow analysis
Declarative Rules
- To define control-flow of a language
- To define data-flow of a language
Language-Independent Tooling
- Data-Flow Analysis
- Code completion
- Refactoring
- Optimisation
- …
Separation of Concerns in Data-Flow Analysis
19
Control-Flow Graphs
20
What is a Control-Flow Graph?
21
A control flow graph (CFG) in computer science is a representation, using graph notation, of
all paths that might be traversed through a program during its execution.
https://en.wikipedia.org/wiki/Control_flow_graph
let
var x : int := a + b
var y : int := a * b
in
while y > a + b do
(
a := a + 1;
x := a + b
)
end
Control-Flow Graph example
22
Control-Flow Graph example
23
y > a + b
var y : int := a * b
var x : int := a + b
a := a + 1
x := a + b
Basic blocks
24
var x : int := a + b
var y : int := a * b
y > a + b
a := a + 1
x := a + b
Nodes
- Usually innermost statements and expressions
- Or blocks for consecutive statements (basic blocks)

Edges
- Back edges: show loops
- Splits: conditionally split the control flow
- Merges: combine previously split control flow
Control Flow Graphs
25
Equivalent to unstructured control-flow
26
a ← 0
L1: b ← a + 1
c ← c + b
a ← 2 * b
if a < N goto L1
return c
a ← 0
b ← a + 1
c ← c + b
a ← 2 * b
a < N
return c
Representation
- Represent control-flow of a program
- Conduct and represent results of data-flow analysis
Declarative Rules
- To define control-flow of a language
- To define data-flow of a language
Language-Independent Tooling
- Data-Flow Analysis
- Code completion
- Refactoring
- Optimisation
- …
Separation of Concerns in Data-Flow Analysis
27
Representation
-
- Conduct and represent results of data-flow analysis
Declarative Rules
- To define control-flow of a language
- To define data-flow of a language
Language-Independent Tooling
- Data-Flow Analysis
- Code completion
- Refactoring
- Optimisation
- …
Separation of Concerns in Data-Flow Analysis
28
Control Flow Graphs
Data-Flow
29
What is Data-Flow?
- Possible values (data) that flow through the program
- Relations between that data (data dependence)
Discuss a series of example programs
- What is wrong or can be optimised?
- What is the flow we can use for this?
Data-Flow
30
Source
Code
Editor
Parse
Abstract
Syntax
Tree
Other Check
Check that code is reachable or observable
Errors
31
public int ComputeFac(int num) {
return num;
int num_aux;
if (num < 1)
num_aux = 1;
else
num_aux = num * this.ComputeFac(num-1);
return num_aux;
}
What is wrong here?
32
- Most of the code is never reached because of the early return

- This is usually considered an error by compilers
Dead code (control-flow)
x := 2;
y := 4;
x := 1;
// x and y used later
What is “wrong” here?
33
- The first value of x is never observed

- This is sometimes warned about by compilers
Dead code (data-flow)
Live variable analysis
Source
Code
Editor
Parse
Abstract
Syntax
Tree
Optimise
Eliminate common subexpressions, reduce loop strength, etc.
Optimised
Abstract
Syntax
Tree
34
let
var x : int := a + b
var y : int := a * b
in
if y > a + b then
(
a := a + 1;
x := a + b
)
end
What is suboptimal here?
35
- a + b is already computed when you get to the condition

- There is no need to compute it again
Common subexpression elimination
Available expression analysis
What is suboptimal here?
for i := 1 to 100 do
(
x[i] := y[i];
if w > 0 then
y[i] := 0
)
- The if condition is not dependent on i, x or y

- Still it is checked in the loop, which is slowing the loop
Loop unswitching
36
Data-dependence analysis
Tiger in FlowSpec
37
Representation
-
- Conduct and represent results of data-flow analysis
Declarative Rules
- To define control-flow of a language
- To define data-flow of a language
Language-Independent Tooling
- Data-Flow Analysis
- Code completion
- Refactoring
- Optimisation
- …
Separation of Concerns in Data-Flow Analysis
38
Control Flow Graphs
Representation
-
-
Declarative Rules
- To define control-flow of a language
- To define data-flow of a language
Language-Independent Tooling
- Data-Flow Analysis
- Code completion
- Refactoring
- Optimisation
- …
Separation of Concerns in Data-Flow Analysis
39
Control Flow Graphs
Data-flow information on CFG nodes
Representation
-
-
Declarative Rules
- To define control-flow of a language
- To define data-flow of a language
Language-Independent Tooling
- Data-Flow Analysis
- Code completion
- Refactoring
- Optimisation
- …
Separation of Concerns in Data-Flow Analysis
40
Control Flow Graphs
Data-flow information on CFG nodes
A domain-specific meta-language for Spoofax: FlowSpec
Map abstract syntax to control-flow (sub)graphs
- Match an AST pattern
- List all edges of that AST
- Use special “context” nodes to connect a subgraph to the outside graph
Control-Flow rules
x := 1;
if y > x then
z := y;
else
z := y * y;
y := a * b;
while y > a + b do
(a := a + 1;
x := a + b)
Control-flow graphs in FlowSpec
root Mod(s) =
start -> s -> end
start
end
While(c, b) =
entry -> node c -> b -> node c,
node c -> exit
IfThenElse(c, t, e) =
entry -> node c -> t -> exit,
node c -> e -> exit
Seq(s1, s2) =
entry -> s1 -> s2 -> exit
node Assign(_, _)
FlowSpec Example program
Data-Flow rules
Define effect of control-flow nodes
- Match an AST pattern on one side of a CFG edge
- Propagate the information from the other side of the edge
- Adapt that information as the effect of the matched CFG node
{z,x}
{z,x}
{z,x}
{z,x}
{z}
{}
{}
{}
{}
{}
{x}
{z}
{}
{}
x := 2;
y := 4;
x := 1;
z := x;
x := z;
{}
{}
{}
{}
{}
{}
{}
Live Variables in FlowSpec
properties
live: MaySet(name)
live(Assign(n, _) -> next) =
{ m | m <- live(next), n != m }
live(Ref(n) -> next) =
live(next) / {n}
live(_.end) =
{}
A variable is live if the current value
of the variable may be read further
along in the program
end
start
property rules
x := 2;
y := 4;
x := 1;
if y > 0 then
z := x;
else
z := y * y;
x := z;
{x,y}
{x}
{y}
{z}
{}
{}
{z}
{}
{}
{x}
{y}
{z}
{}
{}end
start
Live Variables in FlowSpec
A variable is live if the current value
of the variable may be read further
along in the program
properties
live: MaySet(name)
live(Assign(n, _) -> next) =
{ m | m <- live(next), n != m }
live(Ref(n) -> next) =
live(next) / {n}
live(_.end) =
{}
property rules
Conclusion
46
Control-Flow
- Order of execution
- Reasoning about what is reachable
Data-Flow
- Flow of data through a program
- Reasoning about data, and dependencies between data
FlowSpec
- Control-Flow rules to construct the graph
- Annotate with information from analysis by Data-Flow rules
Summary
47
Except where otherwise noted, this work is licensed under

More Related Content

What's hot

Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc pptpssraikar
 
Intermediate code- generation
Intermediate code- generationIntermediate code- generation
Intermediate code- generationrawan_z
 
Code optimization in compiler design
Code optimization in compiler designCode optimization in compiler design
Code optimization in compiler designKuppusamy P
 
Chapter Eight(1)
Chapter Eight(1)Chapter Eight(1)
Chapter Eight(1)bolovv
 
Intermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignIntermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignKuppusamy P
 
CS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingCS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingEelco Visser
 
Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#Robert Pickering
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basicsLovelitJose
 
Code generation in Compiler Design
Code generation in Compiler DesignCode generation in Compiler Design
Code generation in Compiler DesignKuppusamy P
 
Three address code In Compiler Design
Three address code In Compiler DesignThree address code In Compiler Design
Three address code In Compiler DesignShine Raj
 

What's hot (20)

Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc ppt
 
Compiler unit 4
Compiler unit 4Compiler unit 4
Compiler unit 4
 
Ch4c
Ch4cCh4c
Ch4c
 
Intermediate code- generation
Intermediate code- generationIntermediate code- generation
Intermediate code- generation
 
Code optimization in compiler design
Code optimization in compiler designCode optimization in compiler design
Code optimization in compiler design
 
Introduction to HDLs
Introduction to HDLsIntroduction to HDLs
Introduction to HDLs
 
Chapter Eight(1)
Chapter Eight(1)Chapter Eight(1)
Chapter Eight(1)
 
Intermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignIntermediate code generation in Compiler Design
Intermediate code generation in Compiler Design
 
Code optimization
Code optimizationCode optimization
Code optimization
 
Code Generation
Code GenerationCode Generation
Code Generation
 
CS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | ParsingCS4200 2019 | Lecture 3 | Parsing
CS4200 2019 | Lecture 3 | Parsing
 
Compiler unit 2&3
Compiler unit 2&3Compiler unit 2&3
Compiler unit 2&3
 
Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#Combinators, DSLs, HTML and F#
Combinators, DSLs, HTML and F#
 
Code generation
Code generationCode generation
Code generation
 
C language
C languageC language
C language
 
Interm codegen
Interm codegenInterm codegen
Interm codegen
 
Compiler unit 5
Compiler  unit 5Compiler  unit 5
Compiler unit 5
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
Code generation in Compiler Design
Code generation in Compiler DesignCode generation in Compiler Design
Code generation in Compiler Design
 
Three address code In Compiler Design
Three address code In Compiler DesignThree address code In Compiler Design
Three address code In Compiler Design
 

Similar to Compiler Construction | Lecture 10 | Data-Flow Analysis

7-White Box Testing.ppt
7-White Box Testing.ppt7-White Box Testing.ppt
7-White Box Testing.pptHirenderPal
 
Compiler Construction for DLX Processor
Compiler Construction for DLX Processor Compiler Construction for DLX Processor
Compiler Construction for DLX Processor Soham Kulkarni
 
Reverse Engineering automation
Reverse Engineering automationReverse Engineering automation
Reverse Engineering automationPositive Hack Days
 
Taking Spark Streaming to the Next Level with Datasets and DataFrames
Taking Spark Streaming to the Next Level with Datasets and DataFramesTaking Spark Streaming to the Next Level with Datasets and DataFrames
Taking Spark Streaming to the Next Level with Datasets and DataFramesDatabricks
 
Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das
Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das
Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das Databricks
 
Continuous Application with Structured Streaming 2.0
Continuous Application with Structured Streaming 2.0Continuous Application with Structured Streaming 2.0
Continuous Application with Structured Streaming 2.0Anyscale
 
My Postdoctoral Research
My Postdoctoral ResearchMy Postdoctoral Research
My Postdoctoral ResearchPo-Ting Wu
 
Measuring maintainability; software metrics explained
Measuring maintainability; software metrics explainedMeasuring maintainability; software metrics explained
Measuring maintainability; software metrics explainedDennis de Greef
 
NSC #2 - D2 06 - Richard Johnson - SAGEly Advice
NSC #2 - D2 06 - Richard Johnson - SAGEly AdviceNSC #2 - D2 06 - Richard Johnson - SAGEly Advice
NSC #2 - D2 06 - Richard Johnson - SAGEly AdviceNoSuchCon
 
Lecture1-Algorithms-and-Flowcharts-ppt.ppt
Lecture1-Algorithms-and-Flowcharts-ppt.pptLecture1-Algorithms-and-Flowcharts-ppt.ppt
Lecture1-Algorithms-and-Flowcharts-ppt.pptReshuReshma8
 
Apache Flink Deep Dive
Apache Flink Deep DiveApache Flink Deep Dive
Apache Flink Deep DiveVasia Kalavri
 
A Deep Dive into Structured Streaming: Apache Spark Meetup at Bloomberg 2016
A Deep Dive into Structured Streaming:  Apache Spark Meetup at Bloomberg 2016 A Deep Dive into Structured Streaming:  Apache Spark Meetup at Bloomberg 2016
A Deep Dive into Structured Streaming: Apache Spark Meetup at Bloomberg 2016 Databricks
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapKostas Tzoumas
 
2007 Tidc India Profiling
2007 Tidc India Profiling2007 Tidc India Profiling
2007 Tidc India Profilingdanrinkes
 
cs241-f06-final-overview
cs241-f06-final-overviewcs241-f06-final-overview
cs241-f06-final-overviewColin Bell
 
AlgorithmAndFlowChart.pdf
AlgorithmAndFlowChart.pdfAlgorithmAndFlowChart.pdf
AlgorithmAndFlowChart.pdfSusieMaestre1
 
Basic Slides on Algorithms and Flowcharts
Basic Slides on Algorithms and FlowchartsBasic Slides on Algorithms and Flowcharts
Basic Slides on Algorithms and Flowchartsmoazwinner
 
advanced computer architesture-conditions of parallelism
advanced computer architesture-conditions of parallelismadvanced computer architesture-conditions of parallelism
advanced computer architesture-conditions of parallelismPankaj Kumar Jain
 

Similar to Compiler Construction | Lecture 10 | Data-Flow Analysis (20)

7-White Box Testing.ppt
7-White Box Testing.ppt7-White Box Testing.ppt
7-White Box Testing.ppt
 
Compiler Construction for DLX Processor
Compiler Construction for DLX Processor Compiler Construction for DLX Processor
Compiler Construction for DLX Processor
 
Reverse Engineering automation
Reverse Engineering automationReverse Engineering automation
Reverse Engineering automation
 
Taking Spark Streaming to the Next Level with Datasets and DataFrames
Taking Spark Streaming to the Next Level with Datasets and DataFramesTaking Spark Streaming to the Next Level with Datasets and DataFrames
Taking Spark Streaming to the Next Level with Datasets and DataFrames
 
Flink internals web
Flink internals web Flink internals web
Flink internals web
 
Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das
Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das
Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das
 
Continuous Application with Structured Streaming 2.0
Continuous Application with Structured Streaming 2.0Continuous Application with Structured Streaming 2.0
Continuous Application with Structured Streaming 2.0
 
My Postdoctoral Research
My Postdoctoral ResearchMy Postdoctoral Research
My Postdoctoral Research
 
Measuring maintainability; software metrics explained
Measuring maintainability; software metrics explainedMeasuring maintainability; software metrics explained
Measuring maintainability; software metrics explained
 
SWEET - A Tool for WCET Flow Analysis - Björn Lisper
SWEET - A Tool for WCET Flow Analysis - Björn LisperSWEET - A Tool for WCET Flow Analysis - Björn Lisper
SWEET - A Tool for WCET Flow Analysis - Björn Lisper
 
NSC #2 - D2 06 - Richard Johnson - SAGEly Advice
NSC #2 - D2 06 - Richard Johnson - SAGEly AdviceNSC #2 - D2 06 - Richard Johnson - SAGEly Advice
NSC #2 - D2 06 - Richard Johnson - SAGEly Advice
 
Lecture1-Algorithms-and-Flowcharts-ppt.ppt
Lecture1-Algorithms-and-Flowcharts-ppt.pptLecture1-Algorithms-and-Flowcharts-ppt.ppt
Lecture1-Algorithms-and-Flowcharts-ppt.ppt
 
Apache Flink Deep Dive
Apache Flink Deep DiveApache Flink Deep Dive
Apache Flink Deep Dive
 
A Deep Dive into Structured Streaming: Apache Spark Meetup at Bloomberg 2016
A Deep Dive into Structured Streaming:  Apache Spark Meetup at Bloomberg 2016 A Deep Dive into Structured Streaming:  Apache Spark Meetup at Bloomberg 2016
A Deep Dive into Structured Streaming: Apache Spark Meetup at Bloomberg 2016
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmap
 
2007 Tidc India Profiling
2007 Tidc India Profiling2007 Tidc India Profiling
2007 Tidc India Profiling
 
cs241-f06-final-overview
cs241-f06-final-overviewcs241-f06-final-overview
cs241-f06-final-overview
 
AlgorithmAndFlowChart.pdf
AlgorithmAndFlowChart.pdfAlgorithmAndFlowChart.pdf
AlgorithmAndFlowChart.pdf
 
Basic Slides on Algorithms and Flowcharts
Basic Slides on Algorithms and FlowchartsBasic Slides on Algorithms and Flowcharts
Basic Slides on Algorithms and Flowcharts
 
advanced computer architesture-conditions of parallelism
advanced computer architesture-conditions of parallelismadvanced computer architesture-conditions of parallelism
advanced computer architesture-conditions of parallelism
 

More from Eelco Visser

CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingEelco Visser
 
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesCS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesEelco Visser
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionEelco Visser
 
CS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: IntroductionCS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: IntroductionEelco Visser
 
A Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation RulesA Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation RulesEelco Visser
 
Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with StatixEelco Visser
 
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionCompiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionEelco Visser
 
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)Eelco Visser
 
Compiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory ManagementCompiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory ManagementEelco Visser
 
Compiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersCompiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersEelco Visser
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionEelco Visser
 
Compiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type ConstraintsCompiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type ConstraintsEelco Visser
 
Compiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingCompiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingEelco Visser
 
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisCompiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisEelco Visser
 
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term RewritingCompiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term RewritingEelco Visser
 
Compiler Construction | Lecture 4 | Parsing
Compiler Construction | Lecture 4 | Parsing Compiler Construction | Lecture 4 | Parsing
Compiler Construction | Lecture 4 | Parsing Eelco Visser
 
Compiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax DefinitionCompiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax DefinitionEelco Visser
 
Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?Eelco Visser
 
Declare Your Language: Virtual Machines & Code Generation
Declare Your Language: Virtual Machines & Code GenerationDeclare Your Language: Virtual Machines & Code Generation
Declare Your Language: Virtual Machines & Code GenerationEelco Visser
 
Declare Your Language: Dynamic Semantics
Declare Your Language: Dynamic SemanticsDeclare Your Language: Dynamic Semantics
Declare Your Language: Dynamic SemanticsEelco Visser
 

More from Eelco Visser (20)

CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
 
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesCS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic Services
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definition
 
CS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: IntroductionCS4200 2019 Lecture 1: Introduction
CS4200 2019 Lecture 1: Introduction
 
A Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation RulesA Direct Semantics of Declarative Disambiguation Rules
A Direct Semantics of Declarative Disambiguation Rules
 
Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with Statix
 
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionCompiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler Construction
 
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)Domain Specific Languages for Parallel Graph AnalytiX (PGX)
Domain Specific Languages for Parallel Graph AnalytiX (PGX)
 
Compiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory ManagementCompiler Construction | Lecture 15 | Memory Management
Compiler Construction | Lecture 15 | Memory Management
 
Compiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | InterpretersCompiler Construction | Lecture 14 | Interpreters
Compiler Construction | Lecture 14 | Interpreters
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint Resolution
 
Compiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type ConstraintsCompiler Construction | Lecture 8 | Type Constraints
Compiler Construction | Lecture 8 | Type Constraints
 
Compiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type CheckingCompiler Construction | Lecture 7 | Type Checking
Compiler Construction | Lecture 7 | Type Checking
 
Compiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static AnalysisCompiler Construction | Lecture 6 | Introduction to Static Analysis
Compiler Construction | Lecture 6 | Introduction to Static Analysis
 
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term RewritingCompiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
 
Compiler Construction | Lecture 4 | Parsing
Compiler Construction | Lecture 4 | Parsing Compiler Construction | Lecture 4 | Parsing
Compiler Construction | Lecture 4 | Parsing
 
Compiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax DefinitionCompiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax Definition
 
Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?
 
Declare Your Language: Virtual Machines & Code Generation
Declare Your Language: Virtual Machines & Code GenerationDeclare Your Language: Virtual Machines & Code Generation
Declare Your Language: Virtual Machines & Code Generation
 
Declare Your Language: Dynamic Semantics
Declare Your Language: Dynamic SemanticsDeclare Your Language: Dynamic Semantics
Declare Your Language: Dynamic Semantics
 

Recently uploaded

Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 

Recently uploaded (20)

Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 

Compiler Construction | Lecture 10 | Data-Flow Analysis

  • 1. Lecture 10: Data-Flow Analysis Jeff Smits CS4200 Compiler Construction TU Delft November 2018
  • 2. Title Text 2 Source Code Editor Parse Abstract Syntax Tree Type Check Check that names are used correctly and that expressions are well-typed Errors Earlier Lecture
  • 3. Title Text 3 Source Code Editor Parse Abstract Syntax Tree Other Check Check that variables are initialised, statements are reached, etc. Errors This Lecture
  • 4. Title Text 4 Source Code Editor Parse Abstract Syntax Tree Optimise Eliminate common subexpressions, reduce loop strength, etc. Optimised Abstract Syntax Tree This Lecture
  • 5. Reading Material 5 The following papers add background, conceptual exposition, and examples to the material from the slides. Some notation and technical details have been changed; check the documentation.
  • 6. 6 This paper introduces FlowSpec, the declarative data-flow analysis specification language in Spoofax. Although the design of the language described in this paper is still current, the syntax used is already dated, i.e. the current FlowSpec syntax in Spoofax is slightly different. https://doi.org/10.1145/3136014.3136029 SLE 2017
  • 7. 7 Documentation for FlowSpec at the metaborg.org website. http://www.metaborg.org/en/latest/source/langdev/meta/lang/flowspec/index.html
  • 9. What is Control-Flow? - “Order of evaluation” Discuss a series of example programs - What is the control flow? - What constructs in the program determine that? Control-Flow 9
  • 10. What is Control-Flow? 10 function id(x) { return x; } id(4); id(true); - Calling a function passes control to that function - A return passes control back to the caller Function calls
  • 11. What is Control-Flow? 11 if (c) { a = 5 } else { a = "four" } - Control is passed to one of the two branches - This is dependent on the value of the condition Branching
  • 12. What is Control-Flow? 12 while (c) { a = 5 } - Control is passed to the loop body depending on the condition - After the body we start over Looping
  • 13. What is Control-Flow? 13 float distance = 12.0; float velocity = time / distance; - No conditions or anything complicated - But still order of execution Sequence
  • 14. What is Control-Flow? 14 distance = distance + 1; - The expression needs to be evaluated, 
 before we can save its result Writes and reads
  • 15. What is Control-Flow? 15 counter.next() / counter.next() - Order in sub-expressions is usually undefined - Side-effects make sub-expression order relevant Expressions & side-effects
  • 16. - Sequential statements - Conditional if / switch / case - Looping while / do while / for / foreach / loop - Exceptions throw / try / catch / finally - Continuations call/cc - Async-await threading - Coroutines / Generators yield - Dispatch function calls / method calls - Loop jumps break / continue - ... many more ... What kind of Control-Flow? 16
  • 17. Shorter code - No need to repeat the same statement 10 times Parametric code - Extract reusable patterns - Let user decide repetition amount Expressive power - Playing with the Turing Machines Reason about program execution - What happens when? - In what order? Why Control-Flow? 17
  • 18. Imperative programming - Explicit control-flow constructs Declarative programming - What, not how - Less explicit control-flow
 - More options for compilers to choose order - Great if your compiler is often smarter than the programmer Control-Flow and language design 18
  • 19. Representation - Represent control-flow of a program - Conduct and represent results of data-flow analysis Declarative Rules - To define control-flow of a language - To define data-flow of a language Language-Independent Tooling - Data-Flow Analysis - Code completion - Refactoring - Optimisation - … Separation of Concerns in Data-Flow Analysis 19
  • 21. What is a Control-Flow Graph? 21 A control flow graph (CFG) in computer science is a representation, using graph notation, of all paths that might be traversed through a program during its execution. https://en.wikipedia.org/wiki/Control_flow_graph
  • 22. let var x : int := a + b var y : int := a * b in while y > a + b do ( a := a + 1; x := a + b ) end Control-Flow Graph example 22
  • 23. Control-Flow Graph example 23 y > a + b var y : int := a * b var x : int := a + b a := a + 1 x := a + b
  • 24. Basic blocks 24 var x : int := a + b var y : int := a * b y > a + b a := a + 1 x := a + b
  • 25. Nodes - Usually innermost statements and expressions - Or blocks for consecutive statements (basic blocks) Edges - Back edges: show loops - Splits: conditionally split the control flow - Merges: combine previously split control flow Control Flow Graphs 25
  • 26. Equivalent to unstructured control-flow 26 a ← 0 L1: b ← a + 1 c ← c + b a ← 2 * b if a < N goto L1 return c a ← 0 b ← a + 1 c ← c + b a ← 2 * b a < N return c
  • 27. Representation - Represent control-flow of a program - Conduct and represent results of data-flow analysis Declarative Rules - To define control-flow of a language - To define data-flow of a language Language-Independent Tooling - Data-Flow Analysis - Code completion - Refactoring - Optimisation - … Separation of Concerns in Data-Flow Analysis 27
  • 28. Representation - - Conduct and represent results of data-flow analysis Declarative Rules - To define control-flow of a language - To define data-flow of a language Language-Independent Tooling - Data-Flow Analysis - Code completion - Refactoring - Optimisation - … Separation of Concerns in Data-Flow Analysis 28 Control Flow Graphs
  • 30. What is Data-Flow? - Possible values (data) that flow through the program - Relations between that data (data dependence) Discuss a series of example programs - What is wrong or can be optimised? - What is the flow we can use for this? Data-Flow 30
  • 31. Source Code Editor Parse Abstract Syntax Tree Other Check Check that code is reachable or observable Errors 31
  • 32. public int ComputeFac(int num) { return num; int num_aux; if (num < 1) num_aux = 1; else num_aux = num * this.ComputeFac(num-1); return num_aux; } What is wrong here? 32 - Most of the code is never reached because of the early return - This is usually considered an error by compilers Dead code (control-flow)
  • 33. x := 2; y := 4; x := 1; // x and y used later What is “wrong” here? 33 - The first value of x is never observed - This is sometimes warned about by compilers Dead code (data-flow) Live variable analysis
  • 34. Source Code Editor Parse Abstract Syntax Tree Optimise Eliminate common subexpressions, reduce loop strength, etc. Optimised Abstract Syntax Tree 34
  • 35. let var x : int := a + b var y : int := a * b in if y > a + b then ( a := a + 1; x := a + b ) end What is suboptimal here? 35 - a + b is already computed when you get to the condition - There is no need to compute it again Common subexpression elimination Available expression analysis
  • 36. What is suboptimal here? for i := 1 to 100 do ( x[i] := y[i]; if w > 0 then y[i] := 0 ) - The if condition is not dependent on i, x or y - Still it is checked in the loop, which is slowing the loop Loop unswitching 36 Data-dependence analysis
  • 38. Representation - - Conduct and represent results of data-flow analysis Declarative Rules - To define control-flow of a language - To define data-flow of a language Language-Independent Tooling - Data-Flow Analysis - Code completion - Refactoring - Optimisation - … Separation of Concerns in Data-Flow Analysis 38 Control Flow Graphs
  • 39. Representation - - Declarative Rules - To define control-flow of a language - To define data-flow of a language Language-Independent Tooling - Data-Flow Analysis - Code completion - Refactoring - Optimisation - … Separation of Concerns in Data-Flow Analysis 39 Control Flow Graphs Data-flow information on CFG nodes
  • 40. Representation - - Declarative Rules - To define control-flow of a language - To define data-flow of a language Language-Independent Tooling - Data-Flow Analysis - Code completion - Refactoring - Optimisation - … Separation of Concerns in Data-Flow Analysis 40 Control Flow Graphs Data-flow information on CFG nodes A domain-specific meta-language for Spoofax: FlowSpec
  • 41. Map abstract syntax to control-flow (sub)graphs - Match an AST pattern - List all edges of that AST - Use special “context” nodes to connect a subgraph to the outside graph Control-Flow rules
  • 42. x := 1; if y > x then z := y; else z := y * y; y := a * b; while y > a + b do (a := a + 1; x := a + b) Control-flow graphs in FlowSpec root Mod(s) = start -> s -> end start end While(c, b) = entry -> node c -> b -> node c, node c -> exit IfThenElse(c, t, e) = entry -> node c -> t -> exit, node c -> e -> exit Seq(s1, s2) = entry -> s1 -> s2 -> exit node Assign(_, _) FlowSpec Example program
  • 43. Data-Flow rules Define effect of control-flow nodes - Match an AST pattern on one side of a CFG edge - Propagate the information from the other side of the edge - Adapt that information as the effect of the matched CFG node
  • 44. {z,x} {z,x} {z,x} {z,x} {z} {} {} {} {} {} {x} {z} {} {} x := 2; y := 4; x := 1; z := x; x := z; {} {} {} {} {} {} {} Live Variables in FlowSpec properties live: MaySet(name) live(Assign(n, _) -> next) = { m | m <- live(next), n != m } live(Ref(n) -> next) = live(next) / {n} live(_.end) = {} A variable is live if the current value of the variable may be read further along in the program end start property rules
  • 45. x := 2; y := 4; x := 1; if y > 0 then z := x; else z := y * y; x := z; {x,y} {x} {y} {z} {} {} {z} {} {} {x} {y} {z} {} {}end start Live Variables in FlowSpec A variable is live if the current value of the variable may be read further along in the program properties live: MaySet(name) live(Assign(n, _) -> next) = { m | m <- live(next), n != m } live(Ref(n) -> next) = live(next) / {n} live(_.end) = {} property rules
  • 47. Control-Flow - Order of execution - Reasoning about what is reachable Data-Flow - Flow of data through a program - Reasoning about data, and dependencies between data FlowSpec - Control-Flow rules to construct the graph - Annotate with information from analysis by Data-Flow rules Summary 47
  • 48. Except where otherwise noted, this work is licensed under