SlideShare a Scribd company logo
11. Working with Bytecode
© Oscar Nierstrasz
ST — Working with Bytecode
11.2
Roadmap
> The Pharo compiler
> Introduction to Pharo bytecode
> Generating bytecode with IRBuilder
> Parsing and Interpreting bytecode
Original material by Marcus Denker
© Oscar Nierstrasz
ST — Working with Bytecode
11.3
Roadmap
> The Pharo compiler
> Introduction to Pharo bytecode
> Generating bytecode with IRBuilder
> Parsing and Interpreting bytecode
© Oscar Nierstrasz
ST — Working with Bytecode
11.4
The Pharo Compiler
> Default compiler
— very old design
— quite hard to understand
— impossible to modify and extend
> New compiler for Pharo
— http://www.iam.unibe.ch/~scg/Research/NewCompiler/
— adds support for true block closures (optional)
© Oscar Nierstrasz
ST — Working with Bytecode
11.5
The Pharo Compiler
> Fully reified compilation process:
— Scanner/Parser (built with SmaCC)
– builds AST (from Refactoring Browser)
— Semantic Analysis: ASTChecker
– annotates the AST (e.g., var bindings)
— Translation to IR: ASTTranslator
– uses IRBuilder to build IR (Intermediate Representation)
— Bytecode generation: IRTranslator
– uses BytecodeBuilder to emit bytecodes
© Oscar Nierstrasz
ST — Working with Bytecode
11.6
Compiler: Overview
code AST AST
Scanner
/ Parser
Semantic
Analysis
Bytecode
Code
Generation
AST IR
Build
IR
Bytecode
Bytecode
Generation
ASTTranslator
IRBuilder
IRTranslator
BytecodeBuilder
Code generation in detail
© Oscar Nierstrasz
ST — Working with Bytecode
11.7
Compiler: Syntax
> SmaCC: Smalltalk Compiler Compiler
— Similar to Lex/Yacc
— SmaCC can build LARL(1) or LR(1) parser
> Input:
— Scanner definition: regular expressions
— Parser: BNF-like grammar
— Code that builds AST as annotation
> Output:
— class for Scanner (subclass SmaCCScanner)
— class for Parser (subclass SmaCCParser)
© Oscar Nierstrasz
ST — Working with Bytecode
11.8
Scanner
© Oscar Nierstrasz
ST — Working with Bytecode
11.9
Parser
© Oscar Nierstrasz
ST — Working with Bytecode
11.10
Calling Parser code
© Oscar Nierstrasz
ST — Working with Bytecode
11.11
Compiler: AST
> AST: Abstract Syntax Tree
— Encodes the Syntax as a Tree
— No semantics yet!
— Uses the RB Tree:
– Visitors
– Backward pointers in ParseNodes
– Transformation (replace/add/delete)
– Pattern-directed TreeRewriter
– PrettyPrinter
RBProgramNode
RBDoItNode
RBMethodNode
RBReturnNode
RBSequenceNode
RBValueNode
RBArrayNode
RBAssignmentNode
RBBlockNode
RBCascadeNode
RBLiteralNode
RBMessageNode
RBOptimizedNode
RBVariableNode
© Oscar Nierstrasz
ST — Working with Bytecode
11.12
Compiler: Semantics
> We need to analyse the AST
— Names need to be linked to the variables according to the
scoping rules
> ASTChecker implemented as a Visitor
— Subclass of RBProgramNodeVisitor
— Visits the nodes
— Grows and shrinks scope chain
— Methods/Blocks are linked with the scope
— Variable definitions and references are linked with objects
describing the variables
© Oscar Nierstrasz
ST — Working with Bytecode
11.13
A Simple Tree
RBParser parseExpression: '3+4' NB: explore it
© Oscar Nierstrasz
ST — Working with Bytecode
11.14
A Simple Visitor
RBProgramNodeVisitor new visitNode: tree
Does nothing except
walk through the tree
© Oscar Nierstrasz
ST — Working with Bytecode
11.15
TestVisitor
RBProgramNodeVisitor subclass: #TestVisitor
instanceVariableNames: 'literals'
classVariableNames: ''
poolDictionaries: ''
category: 'Compiler-AST-Visitors'
TestVisitor>>acceptLiteralNode: aLiteralNode
literals add: aLiteralNode value.
TestVisitor>>initialize
literals := Set new.
TestVisitor>>literals
^literals
tree := RBParser parseExpression: '3 + 4'.
(TestVisitor new visitNode: tree) literals
a Set(3 4)
© Oscar Nierstrasz
ST — Working with Bytecode
11.16
Compiler: Intermediate Representation
> IR: Intermediate Representation
— Semantic like Bytecode, but more abstract
— Independent of the bytecode set
— IR is a tree
— IR nodes allow easy transformation
— Decompilation to RB AST
> IR is built from AST using ASTTranslator:
— AST Visitor
— Uses IRBuilder
© Oscar Nierstrasz
ST — Working with Bytecode
11.17
Compiler: Bytecode Generation
> IR needs to be converted to Bytecode
— IRTranslator: Visitor for IR tree
— Uses BytecodeBuilder to generate Bytecode
— Builds a compiledMethod
— Details to follow next section
testReturn1
| iRMethod aCompiledMethod |
iRMethod := IRBuilder new
numRargs: 1;
addTemps: #(self); "receiver and args declarations"
pushLiteral: 1;
returnTop;
ir.
aCompiledMethod := iRMethod compiledMethod.
self should:
[(aCompiledMethod
valueWithReceiver: nil
arguments: #() ) = 1].
© Oscar Nierstrasz
ST — Working with Bytecode
11.18
Roadmap
> The Pharo compiler
> Introduction to Pharo bytecode
> Generating bytecode with IRBuilder
> Parsing and Interpreting bytecode
© Oscar Nierstrasz
ST — Working with Bytecode
11.19
Reasons for working with Bytecode
> Generating Bytecode
— Implementing compilers for other languages
— Experimentation with new language features
> Parsing and Interpretation:
— Analysis (e.g., self and super sends)
— Decompilation (for systems without source)
— Printing of bytecode
— Interpretation: Debugger, Profiler
© Oscar Nierstrasz
ST — Working with Bytecode
11.20
The Pharo Virtual Machine
> Virtual machine provides a virtual processor
— Bytecode: The “machine-code” of the virtual machine
> Smalltalk (like Java): Stack machine
— easy to implement interpreters for different processors
— most hardware processors are register machines
> Pharo VM: Implemented in Slang
— Slang: Subset of Smalltalk. (“C with Smalltalk Syntax”)
— Translated to C
© Oscar Nierstrasz
ST — Working with Bytecode
11.21
Bytecode in the CompiledMethod
> CompiledMethod format:
Number of
temps, literals...
Array of all
Literal Objects
Pointer to
Source
Header
Literals
Bytecode
Trailer
(Number methodDict at: #asInteger) inspect
(Number>>#asInteger) inspect
© Oscar Nierstrasz
ST — Working with Bytecode
11.22
Bytecodes: Single or multibyte
> Different forms of bytecodes:
— Single bytecodes:
– Example: 120: push self
— Groups of similar bytecodes
– 16: push temp 1
– 17: push temp 2
– up to 31
— Multibyte bytecodes
– Problem: 4 bit offset may be too small
– Solution: Use the following byte as offset
– Example: Jumps need to encode large jump offsets
Type Offset
4 bits 4 bits
© Oscar Nierstrasz
ST — Working with Bytecode
11.23
> Smalltalk code:
> Symbolic Bytecode
Example: Number>>asInteger
Number>>asInteger
"Answer an Integer nearest
the receiver toward zero."
^self truncated
9 <70> self
10 <D0> send: truncated
11 <7C> returnTop
© Oscar Nierstrasz
ST — Working with Bytecode
11.24
Example: Step by Step
> 9 <70> self
— The receiver (self) is pushed on the stack
> 10 <D0> send: truncated
— Bytecode 208: send litereral selector 1
— Get the selector from the first literal
— start message lookup in the class of the object that is on top of
the stack
— result is pushed on the stack
> 11 <7C> returnTop
— return the object on top of the stack to the calling method
© Oscar Nierstrasz
ST — Working with Bytecode
11.25
Pharo Bytecode
> 256 Bytecodes, four groups:
— Stack Bytecodes
– Stack manipulation: push / pop / dup
— Send Bytecodes
– Invoke Methods
— Return Bytecodes
– Return to caller
— Jump Bytecodes
– Control flow inside a method
© Oscar Nierstrasz
ST — Working with Bytecode
11.26
Stack Bytecodes
> Push values on the stack
— e.g., temps, instVars, literals
— e.g: 16 - 31: push instance variable
> Push Constants
— False/True/Nil/1/0/2/-1
> Push self, thisContext
> Duplicate top of stack
> Pop
© Oscar Nierstrasz
ST — Working with Bytecode
11.27
Sends and Returns
> Sends: receiver is on top of stack
— Normal send
— Super Sends
— Hard-coded sends for efficiency, e.g. +, -
> Returns
— Return top of stack to the sender
— Return from a block
— Special bytecodes for return self, nil, true, false (for
efficiency)
© Oscar Nierstrasz
ST — Working with Bytecode
11.28
> Control Flow inside one method
— Used to implement control-flow efficiently
— Example:
Jump Bytecodes
9 <76> pushConstant: 1
10 <77> pushConstant: 2
11 <B2> send: <
12 <99> jumpFalse: 15
13 <20> pushConstant: 'true'
14 <90> jumpTo: 16
15 <73> pushConstant: nil
16 <7C> returnTop
^ 1<2 ifTrue: ['true']
© Oscar Nierstrasz
ST — Working with Bytecode
11.29
Closures
counterBlock | count |
count := 0.
^[ count := count + 1].
© Oscar Nierstrasz
ST — Working with Bytecode
11.30
Closures
> Break the dependency between the block
activation and its enclosing contexts for
accessing locals
© Oscar Nierstrasz
ST — Working with Bytecode
11.31
Contexts
inject: thisValue into: binaryBlock | nextValue
| nextValue := thisValue. self
do: [:each | nextValue := binaryBlock value:
nextValue value: each]. ^nextValue
© Oscar Nierstrasz
ST — Working with Bytecode
11.32
Contexts
inject: thisValue into: binaryBlock |
indirectTemps | indirectTemps := Array new: 1.
indirectTemps at: 1 put: thisValue.
" was nextValue := thisValue." self do:
[:each | indirectTemps at:
1 put: (binaryBlock
value: (indirectTemps at: 1)
value: each)]. ^indirectTemps at: 1
© Oscar Nierstrasz
ST — Working with Bytecode
11.33
Contexts
inject: thisValue into: binaryBlock | indirectTemps |
indirectTemps := Array new: 1. indirectTemps at: 1 put:
thisValue. self do: (thisContext closureCopy:
[:each |
binaryBlockCopy indirectTempsCopy |
indirectTempsCopy at: 1
put: (binaryBlockCopy
value: (indirectTempsCopy at: 1)
value: each)] copiedValues:
(Array with: binaryBlock with: indirectTemps)).
^indirectTemps at: 1
© Oscar Nierstrasz
ST — Working with Bytecode
11.34
> 138 Push (Array new: k)/Pop k into: (Array new: j)
> 140 Push Temp At k In Temp Vector At: j
> 141 Store Temp At k In Temp Vector At: j
> 142 Pop and Store Temp At k In Temp Vector At: j
> 143 Push Closure Num Copied l Num Args k BlockSize j
Closure Bytecode
© Oscar Nierstrasz
ST — Working with Bytecode
11.35
Roadmap
> The Pharo compiler
> Introduction to Pharo bytecode
> Generating bytecode with IRBuilder
> Parsing and Interpreting bytecode
© Oscar Nierstrasz
ST — Working with Bytecode
11.36
Generating Bytecode
> IRBuilder: A tool for generating bytecode
— Part of the NewCompiler
— Pharo: Install packages AST, NewParser, NewCompiler
> Like an Assembler for Pharo
© Oscar Nierstrasz
ST — Working with Bytecode
11.37
IRBuilder: Simple Example
> Number>>asInteger
iRMethod := IRBuilder new
numRargs: 1; "receiver”
addTemps: #(self); "receiver and args"
pushTemp: #self;
send: #truncated;
returnTop;
ir.
aCompiledMethod := iRMethod compiledMethod.
aCompiledMethod valueWithReceiver:3.5
arguments: #() 3
© Oscar Nierstrasz
ST — Working with Bytecode
11.38
IRBuilder: Stack Manipulation
> popTop
— remove the top of stack
> pushDup
— push top of stack on the stack
> pushLiteral:
> pushReceiver
— push self
> pushThisContext
© Oscar Nierstrasz
ST — Working with Bytecode
11.39
IRBuilder: Symbolic Jumps
> Jump targets are resolved:
> Example:
iRMethod := IRBuilder new
numRargs: 1;
addTemps: #(self); "receiver"
pushLiteral: false;
jumpAheadTo: #false if: false;
pushLiteral: 'true'; "ifTrue: ['true']"
jumpAheadTo: #end;
jumpAheadTarget: #false;
pushLiteral: 'false'; "ifFalse: ['false']"
jumpAheadTarget: #end;
returnTop;
ir.
false ifTrue: [’true’] ifFalse: [’false’]
© Oscar Nierstrasz
ST — Working with Bytecode
11.40
IRBuilder: Instance Variables
> Access by offset
> Read: pushInstVar:
— receiver on top of stack
> Write: storeInstVar:
— value on stack
> Example: set the first instance variable to 2
iRMethod := IRBuilder new
numRargs: 1;
addTemps: #(self); "receiver and args"
pushLiteral: 2;
storeInstVar: 1;
pushTemp: #self;
returnTop;
ir.
aCompiledMethod := iRMethod compiledMethod.
aCompiledMethod valueWithReceiver: 1@2 arguments: #() 2@2
© Oscar Nierstrasz
ST — Working with Bytecode
11.41
IRBuilder: Temporary Variables
> Accessed by name
> Define with addTemp: / addTemps:
> Read with pushTemp:
> Write with storeTemp:
> Example:
— set variables a and b, return value of a
iRMethod := IRBuilder new
numRargs: 1;
addTemps: #(self); "receiver"
addTemps: #(a b);
pushLiteral: 1;
storeTemp: #a;
pushLiteral: 2;
storeTemp: #b;
pushTemp: #a;
returnTop;
ir.
© Oscar Nierstrasz
ST — Working with Bytecode
11.42
> normal send
> super send
— The second parameter specifies the class where the lookup
starts.
IRBuilder: Sends
builder pushLiteral: ‘hello’
builder send: #size;
…
builder send: #selector toSuperOf: aClass;
© Oscar Nierstrasz
ST — Working with Bytecode
11.43
Roadmap
> The Pharo compiler
> Introduction to Pharo bytecode
> Generating bytecode with IRBuilder
> Parsing and Interpreting bytecode
© Oscar Nierstrasz
ST — Working with Bytecode
11.44
Parsing and Interpretation
> First step: Parse bytecode
— enough for easy analysis, pretty printing, decompilation
> Second step: Interpretation
— needed for simulation, complex analyis (e.g., profiling)
> Pharo provides frameworks for both:
— InstructionStream/InstructionClient (parsing)
— ContextPart (Interpretation)
© Oscar Nierstrasz
ST — Working with Bytecode
11.45
The InstructionStream Hierarchy
InstructionStream
ContextPart
BlockContext
MethodContext
Decompiler
InstructionPrinter
InstVarRefLocator
BytecodeDecompiler
© Oscar Nierstrasz
ST — Working with Bytecode
11.46
InstructionStream
> Parses the byte-encoded instructions
> State:
— pc: program counter
— sender: the method (bad name!)
Object subclass: #InstructionStream
instanceVariableNames: 'sender pc'
classVariableNames: 'SpecialConstants'
poolDictionaries: ''
category: 'Kernel-Methods'
© Oscar Nierstrasz
ST — Working with Bytecode
11.47
> Generate an instance:
> Now we can step through the bytecode with:
> Calls methods on a client object for the type of
bytecode, e.g.
— pushReceiver
— pushConstant: value
— pushReceiverVariable: offset
Usage
instrStream := InstructionStream on: aMethod
instrStream interpretNextInstructionFor: client
© Oscar Nierstrasz
ST — Working with Bytecode
11.48
InstructionClient
> Abstract superclass
— Defines empty methods for all methods that InstructionStream
calls on a client
> For convenience:
— Clients don’t need to inherit from this class
Object subclass: #InstructionClient
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Kernel-Methods'
© Oscar Nierstrasz
ST — Working with Bytecode
11.49
Example: A test
InstructionClientTest>>testInstructions
"just interpret all of methods of Object"
| methods client scanner|
methods := Object methodDict values.
client := InstructionClient new.
methods do: [:method |
scanner := (InstructionStream on: method).
[scanner pc <= method endPC] whileTrue: [
self shouldnt:
[scanner interpretNextInstructionFor: client]
raise: Error.
].
].
© Oscar Nierstrasz
ST — Working with Bytecode
11.50
Example: Printing Bytecode
> InstructionPrinter:
— Print the bytecodes as human readable text
> Example:
— print the bytecode of Number>>asInteger:
String streamContents:
[:str | (InstructionPrinter on: Number>>#asInteger)
printInstructionsOn: str ]
'9 <70> self
10 <D0> send: truncated
11 <7C> returnTop
'
© Oscar Nierstrasz
ST — Working with Bytecode
11.51
InstructionPrinter
> Class Definition:
InstructionClient subclass: #InstructionPrinter
instanceVariableNames: 'method scanner
stream indent'
classVariableNames: ''
poolDictionaries: ''
category: 'Kernel-Methods'
© Oscar Nierstrasz
ST — Working with Bytecode
11.52
InstructionPrinter
> Main Loop:
InstructionPrinter>>printInstructionsOn: aStream
"Append to the stream, aStream, a description
of each bytecode in the instruction stream."
| end |
stream := aStream.
scanner := InstructionStream on: method.
end := method endPC.
[scanner pc <= end]
whileTrue: [scanner interpretNextInstructionFor: self]
© Oscar Nierstrasz
ST — Working with Bytecode
11.53
InstructionPrinter
> Overwrites methods from InstructionClient to print
the bytecodes as text
> e.g. the method for pushReceiver
InstructionPrinter>>pushReceiver
"Print the Push Active Context's Receiver
on Top Of Stack bytecode."
self print: 'self'
© Oscar Nierstrasz
ST — Working with Bytecode
11.54
Example: InstVarRefLocator
InstructionClient subclass: #InstVarRefLocator
instanceVariableNames: 'bingo'
classVariableNames: ''
poolDictionaries: ''
category: 'Kernel-Methods'
InstVarRefLocator>>interpretNextInstructionUsing: aScanner
bingo := false.
aScanner interpretNextInstructionFor: self.
^bingo
InstVarRefLocator>>popIntoReceiverVariable: offset
bingo := true
InstVarRefLocator>>pushReceiverVariable: offset
bingo := true
InstVarRefLocator>>storeIntoReceiverVariable: offset
bingo := true
© Oscar Nierstrasz
ST — Working with Bytecode
11.55
InstVarRefLocator
> Analyse a method, answer true if it references an
instance variable
CompiledMethod>>hasInstVarRef
"Answer whether the receiver references an instance variable."
| scanner end printer |
scanner := InstructionStream on: self.
printer := InstVarRefLocator new.
end := self endPC.
[scanner pc <= end] whileTrue:
[ (printer interpretNextInstructionUsing: scanner)
ifTrue: [^true]. ].
^false
© Oscar Nierstrasz
ST — Working with Bytecode
11.56
InstVarRefLocator
> Example for a simple bytecode analyzer
> Usage:
> (has reference to variable testSelector)
> (has no reference to a variable)
aMethod hasInstVarRef
(TestCase>>#debug) hasInstVarRef
(Integer>>#+) hasInstVarRef
true
false
© Oscar Nierstrasz
ST — Working with Bytecode
11.57
ContextPart: Semantics for Execution
> Sometimes we need more than parsing
— “stepping” in the debugger
— system simulation for profiling
InstructionStream subclass: #ContextPart
instanceVariableNames: 'stackp'
classVariableNames: 'PrimitiveFailToken QuickStep'
poolDictionaries: ''
category: 'Kernel-Methods'
© Oscar Nierstrasz
ST — Working with Bytecode
11.58
Simulation
> Provides a complete Bytecode interpreter
> Run a block with the simulator:
(ContextPart runSimulated: [3 factorial]) 6
© Oscar Nierstrasz
ST — Working with Bytecode
11.59
Profiling: MessageTally
> Usage:
> Other example:
MessageTally tallySends: [3 factorial]
MessageTally tallySends: [’3’ + 1]
This simulation took 0.0 seconds.
**Tree**
1 SmallInteger(Integer)>>factorial
1 SmallInteger(Integer)>>factorial
1 SmallInteger(Integer)>>factorial
1 SmallInteger(Integer)>>factorial
© Oscar Nierstrasz
ST — Working with Bytecode
11.60
What you should know!
What are the problems of the old compiler?
How is the new Pharo compiler organized?
What does the Pharo semantic analyzer add to the
parser-generated AST?
What is the format of the intermediate representation?
What kind of virtual machine does the Pharo bytecode
address?
How can you inspect the bytecode of a particular
method?
© Oscar Nierstrasz
ST — Working with Bytecode
11.61
Can you answer these questions?
What different groups of bytecode are supported?
Why is the SmaCC grammar only BNF-“like”?
How can you find out what all the bytecodes are?
What is the purpose of IRBuilder?
Why do we not generate bytecode directly?
What is the responsibility of class InstructionStream?
How would you implement a statement coverage
analyzer?
© Oscar Nierstrasz
ST — Introduction
1.62
Attribution-ShareAlike 3.0 Unported
You are free:
to Share — to copy, distribute and transmit the work
to Remix — to adapt the work
Under the following conditions:
Attribution. You must attribute the work in the manner specified by the author or
licensor (but not in any way that suggests that they endorse you or your use of the
work).
Share Alike. If you alter, transform, or build upon this work, you may distribute the
resulting work only under the same, similar or a compatible license.
For any reuse or distribution, you must make clear to others the license terms of this work.
The best way to do this is with a link to this web page.
Any of the above conditions can be waived if you get permission from the copyright holder.
Nothing in this license impairs or restricts the author's moral rights.
License
http://creativecommons.org/licenses/by-sa/3.0/

More Related Content

What's hot

Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
thnetos
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
John Stevenson
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
Robert Brown
 
Ts archiving
Ts   archivingTs   archiving
Ts archivingConfiz
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
rsebbe
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatchcqtt191
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
John Stevenson
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
Claudio Capobianco
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
Matteo Battaglio
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy
Alonso Torres
 
Distributed systems at ok.ru #rigadevday
Distributed systems at ok.ru #rigadevdayDistributed systems at ok.ru #rigadevday
Distributed systems at ok.ru #rigadevday
odnoklassniki.ru
 
Finding root blocker in oracle database
Finding root blocker in oracle databaseFinding root blocker in oracle database
Finding root blocker in oracle databaseMohsen B
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM
Mario Fusco
 
bluespec talk
bluespec talkbluespec talk
bluespec talk
Suman Karumuri
 
Rust-lang
Rust-langRust-lang
Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22
nikomatsakis
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
Alex Miller
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode Compiler
Donal Fellows
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
Prashant Rane
 

What's hot (20)

Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
 
Ts archiving
Ts   archivingTs   archiving
Ts archiving
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy
 
Distributed systems at ok.ru #rigadevday
Distributed systems at ok.ru #rigadevdayDistributed systems at ok.ru #rigadevday
Distributed systems at ok.ru #rigadevday
 
Finding root blocker in oracle database
Finding root blocker in oracle databaseFinding root blocker in oracle database
Finding root blocker in oracle database
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM
 
bluespec talk
bluespec talkbluespec talk
bluespec talk
 
Rust-lang
Rust-langRust-lang
Rust-lang
 
Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22
 
分散式系統
分散式系統分散式系統
分散式系統
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode Compiler
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
 

Viewers also liked (20)

Stoop 413-abstract classes
Stoop 413-abstract classesStoop 413-abstract classes
Stoop 413-abstract classes
 
Stoop 434-composite
Stoop 434-compositeStoop 434-composite
Stoop 434-composite
 
Stoop ed-frameworks
Stoop ed-frameworksStoop ed-frameworks
Stoop ed-frameworks
 
Stoop sed-sharing ornot
Stoop sed-sharing ornotStoop sed-sharing ornot
Stoop sed-sharing ornot
 
03 standardclasses
03 standardclasses03 standardclasses
03 standardclasses
 
Stoop 415-design points
Stoop 415-design pointsStoop 415-design points
Stoop 415-design points
 
Stoop 433-chain
Stoop 433-chainStoop 433-chain
Stoop 433-chain
 
Stoop 423-some designpatterns
Stoop 423-some designpatternsStoop 423-some designpatterns
Stoop 423-some designpatterns
 
Stoop ed-dual interface
Stoop ed-dual interfaceStoop ed-dual interface
Stoop ed-dual interface
 
09 metaclasses
09 metaclasses09 metaclasses
09 metaclasses
 
Stoop 416-lsp
Stoop 416-lspStoop 416-lsp
Stoop 416-lsp
 
Stoop 430-design patternsintro
Stoop 430-design patternsintroStoop 430-design patternsintro
Stoop 430-design patternsintro
 
Stoop 400 o-metaclassonly
Stoop 400 o-metaclassonlyStoop 400 o-metaclassonly
Stoop 400 o-metaclassonly
 
Stoop ed-class forreuse
Stoop ed-class forreuseStoop ed-class forreuse
Stoop ed-class forreuse
 
Stoop 450-s unit
Stoop 450-s unitStoop 450-s unit
Stoop 450-s unit
 
Stoop 421-design heuristics
Stoop 421-design heuristicsStoop 421-design heuristics
Stoop 421-design heuristics
 
Stoop 390-instruction stream
Stoop 390-instruction streamStoop 390-instruction stream
Stoop 390-instruction stream
 
Stoop sed-smells
Stoop sed-smellsStoop sed-smells
Stoop sed-smells
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop ed-lod
Stoop ed-lodStoop ed-lod
Stoop ed-lod
 

Similar to 11 bytecode

Opal compiler
Opal compilerOpal compiler
Opal compiler
Jorge Ressia
 
Ropython-windbg-python-extensions
Ropython-windbg-python-extensionsRopython-windbg-python-extensions
Ropython-windbg-python-extensions
Alin Gabriel Serdean
 
C sharp 8.0 new features
C sharp 8.0 new featuresC sharp 8.0 new features
C sharp 8.0 new features
Miguel Bernard
 
C sharp 8.0 new features
C sharp 8.0 new featuresC sharp 8.0 new features
C sharp 8.0 new features
MSDEVMTL
 
Working with Bytecode
Working with BytecodeWorking with Bytecode
Working with Bytecode
Marcus Denker
 
ch11_031102.ppt
ch11_031102.pptch11_031102.ppt
ch11_031102.ppt
Sambasiva62
 
Runtime Bytecode Transformation for Smalltalk
Runtime Bytecode Transformation for SmalltalkRuntime Bytecode Transformation for Smalltalk
Runtime Bytecode Transformation for Smalltalk
Marcus Denker
 
Hands on with Smart Contracts session #3
Hands on with Smart Contracts session #3Hands on with Smart Contracts session #3
Hands on with Smart Contracts session #3
Gene Leybzon
 
Blockchain and smart contracts day 2
Blockchain and smart contracts day 2Blockchain and smart contracts day 2
Blockchain and smart contracts day 2
Gene Leybzon
 
New Virtualization Technologies
New Virtualization TechnologiesNew Virtualization Technologies
New Virtualization Technologies
Open Networking Perú (Opennetsoft)
 
Porting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustPorting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to Rust
Evan Chan
 
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
Susan Potter
 
Refactoring
RefactoringRefactoring
Refactoring
Marcus Denker
 
Kernel Recipes 2014 - NDIV: a low overhead network traffic diverter
Kernel Recipes 2014 - NDIV: a low overhead network traffic diverterKernel Recipes 2014 - NDIV: a low overhead network traffic diverter
Kernel Recipes 2014 - NDIV: a low overhead network traffic diverter
Anne Nicolas
 
Cassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A ComparisonCassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A Comparison
shsedghi
 
Créer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heureCréer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heure
Amaury Bouchard
 

Similar to 11 bytecode (20)

Opal compiler
Opal compilerOpal compiler
Opal compiler
 
02 basics
02 basics02 basics
02 basics
 
Ropython-windbg-python-extensions
Ropython-windbg-python-extensionsRopython-windbg-python-extensions
Ropython-windbg-python-extensions
 
Stoop 305-reflective programming5
Stoop 305-reflective programming5Stoop 305-reflective programming5
Stoop 305-reflective programming5
 
C sharp 8.0 new features
C sharp 8.0 new featuresC sharp 8.0 new features
C sharp 8.0 new features
 
C sharp 8.0 new features
C sharp 8.0 new featuresC sharp 8.0 new features
C sharp 8.0 new features
 
Working with Bytecode
Working with BytecodeWorking with Bytecode
Working with Bytecode
 
ch11_031102.ppt
ch11_031102.pptch11_031102.ppt
ch11_031102.ppt
 
Runtime Bytecode Transformation for Smalltalk
Runtime Bytecode Transformation for SmalltalkRuntime Bytecode Transformation for Smalltalk
Runtime Bytecode Transformation for Smalltalk
 
Hands on with Smart Contracts session #3
Hands on with Smart Contracts session #3Hands on with Smart Contracts session #3
Hands on with Smart Contracts session #3
 
Blockchain and smart contracts day 2
Blockchain and smart contracts day 2Blockchain and smart contracts day 2
Blockchain and smart contracts day 2
 
Phd3
Phd3Phd3
Phd3
 
Phd3
Phd3Phd3
Phd3
 
New Virtualization Technologies
New Virtualization TechnologiesNew Virtualization Technologies
New Virtualization Technologies
 
Porting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustPorting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to Rust
 
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
 
Refactoring
RefactoringRefactoring
Refactoring
 
Kernel Recipes 2014 - NDIV: a low overhead network traffic diverter
Kernel Recipes 2014 - NDIV: a low overhead network traffic diverterKernel Recipes 2014 - NDIV: a low overhead network traffic diverter
Kernel Recipes 2014 - NDIV: a low overhead network traffic diverter
 
Cassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A ComparisonCassandra Java APIs Old and New – A Comparison
Cassandra Java APIs Old and New – A Comparison
 
Créer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heureCréer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heure
 

More from The World of Smalltalk (14)

05 seaside canvas
05 seaside canvas05 seaside canvas
05 seaside canvas
 
99 questions
99 questions99 questions
99 questions
 
13 traits
13 traits13 traits
13 traits
 
06 debugging
06 debugging06 debugging
06 debugging
 
04 idioms
04 idioms04 idioms
04 idioms
 
01 intro
01 intro01 intro
01 intro
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop metaclasses
Stoop metaclassesStoop metaclasses
Stoop metaclasses
 
Stoop ed-unit ofreuse
Stoop ed-unit ofreuseStoop ed-unit ofreuse
Stoop ed-unit ofreuse
 
Stoop ed-subtyping subclassing
Stoop ed-subtyping subclassingStoop ed-subtyping subclassing
Stoop ed-subtyping subclassing
 
Stoop ed-some principles
Stoop ed-some principlesStoop ed-some principles
Stoop ed-some principles
 
Stoop ed-inheritance composition
Stoop ed-inheritance compositionStoop ed-inheritance composition
Stoop ed-inheritance composition
 
Stoop 440-adaptor
Stoop 440-adaptorStoop 440-adaptor
Stoop 440-adaptor
 
Stoop 439-decorator
Stoop 439-decoratorStoop 439-decorator
Stoop 439-decorator
 

Recently uploaded

"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
goswamiyash170123
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 

Recently uploaded (20)

"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 

11 bytecode

  • 1. 11. Working with Bytecode
  • 2. © Oscar Nierstrasz ST — Working with Bytecode 11.2 Roadmap > The Pharo compiler > Introduction to Pharo bytecode > Generating bytecode with IRBuilder > Parsing and Interpreting bytecode Original material by Marcus Denker
  • 3. © Oscar Nierstrasz ST — Working with Bytecode 11.3 Roadmap > The Pharo compiler > Introduction to Pharo bytecode > Generating bytecode with IRBuilder > Parsing and Interpreting bytecode
  • 4. © Oscar Nierstrasz ST — Working with Bytecode 11.4 The Pharo Compiler > Default compiler — very old design — quite hard to understand — impossible to modify and extend > New compiler for Pharo — http://www.iam.unibe.ch/~scg/Research/NewCompiler/ — adds support for true block closures (optional)
  • 5. © Oscar Nierstrasz ST — Working with Bytecode 11.5 The Pharo Compiler > Fully reified compilation process: — Scanner/Parser (built with SmaCC) – builds AST (from Refactoring Browser) — Semantic Analysis: ASTChecker – annotates the AST (e.g., var bindings) — Translation to IR: ASTTranslator – uses IRBuilder to build IR (Intermediate Representation) — Bytecode generation: IRTranslator – uses BytecodeBuilder to emit bytecodes
  • 6. © Oscar Nierstrasz ST — Working with Bytecode 11.6 Compiler: Overview code AST AST Scanner / Parser Semantic Analysis Bytecode Code Generation AST IR Build IR Bytecode Bytecode Generation ASTTranslator IRBuilder IRTranslator BytecodeBuilder Code generation in detail
  • 7. © Oscar Nierstrasz ST — Working with Bytecode 11.7 Compiler: Syntax > SmaCC: Smalltalk Compiler Compiler — Similar to Lex/Yacc — SmaCC can build LARL(1) or LR(1) parser > Input: — Scanner definition: regular expressions — Parser: BNF-like grammar — Code that builds AST as annotation > Output: — class for Scanner (subclass SmaCCScanner) — class for Parser (subclass SmaCCParser)
  • 8. © Oscar Nierstrasz ST — Working with Bytecode 11.8 Scanner
  • 9. © Oscar Nierstrasz ST — Working with Bytecode 11.9 Parser
  • 10. © Oscar Nierstrasz ST — Working with Bytecode 11.10 Calling Parser code
  • 11. © Oscar Nierstrasz ST — Working with Bytecode 11.11 Compiler: AST > AST: Abstract Syntax Tree — Encodes the Syntax as a Tree — No semantics yet! — Uses the RB Tree: – Visitors – Backward pointers in ParseNodes – Transformation (replace/add/delete) – Pattern-directed TreeRewriter – PrettyPrinter RBProgramNode RBDoItNode RBMethodNode RBReturnNode RBSequenceNode RBValueNode RBArrayNode RBAssignmentNode RBBlockNode RBCascadeNode RBLiteralNode RBMessageNode RBOptimizedNode RBVariableNode
  • 12. © Oscar Nierstrasz ST — Working with Bytecode 11.12 Compiler: Semantics > We need to analyse the AST — Names need to be linked to the variables according to the scoping rules > ASTChecker implemented as a Visitor — Subclass of RBProgramNodeVisitor — Visits the nodes — Grows and shrinks scope chain — Methods/Blocks are linked with the scope — Variable definitions and references are linked with objects describing the variables
  • 13. © Oscar Nierstrasz ST — Working with Bytecode 11.13 A Simple Tree RBParser parseExpression: '3+4' NB: explore it
  • 14. © Oscar Nierstrasz ST — Working with Bytecode 11.14 A Simple Visitor RBProgramNodeVisitor new visitNode: tree Does nothing except walk through the tree
  • 15. © Oscar Nierstrasz ST — Working with Bytecode 11.15 TestVisitor RBProgramNodeVisitor subclass: #TestVisitor instanceVariableNames: 'literals' classVariableNames: '' poolDictionaries: '' category: 'Compiler-AST-Visitors' TestVisitor>>acceptLiteralNode: aLiteralNode literals add: aLiteralNode value. TestVisitor>>initialize literals := Set new. TestVisitor>>literals ^literals tree := RBParser parseExpression: '3 + 4'. (TestVisitor new visitNode: tree) literals a Set(3 4)
  • 16. © Oscar Nierstrasz ST — Working with Bytecode 11.16 Compiler: Intermediate Representation > IR: Intermediate Representation — Semantic like Bytecode, but more abstract — Independent of the bytecode set — IR is a tree — IR nodes allow easy transformation — Decompilation to RB AST > IR is built from AST using ASTTranslator: — AST Visitor — Uses IRBuilder
  • 17. © Oscar Nierstrasz ST — Working with Bytecode 11.17 Compiler: Bytecode Generation > IR needs to be converted to Bytecode — IRTranslator: Visitor for IR tree — Uses BytecodeBuilder to generate Bytecode — Builds a compiledMethod — Details to follow next section testReturn1 | iRMethod aCompiledMethod | iRMethod := IRBuilder new numRargs: 1; addTemps: #(self); "receiver and args declarations" pushLiteral: 1; returnTop; ir. aCompiledMethod := iRMethod compiledMethod. self should: [(aCompiledMethod valueWithReceiver: nil arguments: #() ) = 1].
  • 18. © Oscar Nierstrasz ST — Working with Bytecode 11.18 Roadmap > The Pharo compiler > Introduction to Pharo bytecode > Generating bytecode with IRBuilder > Parsing and Interpreting bytecode
  • 19. © Oscar Nierstrasz ST — Working with Bytecode 11.19 Reasons for working with Bytecode > Generating Bytecode — Implementing compilers for other languages — Experimentation with new language features > Parsing and Interpretation: — Analysis (e.g., self and super sends) — Decompilation (for systems without source) — Printing of bytecode — Interpretation: Debugger, Profiler
  • 20. © Oscar Nierstrasz ST — Working with Bytecode 11.20 The Pharo Virtual Machine > Virtual machine provides a virtual processor — Bytecode: The “machine-code” of the virtual machine > Smalltalk (like Java): Stack machine — easy to implement interpreters for different processors — most hardware processors are register machines > Pharo VM: Implemented in Slang — Slang: Subset of Smalltalk. (“C with Smalltalk Syntax”) — Translated to C
  • 21. © Oscar Nierstrasz ST — Working with Bytecode 11.21 Bytecode in the CompiledMethod > CompiledMethod format: Number of temps, literals... Array of all Literal Objects Pointer to Source Header Literals Bytecode Trailer (Number methodDict at: #asInteger) inspect (Number>>#asInteger) inspect
  • 22. © Oscar Nierstrasz ST — Working with Bytecode 11.22 Bytecodes: Single or multibyte > Different forms of bytecodes: — Single bytecodes: – Example: 120: push self — Groups of similar bytecodes – 16: push temp 1 – 17: push temp 2 – up to 31 — Multibyte bytecodes – Problem: 4 bit offset may be too small – Solution: Use the following byte as offset – Example: Jumps need to encode large jump offsets Type Offset 4 bits 4 bits
  • 23. © Oscar Nierstrasz ST — Working with Bytecode 11.23 > Smalltalk code: > Symbolic Bytecode Example: Number>>asInteger Number>>asInteger "Answer an Integer nearest the receiver toward zero." ^self truncated 9 <70> self 10 <D0> send: truncated 11 <7C> returnTop
  • 24. © Oscar Nierstrasz ST — Working with Bytecode 11.24 Example: Step by Step > 9 <70> self — The receiver (self) is pushed on the stack > 10 <D0> send: truncated — Bytecode 208: send litereral selector 1 — Get the selector from the first literal — start message lookup in the class of the object that is on top of the stack — result is pushed on the stack > 11 <7C> returnTop — return the object on top of the stack to the calling method
  • 25. © Oscar Nierstrasz ST — Working with Bytecode 11.25 Pharo Bytecode > 256 Bytecodes, four groups: — Stack Bytecodes – Stack manipulation: push / pop / dup — Send Bytecodes – Invoke Methods — Return Bytecodes – Return to caller — Jump Bytecodes – Control flow inside a method
  • 26. © Oscar Nierstrasz ST — Working with Bytecode 11.26 Stack Bytecodes > Push values on the stack — e.g., temps, instVars, literals — e.g: 16 - 31: push instance variable > Push Constants — False/True/Nil/1/0/2/-1 > Push self, thisContext > Duplicate top of stack > Pop
  • 27. © Oscar Nierstrasz ST — Working with Bytecode 11.27 Sends and Returns > Sends: receiver is on top of stack — Normal send — Super Sends — Hard-coded sends for efficiency, e.g. +, - > Returns — Return top of stack to the sender — Return from a block — Special bytecodes for return self, nil, true, false (for efficiency)
  • 28. © Oscar Nierstrasz ST — Working with Bytecode 11.28 > Control Flow inside one method — Used to implement control-flow efficiently — Example: Jump Bytecodes 9 <76> pushConstant: 1 10 <77> pushConstant: 2 11 <B2> send: < 12 <99> jumpFalse: 15 13 <20> pushConstant: 'true' 14 <90> jumpTo: 16 15 <73> pushConstant: nil 16 <7C> returnTop ^ 1<2 ifTrue: ['true']
  • 29. © Oscar Nierstrasz ST — Working with Bytecode 11.29 Closures counterBlock | count | count := 0. ^[ count := count + 1].
  • 30. © Oscar Nierstrasz ST — Working with Bytecode 11.30 Closures > Break the dependency between the block activation and its enclosing contexts for accessing locals
  • 31. © Oscar Nierstrasz ST — Working with Bytecode 11.31 Contexts inject: thisValue into: binaryBlock | nextValue | nextValue := thisValue. self do: [:each | nextValue := binaryBlock value: nextValue value: each]. ^nextValue
  • 32. © Oscar Nierstrasz ST — Working with Bytecode 11.32 Contexts inject: thisValue into: binaryBlock | indirectTemps | indirectTemps := Array new: 1. indirectTemps at: 1 put: thisValue. " was nextValue := thisValue." self do: [:each | indirectTemps at: 1 put: (binaryBlock value: (indirectTemps at: 1) value: each)]. ^indirectTemps at: 1
  • 33. © Oscar Nierstrasz ST — Working with Bytecode 11.33 Contexts inject: thisValue into: binaryBlock | indirectTemps | indirectTemps := Array new: 1. indirectTemps at: 1 put: thisValue. self do: (thisContext closureCopy: [:each | binaryBlockCopy indirectTempsCopy | indirectTempsCopy at: 1 put: (binaryBlockCopy value: (indirectTempsCopy at: 1) value: each)] copiedValues: (Array with: binaryBlock with: indirectTemps)). ^indirectTemps at: 1
  • 34. © Oscar Nierstrasz ST — Working with Bytecode 11.34 > 138 Push (Array new: k)/Pop k into: (Array new: j) > 140 Push Temp At k In Temp Vector At: j > 141 Store Temp At k In Temp Vector At: j > 142 Pop and Store Temp At k In Temp Vector At: j > 143 Push Closure Num Copied l Num Args k BlockSize j Closure Bytecode
  • 35. © Oscar Nierstrasz ST — Working with Bytecode 11.35 Roadmap > The Pharo compiler > Introduction to Pharo bytecode > Generating bytecode with IRBuilder > Parsing and Interpreting bytecode
  • 36. © Oscar Nierstrasz ST — Working with Bytecode 11.36 Generating Bytecode > IRBuilder: A tool for generating bytecode — Part of the NewCompiler — Pharo: Install packages AST, NewParser, NewCompiler > Like an Assembler for Pharo
  • 37. © Oscar Nierstrasz ST — Working with Bytecode 11.37 IRBuilder: Simple Example > Number>>asInteger iRMethod := IRBuilder new numRargs: 1; "receiver” addTemps: #(self); "receiver and args" pushTemp: #self; send: #truncated; returnTop; ir. aCompiledMethod := iRMethod compiledMethod. aCompiledMethod valueWithReceiver:3.5 arguments: #() 3
  • 38. © Oscar Nierstrasz ST — Working with Bytecode 11.38 IRBuilder: Stack Manipulation > popTop — remove the top of stack > pushDup — push top of stack on the stack > pushLiteral: > pushReceiver — push self > pushThisContext
  • 39. © Oscar Nierstrasz ST — Working with Bytecode 11.39 IRBuilder: Symbolic Jumps > Jump targets are resolved: > Example: iRMethod := IRBuilder new numRargs: 1; addTemps: #(self); "receiver" pushLiteral: false; jumpAheadTo: #false if: false; pushLiteral: 'true'; "ifTrue: ['true']" jumpAheadTo: #end; jumpAheadTarget: #false; pushLiteral: 'false'; "ifFalse: ['false']" jumpAheadTarget: #end; returnTop; ir. false ifTrue: [’true’] ifFalse: [’false’]
  • 40. © Oscar Nierstrasz ST — Working with Bytecode 11.40 IRBuilder: Instance Variables > Access by offset > Read: pushInstVar: — receiver on top of stack > Write: storeInstVar: — value on stack > Example: set the first instance variable to 2 iRMethod := IRBuilder new numRargs: 1; addTemps: #(self); "receiver and args" pushLiteral: 2; storeInstVar: 1; pushTemp: #self; returnTop; ir. aCompiledMethod := iRMethod compiledMethod. aCompiledMethod valueWithReceiver: 1@2 arguments: #() 2@2
  • 41. © Oscar Nierstrasz ST — Working with Bytecode 11.41 IRBuilder: Temporary Variables > Accessed by name > Define with addTemp: / addTemps: > Read with pushTemp: > Write with storeTemp: > Example: — set variables a and b, return value of a iRMethod := IRBuilder new numRargs: 1; addTemps: #(self); "receiver" addTemps: #(a b); pushLiteral: 1; storeTemp: #a; pushLiteral: 2; storeTemp: #b; pushTemp: #a; returnTop; ir.
  • 42. © Oscar Nierstrasz ST — Working with Bytecode 11.42 > normal send > super send — The second parameter specifies the class where the lookup starts. IRBuilder: Sends builder pushLiteral: ‘hello’ builder send: #size; … builder send: #selector toSuperOf: aClass;
  • 43. © Oscar Nierstrasz ST — Working with Bytecode 11.43 Roadmap > The Pharo compiler > Introduction to Pharo bytecode > Generating bytecode with IRBuilder > Parsing and Interpreting bytecode
  • 44. © Oscar Nierstrasz ST — Working with Bytecode 11.44 Parsing and Interpretation > First step: Parse bytecode — enough for easy analysis, pretty printing, decompilation > Second step: Interpretation — needed for simulation, complex analyis (e.g., profiling) > Pharo provides frameworks for both: — InstructionStream/InstructionClient (parsing) — ContextPart (Interpretation)
  • 45. © Oscar Nierstrasz ST — Working with Bytecode 11.45 The InstructionStream Hierarchy InstructionStream ContextPart BlockContext MethodContext Decompiler InstructionPrinter InstVarRefLocator BytecodeDecompiler
  • 46. © Oscar Nierstrasz ST — Working with Bytecode 11.46 InstructionStream > Parses the byte-encoded instructions > State: — pc: program counter — sender: the method (bad name!) Object subclass: #InstructionStream instanceVariableNames: 'sender pc' classVariableNames: 'SpecialConstants' poolDictionaries: '' category: 'Kernel-Methods'
  • 47. © Oscar Nierstrasz ST — Working with Bytecode 11.47 > Generate an instance: > Now we can step through the bytecode with: > Calls methods on a client object for the type of bytecode, e.g. — pushReceiver — pushConstant: value — pushReceiverVariable: offset Usage instrStream := InstructionStream on: aMethod instrStream interpretNextInstructionFor: client
  • 48. © Oscar Nierstrasz ST — Working with Bytecode 11.48 InstructionClient > Abstract superclass — Defines empty methods for all methods that InstructionStream calls on a client > For convenience: — Clients don’t need to inherit from this class Object subclass: #InstructionClient instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Methods'
  • 49. © Oscar Nierstrasz ST — Working with Bytecode 11.49 Example: A test InstructionClientTest>>testInstructions "just interpret all of methods of Object" | methods client scanner| methods := Object methodDict values. client := InstructionClient new. methods do: [:method | scanner := (InstructionStream on: method). [scanner pc <= method endPC] whileTrue: [ self shouldnt: [scanner interpretNextInstructionFor: client] raise: Error. ]. ].
  • 50. © Oscar Nierstrasz ST — Working with Bytecode 11.50 Example: Printing Bytecode > InstructionPrinter: — Print the bytecodes as human readable text > Example: — print the bytecode of Number>>asInteger: String streamContents: [:str | (InstructionPrinter on: Number>>#asInteger) printInstructionsOn: str ] '9 <70> self 10 <D0> send: truncated 11 <7C> returnTop '
  • 51. © Oscar Nierstrasz ST — Working with Bytecode 11.51 InstructionPrinter > Class Definition: InstructionClient subclass: #InstructionPrinter instanceVariableNames: 'method scanner stream indent' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Methods'
  • 52. © Oscar Nierstrasz ST — Working with Bytecode 11.52 InstructionPrinter > Main Loop: InstructionPrinter>>printInstructionsOn: aStream "Append to the stream, aStream, a description of each bytecode in the instruction stream." | end | stream := aStream. scanner := InstructionStream on: method. end := method endPC. [scanner pc <= end] whileTrue: [scanner interpretNextInstructionFor: self]
  • 53. © Oscar Nierstrasz ST — Working with Bytecode 11.53 InstructionPrinter > Overwrites methods from InstructionClient to print the bytecodes as text > e.g. the method for pushReceiver InstructionPrinter>>pushReceiver "Print the Push Active Context's Receiver on Top Of Stack bytecode." self print: 'self'
  • 54. © Oscar Nierstrasz ST — Working with Bytecode 11.54 Example: InstVarRefLocator InstructionClient subclass: #InstVarRefLocator instanceVariableNames: 'bingo' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Methods' InstVarRefLocator>>interpretNextInstructionUsing: aScanner bingo := false. aScanner interpretNextInstructionFor: self. ^bingo InstVarRefLocator>>popIntoReceiverVariable: offset bingo := true InstVarRefLocator>>pushReceiverVariable: offset bingo := true InstVarRefLocator>>storeIntoReceiverVariable: offset bingo := true
  • 55. © Oscar Nierstrasz ST — Working with Bytecode 11.55 InstVarRefLocator > Analyse a method, answer true if it references an instance variable CompiledMethod>>hasInstVarRef "Answer whether the receiver references an instance variable." | scanner end printer | scanner := InstructionStream on: self. printer := InstVarRefLocator new. end := self endPC. [scanner pc <= end] whileTrue: [ (printer interpretNextInstructionUsing: scanner) ifTrue: [^true]. ]. ^false
  • 56. © Oscar Nierstrasz ST — Working with Bytecode 11.56 InstVarRefLocator > Example for a simple bytecode analyzer > Usage: > (has reference to variable testSelector) > (has no reference to a variable) aMethod hasInstVarRef (TestCase>>#debug) hasInstVarRef (Integer>>#+) hasInstVarRef true false
  • 57. © Oscar Nierstrasz ST — Working with Bytecode 11.57 ContextPart: Semantics for Execution > Sometimes we need more than parsing — “stepping” in the debugger — system simulation for profiling InstructionStream subclass: #ContextPart instanceVariableNames: 'stackp' classVariableNames: 'PrimitiveFailToken QuickStep' poolDictionaries: '' category: 'Kernel-Methods'
  • 58. © Oscar Nierstrasz ST — Working with Bytecode 11.58 Simulation > Provides a complete Bytecode interpreter > Run a block with the simulator: (ContextPart runSimulated: [3 factorial]) 6
  • 59. © Oscar Nierstrasz ST — Working with Bytecode 11.59 Profiling: MessageTally > Usage: > Other example: MessageTally tallySends: [3 factorial] MessageTally tallySends: [’3’ + 1] This simulation took 0.0 seconds. **Tree** 1 SmallInteger(Integer)>>factorial 1 SmallInteger(Integer)>>factorial 1 SmallInteger(Integer)>>factorial 1 SmallInteger(Integer)>>factorial
  • 60. © Oscar Nierstrasz ST — Working with Bytecode 11.60 What you should know! What are the problems of the old compiler? How is the new Pharo compiler organized? What does the Pharo semantic analyzer add to the parser-generated AST? What is the format of the intermediate representation? What kind of virtual machine does the Pharo bytecode address? How can you inspect the bytecode of a particular method?
  • 61. © Oscar Nierstrasz ST — Working with Bytecode 11.61 Can you answer these questions? What different groups of bytecode are supported? Why is the SmaCC grammar only BNF-“like”? How can you find out what all the bytecodes are? What is the purpose of IRBuilder? Why do we not generate bytecode directly? What is the responsibility of class InstructionStream? How would you implement a statement coverage analyzer?
  • 62. © Oscar Nierstrasz ST — Introduction 1.62 Attribution-ShareAlike 3.0 Unported You are free: to Share — to copy, distribute and transmit the work to Remix — to adapt the work Under the following conditions: Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license. For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a link to this web page. Any of the above conditions can be waived if you get permission from the copyright holder. Nothing in this license impairs or restricts the author's moral rights. License http://creativecommons.org/licenses/by-sa/3.0/