Tag Archives: bytecodes

Introduction to Smalltalk bytecodes

Hi all. It this post I will give you a quick overview and introduction to bytecodes. I won’t talk that much because this topic is well explained in the Blue book, in the code, etc. In the previous posts we saw that a CompiledMethod is all about bytecodes and literals (ok, and a header and a trailer). To really follow the post, I recommend you to have an image with VMMaker. If you don’t know how to do it, please see the title “Prepare the image” of a previous post.

Bytecodes introduction

Let’s start from the beginning: What is a bytecode?  A bytecode is a compact and platform neutral representation of machine code instructions, interpreted by VM. When you code and then save a method in Smalltalk, the Compiler generates an instance of CompiledMethod. Your method’s code is decomposed by the Compiler into a set of basic instructions so that the VM can interpret them.

We have also seen that a CompiledMethod is just an array of bytes. And “BYTEcode” has the prefix “byte”. So, as you can imagine, every bytecode is represented by a byte. One bytecode, one byte (sure?? mmmm). One byte, 8 bits, 2^8 -1 = 255 possible different bytecodes.

Imagine that we code the following basic method:

MyClass >> foo
self name.

To see the bytecodes there are two possibilities: print the answer of  the message #symbolic to the CompiledMethod instance. For example, (MyClass >> #foo) symbolic or use the SystemBrowser, button “View” -> “byte codes”. The bytecodes from the previous method are:

17 <70> self
18 <D0> send: name
19 <87> pop
20 <78> returnSelf

So…how do we interpret such symbolic representation?

Understanding bytecodes printing

Let’s start from left to right. First “column” is a number. In this case, from 17 to 20. What do those number mean?  Explore or inspect the CompiledMethod:

So, those number represent just the position in the whole array. We said a CM (CompiledMethod) was an array of bytes. So, those number represent the position. The CM has two regions: the literal frame (the first bytes of the CM where the literals are stored) and the bytecodes. These numbers are called “Program Counter” (PC) when they are in the bytecode part. For example, if we send the message #endPC to this CM instance, we will get 20 which is the last byte of the CM that represents bytecodes. The next one, 21, is already representing the trailer. The same way, #initialPC answers 17. And how those two methods are implemented?  the #initialPC uses the header’s encoded information such as the number of literals. And #endPC delegates to its trailer since he knows the size of the trailer.

The second column is an hexadecimal surrounded by <> which represents the bytecode number. For example, <70>,, etc. This hexadecimal represent the unique number of bytecode. ’70’ is the bytecode push receiver, ‘D0’ is a send bytecode, 85 pop stack, and push receiver. Since these numbers are encoded in 1 byte it follows that there are 255 possible differnt type of bytecodes.

The third column is just a text describing the type of bytecode.

If we analyze now the bytecodes generated for our simple method that does a “self name” we have that:  the first bytecode (number 17) it just pushes the receiver (self) into the stack. We need that in the stack because in the next bytecode we send a message to it. The second bytecode, 18, sends the message #name to what it is in the stack. When this bytecode finishes, it pushes in the stack the result of the send. But our method doesn’t do anything with it and instead it just answers self (because there is not explicit return). So, we need to do a pop first, bytecode number 19, to remove the result from stack and let the receiver in the top of the stack. And now, we can finally do the return with bytecode number 20.

Mapping bytecodes from image side to VM side

So far we saw how the bytecodes in the CM look like, but we didn’t see how they are map to the VM. So, take your image with VMMaker loaded, and inspect the method #initializeBytecodeTable. You will see that such method is something like this:

The table follows much more but I cut it for the post. So as you see it is just a table that maps numbers to methods 😉  We saw that the symbolic representation has 3 columns, and the second one which was surrounded by <> and an hexadecimal value represents the number of the bytecode. That number is exactly this one used in this table, with the difference that it is in decimal. So, for example the bytecode “<78> returnSelf”, if we translate 78 from hexa to decimal (just print 16r78)  we get 120, which maps to the method #returnReceiver. So, you can now just browse the method and look what it does 🙂  Remember that this is part of VMMaker and this code is written is SLANG. For more details read my old posts.

StackInterpreter >> returnReceiver
localReturnValue := self receiver.
self commonReturn

You have now learned how to see the bytecodes of a method and how to see its implementation in the VM. Cool!!  You deserve a break (or a beer) 🙂

Did you notice that some bytecodes are mapped directly to one only number (like #returnReceiver) but some other like #pushLiteralVariableBytecode are mapped to a range of numbers?  We will see later why.

More complicated bytecodes

Now, let’s see a more advance method, for example, this one:

fooComplicated: aBool and: aNumber
| something aName |
aName := self name.
Transcript show: aName.
aBool
ifTrue: [ ^ aName ].
^ nil

Which generates the following bytecodes:

25 <70> self
26  send: name
27 <6B> popIntoTemp: 3
28 <42> pushLit: Transcript
29 <13> pushTemp: 3
30  send: show:
31 <87> pop
32 <10> pushTemp: 0
33 <99> jumpFalse: 36
34 <13> pushTemp: 3
35 <7C> returnTop
36 <7B> return: nil

There are a couple of new bytecodes in this method. Bytecode 27, does a pop of the return of “self name” and push it in the temp number 3. Notice that temps are both, parameters and temp variables. In this case, temp 0 is ‘aBool’, temp 1 ‘aNumber’, temp 2 ‘something’ and temp 3 is ‘aName’. Bytecode 28 needs to push the literal “Transcript” into the stack since in the next bytecode a message is sent to it. Bytecode 29 pushes ‘aName’ to the stack since it will be the parameter for the send.  Bytecode 30 does the send and 31 does a pop because we don’t do anything with the return of the message.

With bytecode 32 we put ‘aBool’ into the stack and then….then…shouldn’t we have something like 33 send: ifTrue:ifFalse:  ???  Yes, we should. But the compiler does an optimization and replaces the message send by a jump bytecode. In this case, a jump bytecode saying that when it is false jump to bytecode number 36 which does the return nil. Otherwise (if true), continue with bytecode 34 which pushes ‘aName’ into the stack and finally bytecode 35 does the return of the top of the stack (where we can ‘aName’).

How do we represent parameters in bytecodes?

We shouldn’t forget that btyecodes are just a number between 0 and 255. The bytecode <78> returnSelf  is number 120, which was we can see in #initializeBytecodeTable it is mapped by  (120 returnReceiver). Does this method requires any kind of parameter? No. It just returns the receiver. Now,  let’s analyze the bytecode <6B> popIntoTemp: 3 from the previous example. 16r6B -> 107.  Ok, cool. So, number 107 does a pop and puts that into the temp number 3. But….all what we have in the CompiledMethod is the bytecode, the byte that contains the number 107. Nothing more. Imagine the method in the VM that is mapped to this bytecode….how can it knows the temp number?   The same with bytecode “<42> pushLit: Transcript”. It is just a number,  66. Where is the “Transcript” stored?

So…the generic question is, if we only have a bytecode number, how do we solve the bytecodes that require some parameters ? Ok, this will sound a little weird. Or smart?  The truth is that this missing information is sometimes (we will see later why sometimes) encoded using offsets in the range of bytecodes. Let’s see the example of the  <6B> popIntoTemp: 3, which is bytecode number 107. In #initializeBytecodeTable, we can see: “(104 111 storeAndPopTemporaryVariableBytecode)“. So we have a range of bytecode between 104 and 111. In this case we want to do a pop and put the result in the temp number 3. If we can assume that 104 is for temp 0, 105, temp1, 106 temp2 and 107 temp3 🙂 we now understand why out bytecode number is 107. That bytecode number encodes that the number of the temp is the 3. The method storeAndPopTemporaryVariableBytecode  will be able to get a diff between the current number (107) and the start of this range (104) and finally know that the temp number is the 3th.

The same happens with the other example <42> pushLit: Transcript, number 66. In #initializeBytecodeTable we can see “( 64  95 pushLiteralVariableBytecode)“. 64 is for literal at 1, 65 at 2, and 66 at 3.   Now, do (MyClass >> #fooComplicated:and:) literalAt: 3 -> #Transcript->Transcript  🙂

Now, if we analyze “(104 111 storeAndPopTemporaryVariableBytecode)” we can understand that the maximum amount of temporal variable is 7 (111-104). However, in this post, we saw the class comment of CompiledMethod says “(index 18)    6 bits:    number of temporary variables (#numTemps)”. That means that maximum number of temps is 2^6-1=63 . So…..something is wrong. Let’s find out what.

Extended bytecodes

(104 111 storeAndPopTemporaryVariableBytecode)”  supports 7 temps, but CompiledMethod class comment says 63 are supported. So, let’s create a method with more than 7 temps and let’s see its bytecodes. If we continue with our example we now modify the method to this:

fooComplicated: aBool and: aNumber
| something aName a b c d e f g h i j k |
d := self name.
Transcript show: aName.
aBool
ifTrue: [ ^ aName ].
^ nil

In this case, “d := self name” we are assigning ‘name’ to ‘d’ which is the temp number 7 (remember they start in 0 and the parameters are count together with the temp variables). Hence, the bytecodes are:

 25 <70> self
 26  send: name
 27 <6F> popIntoTemp: 7
 28 <42> pushLit: Transcript
 29 <13> pushTemp: 3
 30  send: show:
 31 <87> pop
 32 <10> pushTemp: 0
 33 <99> jumpFalse: 36
 34 <13> pushTemp: 3
 35 <7C> returnTop
 36 <7B> return: nil

Now, if we just change “d := self name.” to “e := self name.” we would be using the parameter number 8. What would happen? Ok, if you change it you will see that the bytecode changes from “27 <6F> popIntoTemp: 7” to “27 <82 48> popIntoTemp: 8”. Chan! Chan! Chan! What is that???? It seems the bytecode is using in fact 2 bytecodes? (82 and 48).

These kind of bytecodes are called “extended bytecodes”. If we check in #initializeBytecodeTable bytecode 16r82 = 130 is #extendedStoreAndPopBytecode. So at least we know which method is it. Now, what does the 2 bytecode mean (48 in our example) ?  Somehow such second byte should tell us the number of the temp (8 in our example). If we do 16r48 = 72 and check the bytecode 72 we get it is #pushLiteralVariableBytecode, which doesn’t seem to be correct. So, this second byte does not represent a bytecode. Instead, it represents just a byte that encodes information. That information is usually a type and an index, both encoded in one single byte.

In this particular example of #extendedStoreAndPopBytecode uses 2 bits for a type and 6 bits for an index:

extendedStoreBytecode
| descriptor variableType variableIndex association |
<inline: true>
descriptor := self fetchByte.
self fetchNextBytecode.
variableType := descriptor >> 6 bitAnd: 3.
variableIndex := descriptor bitAnd: 63.
variableType = 0 ifTrue:
[^objectMemory storePointer: variableIndex ofObject: self receiver withValue: self internalStackTop].
variableType = 1 ifTrue:
[^self temporary: variableIndex in: localFP put: self internalStackTop].
variableType = 3 ifTrue:
[association := self literal: variableIndex.
^objectMemory storePointer: ValueIndex ofObject: association withValue: self internalStackTop].
self error: 'illegal store'.
^nil

We can see that in our example, 16r48 = 72.  (72 >> 6) bitAnd: 3  -> 1. So, type is 1. The 3 is because it uses 2 bits for the type (2^2-1=3). And 72 bitAnd: 63 -> 8  (which correctly is the number of temp we need). 63 is because 2^6-1=63.  As you can notice, each bytecode is responsible of decoding the information of the second byte. The compiler of course, needs to correctly generate the bytecodes. #extendedStoreAndPopBytecode was an example so that you can understand and learn, but there are much more extended bytecodes. There are even “single extended bytecodes” and “double extended bytecodes”.

Why do we need extended bytecodes?

Well, I am not an expert at all in this subject but I can guess it is because of the size of CompiledMethod. In the previous example of the extended bytecode, it uses two bytes instead of one, as we can see in the explorer:

Notice that bytecode number 27 occupies two (28 is not shown). At the beginning we saw that when we have a “range” in the bytecodes it means that the difference encodes a number, usually an index. But if we need a range of bytecodes for the maximum supported, we would need much more than 255. Hence, more bytes per bytecode.  Since most methods in Smalltalk are short and encode few number of instance variables, parameters, temporal variables, etc, it was decided to use 255 and just use more bytes per bytecode for those cases that was needed. For example:

(CompiledMethod allInstances select: [:each | each numTemps > 7]) size  -> 1337
CompiledMethod instanceCount -> 75786
((1337 * 100) / 75786) asFloat -> 1.7641780803842397

So…only a 1.76% of the CompiledMethod of my image have more than 7 temporal variables. And remember that this was just an example, but there are extended bytecodes for more things. Maybe (I have no idea) with today computers this is not worth it and maybe having 3 or 4 bytes for every bytecode is enough. But since it is like this and working correctly, why to change it?

Groups of bytecodes

Since the specification of the blue book of Smalltalk-80, bytecodes are known to be grouped in different groups. And since the core of Squeak/Pharo VM is implemented in a subset of Smalltalk called SLANG and since we have classes with methods that represents Interpreters….how would these groups be represented? Of course, as method categories!!! So, you can map each of the following group, with a method category of an Interpreter class:

  • Stack manipulation bytecodes: all things related to push and pop.
  • Message sending bytecodes: bytecodes that are used when sending messages.
  • Return bytecodes: are used for different kinds of return.
  • Jump bytecodes are related to conditionals

Look the attached screenshot:

Books and links

In this post it is easy: just read the blue book 🙂   As always, you can download it in pdf from http://stephane.ducasse.free.fr/FreeBooks.html or directly browse the web version provided by Eliot Miranda. For a bytecode introduction read the end of chapter 26  and for more details the whole chapter 28. Notice that the specification has changed a bit from the 80’s and there are now there are more bytecodes but the general idea is still valid.

Advertisements

Playing with CompiledMethod

The today’s stop of this Journey through the VM is about CompiledMethods. In the previous post I explained the different class formats and specially, the unique format of CompiledMethod. Today we are going deeper with them and we will see why they are even more special 😉

Summary of the previous post: CompiledMethod instances are internally represented in the VM as bytes. However, CompiledMethod is the only class in the system that mixes pointers (for the literals) with bytes (for the bytecodes). So those bytes encodes both things.

Inspecting a CompiledMethod

What is the normal way to learn something in Smalltalk? Open your image and check senders, references, or someone who does more or less what you need and try to understand it. In the previous post, I showed you how inspecting or exploring a CompiledMethod give us a lot useful information like the header, the literals, the bytecodes and the trailer. Example:

So this means that at least the Inspector and the Explorer can have access to the CompiledMethod and understand its internal. Let’s take the Inspector (we could have taken also the explorer in which case take a look to CompiledMethod >> #explorerContents). When we inspect a CompiledMethod, the inspector class that is used is CompiledMethodInspector. So, first point, there is a special inspector class for CompiledMethod. Otherwise, if we inspect it with a normal inspector, for example if we do “BasicInspector openOn: (MyClass >> #testSomething)” we have something like this:

CompiledMethodInspector has two important methods:

CompiledMethodInspector >> fieldList

| keys |
keys := OrderedCollection new.
keys add: 'self'.
keys add: 'all bytecodes'.
keys add: 'header'.
1 to: object numLiterals do: [ :i |
keys add: 'literal', i printString ].
object initialPC to: object size do: [ :i |
keys add: i printString ].
^ keys asArray
CompiledMethodInspector  >> selection

| bytecodeIndex |
selectionIndex = 0 ifTrue: [^ ''].
selectionIndex = 1 ifTrue: [^ object ].
selectionIndex = 2 ifTrue: [^ object symbolic].
selectionIndex = 3 ifTrue: [^ object headerDescription].
selectionIndex <= (object numLiterals + 3)
ifTrue: [ ^ object objectAt: selectionIndex - 2 ].
bytecodeIndex := selectionIndex - object numLiterals - 3.
^ object at: object initialPC + bytecodeIndex - 1

So…as you can see in the code, “keys add: ‘all bytecodes’.”  maps to “selectionIndex = 2 ifTrue: [^ object symbolic].“, and “keys add: ‘header’.” to “selectionIndex = 3 ifTrue: [^ object headerDescription].“.  What we should learn from this, is that CompiledMethod >> #symbolic answers a string which nicely shows the bytecodes. So for example, if we have the method:

MyClass >> testSomething
TestCase new.
self name.
Transcript show: 'The answer is:', 42.

Then, “(MyClass >> #testSomething) symbolic” answers the following:

41 <40> pushLit: TestCase
42  send: new
43 <87> pop
44 <70> self
45  send: name
46 <87> pop
47 <43> pushLit: Transcript
48 <25> pushConstant: ''The answer is:''
49 <26> pushConstant: 42
50  send: ,
51  send: show:
52 <87> pop
53 <78> returnSelf

Don’t worry for the moment about the first number in each column (for the interested guys it is the PC -> program counter) and the hexadecimal between <>  (it is the bytecode number in hexa). I will explain that in a future post.

This method #symbolic could be the same used by the SystemBrowser when you select “View” -> “Bytecodes”.  From the previous example, we can also learn that CompiledMethod implements methods like #numLiterals, #objectAt:, #initialPC, etc.  Imagine the CompiledMethod as an array of bytes…how can you determinate which part is literals and which one is bytecodes?  How the #numLiterals can be implemented in CompiledMethod if it is just an array of bytes?

CompiledMethod header

It may be already obvious that CompiledMethods have a header. But be careful, CompiledMethod have both, the normal object header every object has, and then a special header which is just the first word (32 bits -> 4 bytes) of the byte array. So this header is just before the literals and the bytecodes. As we can read in the class comment of CompiledMethod:

“The header is a 30-bit integer with the following format:

(index 0)    9 bits:    main part of primitive number   (#primitive)
(index 9)    8 bits:    number of literals (#numLiterals)
(index 17)    1 bit:    whether a large frame size is needed (#frameSize)
(index 18)    6 bits:    number of temporary variables (#numTemps)
(index 24)    4 bits:    number of arguments to the method (#numArgs)
(index 28)    1 bit:    high-bit of primitive number (#primitive)
(index 29)    1 bit:    flag bit, ignored by the VM  (#flag)”

Ok, with this comment you may notice the limits imposed in methods. For example, 9 bits for a primitive it means (2^9) -1=511. BTW, I think this class comment is outdated and now there are 11 bits for primitive index, so it is (2^11) – 1 = 2 047. But you get the idea…. anyway, it is not likely that you have ever reached any of these limits.

Who is responsable of generating such header in the CompiledMethod?  In this post, I told you that usually the input for the Compiler was a string representing the source code and the result was a CompiledMethod instance. Hence, the Compiler takes care about creating such CompiledMethod header. Notice that this header is not only used from the image side but also from the VM. Check (in the VMMaker) implementors and senders of #argumentCountOf:, #literal:ofMethod:, #primitiveIndexOf:, #tempCountOf:, etc.

CompiledMethod trailer

Something you should be asking yourself is where the source code is stored?  I mean, when you open a browser and see the source code of a method, where does it come from?  because in the CompiledMethod we saw that only literals and bytecodes are stored, not source code. So???  Ok… the source code is stored in two files: .sources and .changes. The “old” methods’ source code is in the .sources file and the “new” method’s source code in the .changes. You can browse #condenseChanges and #condenseSources for details. So far so good. But…. how a CompiledMethod instance is map to its source code in the file?  Excellent question Mariano 🙂

The same way there is a special header for CompiledMethod, there is a trailer. So far the trailer has been used only for getting the source code of the method. Some time ago, this trailer was one word size (4 bytes) and it encoded a number which was the offset in the .sources/.changes file. That number represent both things: the offset in the file, and a flag to say from which file (if .changes or .sources). Check for example the method #filePositionFromSourcePointer:. In addition, the logic of encoding and decoding the trailer was implemented in the CompiledMethod class.

In today’s Pharo images (and Squeak), this is not true anymore. There are two big differences with the “old” approach:

  1. The trailer was reified with the class CompiledMethodTrailer.
  2. There are different kind of trailers implemented and up to 255 possibilities. The implemented kinds are: normal source pointer, temp names (the decompiler can use such temp names when getting the source so that to generate a source code more similar to the original one), variable length (for example when .changes is bigger than 32MB), etc. For more details, check #trailerKinds. Of course, the most common type is “SourcePointer”.

CompiledMethod is a chunk of bytes (this is why it is a subclass from ByteArray), and its format is “bytes”, so it means it cannot define normal instance variables.  So how can it have a CompiledMethodTrailer?  Ok, it works this way: when a CompiledMethod is being created (usually by the Compiler), a specific CompiledMethodTrailer instance is also created. That instance of CompiledMethodTrailer has to be created with a specific type (source pointer, temp names, etc). Once the CompiledMethod is almost ready the trailer instance is encoded as bytes in the CompiledMethod instance, and then it is garbage collected. Later on, when someone ask to the CompiledMethod for its source code (using the method #getSource), it delegates to a trailer instance. But there is not trailer instance as this moment. So….every time the source code is needed, the CompiledMethod creates an instance of a trailer. But notice that it is up to the CompiledMethodTrailer to know how many bytes are the trailer, how to decode it and what do the bytes represent (if a source pointer, an array of temp names, etc). Finally, the trailer answers the source code of the method. So, the CompiledMethod just has:

CompiledMethod >> trailer
"Answer the receiver's trailer"
^ CompiledMethodTrailer new method: self

The CompiledMethodTrailer just read the last byte, it checks in an internal table to see which kind of trailer is it, and then perform the correct method to decode the information. The amount of bytes used by the trailer and what they represent, depends on the kind of trailer.

method: aMethod

| flagByte |

data := size := nil.
method := aMethod.
flagByte := method at: (method size).

"trailer kind encoded in 6 high bits of last byte"
kind := self class trailerKinds at: 1+(flagByte>>2).

"decode the trailer bytes"
self perform: ('decode' , kind) asSymbol.

"after decoding the trailer, size must be set"
[size notNil] assert.

Depending on the type of trailer,  CompiledMethodTrailer will finally execute one of the methods encode* when the CompiledMethod is being created, and decode* when asking its source code.

A question to all of you….wouldn’t it make sense to rename CompiledMethodTrailer to MethodSource ? because trailers has been always use only for that….

Decompiling CompiledMethods

Why source code is not stored in CompiledMethod? From my point of view, there are 2 main reasons:

  1. Because as its class name suggests, they reify COMPILED methods, not source methods or whatever name you want to use.
  2. Memory and security reasons. When you deploy an application written in C, do you include source code? no. And in Java? no. So why we would do it in Smalltalk? Remember that the way to “deploy” a Smalltalk application is providing an .image.

The ideal approach would be to have the sources in development and to be able to remove them when deploying. Smalltalk allows us that. Just remove the .sources file and that’s all 🙂 Your image continues to work as if nothing has happened. But sometimes we have a bug in our application and we want to be able to browse the code. Guess what? Smalltalk provides that also 😉  Let’s try it (don’t try in Pharo1.3 because there is a bug. Use anyone before 1.3). Create a method anywhere, for example:

testSomething: aaa with: bbb and: ccc
| name |
TestCase new.
(4 = 3)
ifTrue: ["I am a nice comment, don't remove meeee pleaeee!"]
ifFalse: ["I like this way of formatting my code"].

name := self name.
Transcript show: 'The answer is:', 42.

Now, close your image. Rename the .changes file (creating a new method will ensure that the source pointer points to the .changes and not to .sources) so that it is not found. Open your image again, and you may have the popup saying that the .changes couldn’t be find. No problem. Accept it.

Now, if you open the system browser, you can browse any method of the image. And only whose source were in the .changes will look similar to this:

testSomething: t1 with: t2 and: t3
| t4 |
TestCase new.
4 = 3.
t4 := self name.
Transcript show: 'The answer is:' , 42

What you are seeing is not the source code of the method but instead the decompiled one. The compiler is able to decompile a CompiledMethod (using the bytecodes and literals) and get the possible “source code”. However, the decompiler source is not exactly the same as the original source. Note that the decompiler the only thing it has for a method is the bytecodes and the literals. Hence, the decompiled code does not have:

  • Temporal variable and parameters  names. Since they are not stored in the CompiledMethod they are lost. Both temps and parameters are replaced in the decompiled code with “t1”, “t2”, etc.
  • Comments are lost (they are not stored in the CompiledMethod).
  • Code formatting (tabs and spaces) is lost.

The cool thing is that even with the decompiled code we can get an idea of the code, debug it, and probably find the bug we were looking for.

Notice that the source code of “old” methods are stored not in the .changes but in the .sources. So, even removing .changes there are methods which get the source from the .sources file. Therefore, we can also remove the .sources and that way all methods in the image will be decompiled if you try to browse them.

Depending of what and where you are deploying, getting rid of .sources and .changes could be worth it.

CompiledMethod equality

What do you expect the following expression to answer:

(Boolean>>#&) = (Boolean>>#|)

Ok…you need to see the source code?

& aBoolean
"Evaluating conjunction. Evaluate the argument. Then answer true if
both the receiver and the argument are true."

self subclassResponsibility
| aBoolean
"Evaluating disjunction (OR). Evaluate the argument. Then answer true
if either the receiver or the argument is true."

self subclassResponsibility

So? true or false? TRUEEEE!!! that is true. And why? if they have different comments, they have different selectors! So? who cares about that? we are talking about COMPILED methods. Are the bytecodes the same? yes. Are the literals the same? yes.  So they are the same compiled method. Point. So….you would really be careful when putting CompiledMethods in Sets, Dictionaries or things like that. Example:

InstructionClient methods size -> 27
InstructionClient methods asSet size -> 21

Conclusion: use an IdentitySet or a IdentiyDictionary if you want to avoid problems.

Sorry for the long post, but there is too much to talk about CompiledMethods. In the next post we will talk a little more about bytecodes.


Smalltalk reflective model

Hi. I am sure the title of this post is horrible, but I didn’t find anything better. The idea is simple: in this part of the journey, we will talk about bytecodes, primitives, CompiledMethods, FFI, plugins, etc… But before going there, I would like to write some bits about what happens first in the image side. These may be topics everybody know, so in that case, just skip the post and wait for the next one 😉  My intention is that anyway can follow my posts.

A really quick intro to Smalltalk reflective model

The reflective model of Smalltalk is easy and elegant. As we can read in Pharo by Example, there are two important rules:  1) Everything is an object; 2) Every object is instance of a class. Since classes are objects and every object is an instance of a class, it follows that classes must also be instances of classes. A class whose instances are classes is called a metaclass. Whenever you create a class, the system automatically creates a metaclass. The metaclass defines the structure and behavior of the class that is its instance. The following picture shows a minimized reflective model of Smalltalk. Notice that for clarification purposes this diagram shows only a part of it.

A class contains a name, a format, a method dictionary, its superclass, a list of instance variables, etc. The method dictionary is a map where keys are the methods names (called selectors in Smalltalk) and the values are the compiled methods which are instances of CompiledMethod.

When an object receives a message, the Virtual Machine has to do first what it is commonly called as the Method Lookup. This consist of searching the message through the hierarchy chain of the receiver’s class. For each class in the chain, it checks whether the selector is included or not in the MethodDictionary.  If it is not, it continues searching forward in the chain until it finds a method or sends the #doesNotUnderstand: message in case it was not found in the whole hierarchy. When a method is found, it is directly executed.

To understand these topics, I really recommend the two wonderful chapters in Pharo By Example book: Chapter 13 “Classes and Metaclasses” and Chapter 14 “Reflection”. They are both a “must read” if you are more or less new with these topics.

In the internal representation of the Virtual Machine, objects are a chuck of memory. They have an object header which (there will be a whole post about it) can be between one and three words, and following the object header, there are slots (normally of 32 or 64 bytes) that are memory addresses which usually (we will see why I didn’t say always) represent the instance variables. The object header contains bits for the Garbage Collector usage, the hash, the format, a pointer to its class, etc.

Classes and Metaclasses

How do you create a class in Smalltalk? In other languages, you normally create a new text file that after you compile. But in Smalltalk, as we are used to, everything happens by a message send. So, to create a new class you tell to the superclass, “Can you create this subclass with this name, these instance variables and this category please?”. So, when you take a browser and you do a “Ctrl + s” of this code:

Object subclass: #MyClass
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'MyCategory'

The only thing you do, is to send the message #subclass:instanceVariableNames:classVariableNames:poolDictionaries:category: to Object. If fact, you can take that piece of code, evaluate it in a Workspace, and you will get the same results 🙂

You can see implementors and you will logically find one in Class. Which should be the result of such message sent?  two things: a new class and a new metaclass. Do the following test:

Metaclass instanceCount ->  3710
Class allSubclasses size -> 3710

Now, create a new class, and inspect again:

Metaclass instanceCount ->  3711
Class allSubclasses size -> 3711

The problem with Metaclasses is that they are implicit, so they are very difficult to understand. Imagine that you create a class User, then its class is “User class”. The unique instance of “User class” is “User”. And at the same time, “User class” is an instance of Metaclass. So….complicated, but if you want to understand them, take a look to the chapters I told you.  How it is done?  it is not really important for the purpose of this post, but it uses the ClassBuilder and also the Compiler (check senders of #compilerClass).

Creating a method

We saw what happens when we create a class. And when you save a method from the browser? what happens ? In a nutshell what happens is that the Smalltalk Compiler does its magic, that is, it receives as an input a string that represents the source code, and as a result you get a CompiledMethod instance. A CompiledMethod contains all the instructions (bytecodes) and information (literals) that the VM needs to interpret and execute such method.

Let’s see it by ourself. Take your image, create a dumy class and then put a breakpoint at the beginning of Behavior >> #compile:classified:notifying:trailer:ifFail:. Now, type the following method and accept it:

testCompiler
Transcript show: 'all this code will be compiled'.

Once you accept such code, the debugger should appear. You can analyze the stacktrace if you want. Notice the arguments that the methods has: compile: code classified: category notifying: requestor trailer: bytes ifFail: failBlock.  So, I told you that the basic idea was to send a piece of code as text and get the CompiledMethod instance. The parameter “code” should be the code of the method we type, and yes, it is a ByteString. If you go step by step with the debugger, and inspect the result, that is, “CompiledMethodWithNode generateMethodFromNode: methodNode trailer: bytes.”  you will see it answers the CompiledMethodWithNode instance to which you can ask “method” and it is the CompiledMethod instnace.  Of course, that method should be the same you get after when doing “MyClass methodDict at: #testCompiler”.

The rest of the parameters are the category in which the method should be, the requestor (someone to notify about this event), the trailer bytes (we will see this later on), and a block to execute if there is an error.

CompiledMethods

In Smalltalk compiled methods are first-class objects (classes too!), in this case instances of CompiledMethod class. However, the class CompiledMethod is quite special and a little differet from the rest. But we will see this later on….What it is important for the moment, is to know that a CompiledMethod contains a list of bytecodes and a list of  literals. Bytecodes are instructions. A method is decomposed in a set of bytecodes, which are grouped in five categories: pushes, stores, sends, returns, and jumps. Literals are all those objects and selectors that are needed by the bytecodes but they are not instance variables of the receiver, hence they need to be stored somewhere.

For example, with our previous example of #testCompiler, we will have a bytecode (among others) for sending the message #show:  and we will have the ‘Transcript’ and the selector name ‘show:’ in the literals. As an exersise, inspect the CompiledMethod instance. You can just evaluate: “(MyClass >> #testCompiler) inspect”. But….”exploring” is usually better that “inspect” for compiled methods…I let you see the differences 🙂  Anyway, you will see something like this:

In the next post we will play a bit deeper with CompiledMethods so don’t worry.

The Compiler

My knowledge of the Compiler is quite limited, but is is important to notice that the Compiler does much more things than the one I have said. In a compiler, there are usually several steps like parse the code, validate it, get an intermediate representation, and finally create the CompiledMethod instance. The compiler needs to know how to translate our Smalltalk code to bytecodes understood by the VM.

In Squeak and Pharo, the compiler is mostly implemented in the class Compiler. It seems it is quite difficult to understand and it has some limitations and difficulties to get intermediate representation of the code. Because of that and probably much other reasons, the community started to work in a new compiler called Opal (which at the beginning was called NewCompiler).

Links

  • Blue book: When talking about the VM and Smalltalk in general, the bible is the book “Smalltalk-80: The Language and Its Implementation”. You can find it in pdf in Stéphane Ducasse free books page, and directly in html (actually, only the chapters 26-30) in Eliot Miranda webpage. Those chapters are the part of the “Implementation” so everything that is related to the VM is there.
  • Regarding Compiler, CompiledMethod, etc, you can read in the blue book this and this. About bytecodes, an intro here and in details here.
  • Pharo By Example book: Chapter 13 “Classes and Metaclasses” and Chapter 14 “Reflection”.
  • A Tour of the Squeak Object Engine” gives an excellent overview of the VM, including a description about CompiledMethod, bytecodes and friends.
  • Opal Compiler.