ANALYSIS-2026-11-inlining.md 73 KB

Amber Smalltalk — the inliner (November 2026)

What the inliner is and how it is designed. What it folds and what it leaves. What a new inlined form costs, and what could change. Read in full: lang/src/Compiler-Inlining.st, the aliasing in Compiler-IR.st, the scope rules in Compiler-Semantic.st, and Kernel-Dag.st. Read too: the 28 commits to Compiler-Inlining.st since its move into lang/src in 2018. And the issues #1242, #1244 and #1260 on lolg.it. Every number below was measured on this machine (Node 24.18.0) with throwaway scripts. The appendix says how.

The text describes the tree of 2 November 2026, at 919ffc7d. ANALYSIS-2026-10-compiler.md is the general analysis of the compiler suite. Its §2.4 describes the aliasing and its §2.5 the inliner. Its §5.3 measures the cost of loops. Its §7 item 4 proposes to inline the loop selectors. This document goes one level down and repeats none of it.

The maintainer put a hypothesis to this document. The tagging stage marks the inlinable sends before translation. The inliner replaces them three stages later. Every inlined form is a class of its own. The maintainer suspects that this makes the design rigid. The core that the October analysis praised may be at its limits. This document tests the hypothesis on the code, on the image, and with spikes. The maintainer then asked whether most forms could be derived in Smalltalk, from a few primitives. §3.5 tries that on the image.

0. Summary

  • The inliner folds every shape the task names, and it does so through statements. 397 of the 403 sends of its ten selectors in the image are inlined. A send that is the receiver or an argument of another send is hoisted into an alias variable. The hoisting assignment becomes the if. (x and: [ y ]) ifTrue: [ 1 ] ifFalse: [ 2 ] is two ifs and a $1. One inlined send never enables another. The inliner never looks at the receiver of a send it inlines. An inlinable receiver has already become a variable, so nothing is lost there (§2.1, §3.2).
  • Two latent defects. Two inlined blocks of one method that declare the same name share one JavaScript variable. A block that captures it can see the other block's value. And an inlinable send inside a block of an inlined send's receiver stays a send, because nothing visits that receiver. No method in amber or in its eight sibling checkouts has either shape. Each fix is one or two methods, and the suite stays green under both (§2.4, §3.4).
  • The alias variables are the inliner's visible cost, and most of them come from one rule. The image has 384 aliases in 283 methods. 157 of them come from the rule that the receiver of an ifNil: is read twice. 81 of those are needless, because a temp, a slot or a global can be read twice. One method of the tagger removes them; the spike went from 384 to 303. The sends in operand position cost 24 more. Evaluation order alone costs 203 (§2.3, §3.3).
  • Loops: a new form fits the pipeline and does not fit the inliner. A spike inlined whileTrue:, whileFalse:, timesRepeat: and to:do: with 30 methods and four node classes. The plain generator, as the oracle, agrees on 26 of 27 cases. The transformer list, the IR base and the aliasing were not touched. Three parts of the inliner had to be written around: its shape test, its block template and its value wrapping. Two facts came out of the oracle. Inside a loop, an inlined block's var is wrong for every temp that a block captures. That is the first defect, made general. In Amber, whileTrue: answers its receiver block, not nil (§3.1).
  • Measured: 2.4× on a whileTrue: loop, 10× on to:do: and timesRepeat:. The image itself has 20 loop sends with literal blocks against 196 iteration sends over collections. The gain is for user code, not for the image (§2.3, §3.1).
  • Eight of the ten forms can be kernel methods. The maintainer proposed a pragma, <inline>. The body of such a method would be the expansion of every send of its selector with literal blocks. Boolean already writes five of its methods that way, over ifTrue:ifFalse:. A spike expanded them, and three new bodies for the nil family, into two primitives. The suite stayed green but for one test of navigation. and:, or: and the two swapped forms emit the same code as today. The one-armed forms change the code of 174 methods, and the tools see the expansion (§3.5).
  • The rigidity is in the inliner's templates and in its split from the tagger. It is not in the classes, the IR or the list. A node class costs two methods. The IR took four more classes without a change anywhere else. Every new form fights the same four things. inlineClosure: says that an argument is the receiver. inlinedClosure:wrapFinalValueIn: says that a value is the last statement of a branch. shouldInline: says that every argument is a block. The tagger predicts the inliner on another tree, and it over-approximates. Derived inlines would leave the rigidity with the primitives alone (§3.5, §4.1).
  • "The core is at its limits" holds for the inliner and for nothing else. The transformer list absorbed every spike without a change. The IR is the right size for an emitter, and it welcomes nodes. The inliner is a conditional inliner. Every form that is not a conditional is a special case in it (§4.3).
  • Recommended, in order (§5). The two defects: a visit of the receiver, and let for inlined temps after one decision. The receiver rule: one method and a Recompile.. The dead code and the stale comments. A rewriting pass on the Redux variant, as the home of simplifications. Derived inlines, after two decisions. The loop selectors, after three more decisions. Derived inlines would turn two of those into kernel text. and: and or: as expressions, a small gain of 13 aliases. Not recommended: inlining the primitives on the AST, or at emission.

1. What the inliner is

1.1 The parts

Compiler-Inlining.st is 770 lines: 19 classes, one trait, 79 methods and two extension methods.

part stage what it does
ASTPreInliner, 1 method 3000-inlinerTagging marks a send with one of the ten selectors as shouldBeAliased, and the receiver of the four ifNil: selectors too
IRInliner, 12 methods 6000-inliner an IRVisitor; visitIRSend:, visitIRAssignment:, visitIRReturn: and visitIRNonLocalReturn: ask a shouldInline… test and hand the node to an inliner; flattens non-local returns
IRSendInliner, 24 methods and 3 class methods the ten selectors as methods, reached by perform:; the block template inlineClosure:; the builders inlinedSend:withBlock: and inlinedSend:withBlock:withBlock:; shouldInline: and the two selector lists
IRWrappingSendInliner, 5, with IRAssignmentInliner, IRReturnInliner, IRNonLocalReturnInliner, 4, 2 and 2 the same for a send whose value is assigned or returned: the last value of each branch is wrapped in the assignment or the return, and a one-armed form gets its other arm
IRInlinedSend with six subclasses, IRInlinedClosure, IRInlinedSequence the inlined IR: one class per form, each with acceptDagVisitor: and isInlined
IRInliningJSTranslator, 7 8000-irToJs one visitIRInlined…: per form, writing if through JSStream >> nextPutIf:then:else:
TIRInlinedVisitor lets the inliner and the translator visit an inlined closure and sequence as plain ones
InliningCodeGenerator, 4 puts the two stages into the transformer dictionary

The October analysis measured the two stages at 5 % and 9 % of the pipeline's time, in its §5.1.

1.2 One send through the pipeline

The method foo: x y: y ^ (x and: [ y ]) ifTrue: [ 1 ] ifFalse: [ 2 ] goes through four stages. The tagger marks both sends. The and: is the receiver of the ifTrue:ifFalse:. So IRASTTranslator >> aliasTemporally: finds a marked child and hoists it into $1. The IR after 5000-astToIr reads:

IRMethod
  IRSequence
    IRAssignment
      IRVariable $1 (AliasVar)
      IRSend and:
        IRVariable x (ArgVar)
        IRClosure args=[] scope:real
          IRBlockSequence
            IRBlockReturn
              IRVariable y (ArgVar)
    IRReturn
      IRSend ifTrue:ifFalse:
        IRVariable $1 (AliasVar)
        IRClosure args=[] scope:real
          IRBlockSequence
            IRBlockReturn
              IRValue 1
        IRClosure args=[] scope:real
          IRBlockSequence
            IRBlockReturn
              IRValue 2

The inliner meets the assignment first. Its right side is an and: with a literal block, so IRAssignmentInliner takes it. The and: method of the inliner rewrites the send as an ifTrue:ifFalse: with a synthesised false branch. Each branch is flattened into an IRInlinedClosure. The assignment to $1 is pushed to the end of each. The return goes to IRReturnInliner the same way. The IR after 6000-inliner reads:

IRMethod
  IRSequence
    IRInlinedIfTrueIfFalse
      IRVariable x (ArgVar)
      IRInlinedClosure args=[] scope:inlined
        IRInlinedSequence
          IRAssignment
            IRVariable $1 (AliasVar)
            IRVariable y (ArgVar)
      IRInlinedClosure args=[] scope:inlined
        IRInlinedSequence
          IRAssignment
            IRVariable $1 (AliasVar)
            IRValue false
    IRInlinedIfTrueIfFalse
      IRVariable $1 (AliasVar)
      IRInlinedClosure args=[] scope:inlined
        IRInlinedSequence
          IRReturn
            IRValue 1
      IRInlinedClosure args=[] scope:inlined
        IRInlinedSequence
          IRReturn
            IRValue 2

The translator writes one if per node:

function (x,y){
var self=this,$self=this;
var $1;
if($core.assert(x)){
$1=y;
} else {
$1=false;
}
if($core.assert($1)){
return (1);
} else {
return (2);
}
}

Three parts decided this outcome. The tagger decided that the and: would be hoisted. The aliasing decided where the hoist goes and gave it $1. The wrapping inliners decided how the value reaches $1 and the return. The node classes decided nothing. They carry the decision to the emitter.

1.3 The tagger's three rules, and who reads them

The tagger is one method, ASTPreInliner >> visitSendNode:. It encodes three rules.

  1. A send with one of the ten selectors is marked shouldBeAliased. One method reads the mark: aliasTemporally:. It runs over the children of a send, a brace array or a brace dictionary. A marked child is hoisted into an alias. Every child to its left is hoisted too, so that evaluation order holds. A send that is a statement, a return, an assignment or a block's value has no reader for its mark. The inliner meets such a send where it stands.
  2. The receiver of the four ifNil: selectors is marked too, because the emitter writes it twice: x == null || x.a$nil. The hoist asks isIdempotent. A literal, an argument and a pseudo-variable answer yes. A temp, a slot, a global and a send answer no, and get a $n. The first three of those need none, as §3.3 says.
  3. The tagger marks by selector alone. IRSendInliner class >> shouldInline: later checks that every argument is a literal block and that the receiver is not super. A send with its block in a variable is marked, hoisted and then not inlined (§2.2).

The tagger and the inliner are two predicates on two trees. The tagger must say yes to everything the inliner will take, and it may say yes to more. Today it says yes to more.

1.4 The templates

Four methods do the work for all ten selectors.

inlineClosure: turns an IRClosure into an IRInlinedClosure. It copies the temp declarations. It turns each block argument into a temp assigned from the send's receiver; this is how ifNotNil: [ :v | … ] gets its v. It copies the statements. It unwraps the last statement's implicit return through asInlinedBlockResult. The argument is the receiver. No other binding exists.

inlinedSend:withBlock: and its two-block sibling build the node: the receiver as the first child, the inlined closures after it. They replace the send in its parent through IRVisitor >> replace:with:. That method replaces in the node before the last on the visitor's path. The receiver is added as it is. The inliner never visits it. §2.4 shows what that leaves behind.

inlinedClosure:wrapFinalValueIn:, on IRWrappingSendInliner, is what makes a value out of a statement. An if is a statement in JavaScript, and a statement has no value. So when the send's value is assigned or returned, the wrapping inliner pushes that assignment or return into each branch. It wraps the branch's last value. An empty branch gets nil first (#1242). The one-armed forms get their other arm here. ifTrue: becomes an ifTrue:ifFalse: with an empty branch. ifNil: becomes an ifNil:ifNotNil: whose other branch is the receiver itself (#1260). The receiver instruction then sits twice in the tree, as a condition and as a value. The IR is a DAG, and this is where it shows.

IRInliner >> visitIRNonLocalReturn: flattens a ^ inside an inlined block to a plain return when every scope up to the method is inlined. The test is on the scope, not on the tree. inlineClosure: points the block's LexicalScope at the new IRInlinedClosure. LexicalScope >> isInlined asks that instruction. The inliner also removes the return from the method scope's list, so the method gets no try. A semantic-analysis object is rewritten by stage 6000. That is the one place where the inliner is not a function of the IR.

1.5 History

Nicolas Petton wrote the inliner in 2012 with the architecture, for conditionals only. The 28 commits since the 2018 move are the maintainer's. Four of them are the inliner's decisions.

when commit what why
2019-10-08 ef1f6f18, 1693b5d5 IRNonLocalReturnInliner; an empty inlined block answers nil #1244: [ ^ true ifTrue: [1] ifFalse: [2] ] value was a JavaScript syntax error; #1242: x := true ifTrue: [] left x unchanged
2020-03-07 9e68ecec $receiver removed the emitter had written ($receiver = x) == null \|\| $receiver.a$nil, one variable per method; the message says "inlined send receivers are aliased anyway"
2020-04-05 4d1656fb the receiver rule restricted to the ifNil: family "ifTrue:ifFalse: family does not" need it
2020-04-30 96470467 and: and or: inlined as ifTrue:ifFalse: with a synthesised branch
2021-07-18 f4a253cc, f8d3f39c IRWrappingSendInliner; ifNil: without a value #1260
2026-10-23 84dc04f9 the inliner replaces through the visitor nodes have no parent since 0.32.0

The thread of #1260 is the record of the design meeting its limit. The report was that a := true ifFalse: [3] left a at 1. On 2021-07-10 the maintainer wrote that the fix "needs bigger change in compiler (essentially, making everything into ifTrue:ifFalse: and the optimizing out the branches that actually do nothing)". On 2021-07-18 the maintainer wrote that there was a "more direct (though not as perfect) solution for exactly this problem". The wrapping inliner was committed the same day. The rewrite pass that the first comment describes does not exist. §3.5 tries the first half of that comment in Smalltalk, and §5 item 4 returns to the second.

The internalVariables hook on IRInlinedSend and the visitInlinedSend: dispatch of its acceptDagVisitor: are left from $receiver. The hook answers an empty collection in every subclass. Nothing implements visitInlinedSend:.

2. What comes out

2.1 The shapes

Every shape below was compiled through the default InliningCodeGenerator and through CodeGenerator, on DoIt. x, y and z are method arguments. The emitted code is shown with its //>>excludeStart("ctx") sections removed. The last column names the part of the mechanism that decided the outcome.

shape source outcome decided by
statement x ifTrue: [ self bar ] if($core.assert(x)){ $self._bar(); } IRInliner >> visitIRSend:, the plain IRSendInliner
return ^ x ifTrue: [ 1 ] ifFalse: [ 2 ] if(…){ return (1); } else { return (2); } IRReturnInliner
assignment a := x ifTrue: [ 1 ] if(…){ a=(1); } else { a=nil; } IRAssignmentInliner; the else is the other arm from #1260
inlinable send as receiver (x and: [ y ]) ifTrue: [ … ] if(…){ $1=y; } else { $1=false; } if($core.assert($1)){ … } the tagger's mark, aliasTemporally:, then IRAssignmentInliner for $1
ifNil: as receiver (x ifNil: [ 1 ]) ifTrue: [ … ] if(x == null \|\| x.a$nil){ $1=(1); } else { $1=x; } if($core.assert($1)){ … } the same; x is an argument, so no second alias
as an argument self bar: (x ifTrue: [ 1 ] ifFalse: [ 2 ]) if(…){ $1=(1); } else { $1=(2); } return $self._bar_($1); the same
as an argument after a temp t := 3. ^ self bar: t baz: (x ifTrue: [ 1 ] ifFalse: [ 2 ]) $1=t; if(…){ $2=(1); } else { $2=(2); } return $self._bar_baz_($1,$2); aliasTemporally: hoists t too, because the branch could assign it
in a brace array ^ { x ifTrue: [ 1 ] ifFalse: [ 2 ]. 3 } if(…){ $1=(1); } else { $1=(2); } return [$1,(3)]; the same
last message of a cascade ^ x foo; ifTrue: [ 1 ] ifFalse: [ 2 ] $recv(x)._foo(); if(…){ return (1); } else { return (2); } visitCascadeNode: emits the earlier messages as statements; the last is a return
middle message of a cascade ^ x ifTrue: [ 1 ]; bar if(…){ (1); } return $recv(x)._bar(); the plain IRSendInliner; the value is dropped
cascade on an inlined receiver ^ (x ifTrue: [ 1 ] ifFalse: [ 2 ]) foo; bar; yourself if(…){ $1=(1); } else { $1=(2); } $recv($1)._foo(); … visitCascadeNode: aliases a receiver that is not idempotent, then IRAssignmentInliner
inlined receiver is a cascade ^ (x foo; bar) ifTrue: [ 1 ] ifFalse: [ 2 ] $recv(x)._foo(); if($core.assert($recv(x)._bar())){ … } hasOpeningStatements; nothing is left of the cascade, so no alias
branch value is an inlined send, assigned a := x ifTrue: [ y ifTrue: [ 1 ] ifFalse: [ 2 ] ] ifFalse: [ 3 ] if(…){ if(…){ a=(1); } else { a=(2); } } else { a=(3); } the outer wrapper wraps the inner send in a :=, and the inner assignment goes to IRAssignmentInliner again
branch value is an ifNil:, returned ^ x ifTrue: [ y ifNil: [ 1 ] ] ifFalse: [ 2 ] if(…){ if(y == null \|\| y.a$nil){ return (1); } else { return y; } } else { return (2); } the same, with IRReturnInliner
nested statements x ifTrue: [ y ifTrue: [ z ifTrue: [ self bar ] ] ] three nested ifs the plain IRSendInliner, recursively through visit: of the inlined closure
else-if ladder ^ x ifTrue: [ 1 ] ifFalse: [ y ifTrue: [ 2 ] ifFalse: [ 3 ] ] if(…){ return (1); } else { if(…){ return (2); } else { return (3); } } the same; the emitter has no else if
ifNil: on a send ^ self bar ifNil: [ 1 ] $1=$self._bar(); if($1 == null \|\| $1.a$nil){ return (1); } else { return $1; } the receiver rule, through alias:
ifNotNil: on a temp t := self bar. ^ t ifNotNil: [ :v \| v + 1 ] $1=t; if($1 == null \|\| $1.a$nil){ return $1; } else { var v; v=$1; return $recv(v).__plus((1)); } the receiver rule; TempVar is not idempotent
ifNotNil: on an argument foo: t ^ t ifNotNil: [ :v \| v + 1 ] if(t == null \|\| t.a$nil){ return t; } else { var v; v=t; … } ArgVar is idempotent, so alias: passes it through
ifNil: on a global ^ Smalltalk ifNil: [ 1 ] $1=$globals.Smalltalk; if($1 == null \|\| … the receiver rule; ClassRefVar is not idempotent
non-local return in a nested inline x ifTrue: [ y ifTrue: [ ^ 1 ] ]. ^ 2 if(…){ if(…){ return (1); } } return (2);, no try canFlattenNonLocalReturns up the inlined scopes; removeNonLocalReturn:
non-local return in an inline inside a real block self bar do: [ :e \| e ifTrue: [ ^ e ] ] … (function(e){ if(…){ throw $nlr=…; } else { return nil; } }) inside try the real block's scope stops the flattening
#1244 [ ^ x ifTrue: [ 1 ] ifFalse: [ 2 ] ] value (function(){ if(…){ throw $nlr=…(1); } else { throw $nlr=…(2); } }) IRNonLocalReturnInliner
value of a real block ^ [ x ifTrue: [ 1 ] ifFalse: [ 2 ] ] value (function(){ if(…){ return (1); } else { return (2); } }) IRBlockReturn goes to IRReturnInliner
block with temps ^ x ifTrue: [ \| t \| t := 1. t + 1 ] ifFalse: [ 2 ] if(…){ var t; t=(1); return …; } else { return (2); } inlineClosure: copies the temp declarations; the emitter writes var inside the branch
empty block a := x ifTrue: [] if(…){ a=nil; } else { a=nil; } wrapFinalValueIn:, #1242
and: as a statement (x and: [ y ]). ^ 1 if($core.assert(x)){ y; } else { false; } the synthesised branch of and:, emitted although nothing uses it

Every shape above is inlined. In none of them does the inliner give up. The shapes differ only in where the value goes: a return, an assignment, or a $n.

Two things the table shows deserve a sentence each. The $n is not a cost of nesting. Nested branches, wrapped values and cascades produce none. It is the cost of a position: an operand. A receiver is folded into its sender's condition only when it is not inlinable. (x foo; bar) ifTrue: puts $recv(x)._bar() into the if. (x and: [ y ]) ifTrue: puts $1 there.

2.2 Where the inliner gives up, and what else it does

shape source outcome decided by
block in a variable foo: x block: aBlock ^ x ifTrue: aBlock return $recv(x)._ifTrue_(aBlock); shouldInline:
the same as an operand ^ self bar: (x ifTrue: aBlock) $1=$recv(x)._ifTrue_(aBlock); return $self._bar_($1); the tagger marked it, the aliasing hoisted it, shouldInline: refused it; the $1 is for nothing
one literal block, one variable ^ x ifTrue: [ 1 ] ifFalse: aBlock a send with one closure shouldInline:, allSatisfy:
and: with a non-block argument ^ x and: y return $recv(x)._and_(y); shouldInline:
super receiver ^ super ifTrue: [ 1 ] a super send shouldInline:
a block in the receiver ^ (c anySatisfy: [ :e \| e > 2 or: [ e < 0 ] ]) ifTrue: [ 1 ] ifFalse: [ 2 ] the or: in the block is a send with a closure inlinedSend:withBlock: never visits the receiver (§2.4)
wrong arity ^ x ifTrue: [ :a \| a ] InliningError: Inlined block should have zero argument, at compile time mustBeNiladicClosure:
loops [ i < 3 ] whileTrue: [ i := i + 1 ] $recv((function(){ … }))._whileTrue_((function(){ … })) the selector list
loop with an inlined body [ i < 3 ] whileTrue: [ i odd ifTrue: [ … ] ifFalse: [ … ] ] the loop is a send, the ifTrue:ifFalse: inside its closure is an if IRInliner descends into real closures

The wrong-arity case is a divergence between the two generators. CodeGenerator compiles ^ x ifTrue: [ :a | a ]. With x true the method answers nil, because the block runs with a unbound. InliningCodeGenerator refuses the method. The October analysis §3.2 records the other divergence of this kind, NonBooleanReceiver against MessageNotUnderstood. Both come from the same place. The inliner speculates on the receiver's class, and it reports its own error when the speculation fails.

2.3 The image

The census ran at 919ffc7d over 2,404 methods. They are the methods with source in the lang image and Platform-Node, on both sides of each class and trait. The October analysis counted 2,217 methods at 9ef24753 and found 282 with aliases. This census finds

  1. The two bases agree on what matters.

The ten selectors. 403 sends:

selector sends selector sends
ifNil: 87 ifFalse: 42
ifTrue: 67 ifNil:ifNotNil: 31
ifTrue:ifFalse: 58 or: 17
ifNotNil: 46 ifFalse:ifTrue: 8
and: 44 ifNotNil:ifNil: 3

397 are inlined, in 307 methods. Six are not inlined, each because a block is in a variable. Four of the six are the kernel's own definitions: Boolean >> ifTrue: and its siblings, and UndefinedObject >> ifNil:. They forward to a two-armed send. The other two are PackageHandler >> ajaxPutAt:data:onSuccess:onError: and AIContext >> lookupContextForLocal:ifNone:. No send has super as receiver. The inlined IR holds 153 IRInlinedIfTrueIfFalse, 110 IRInlinedIfNilIfNotNil, 47 IRInlinedIfTrue, 34 IRInlinedIfNotNil, 32 IRInlinedIfFalse and 21 IRInlinedIfNil. It holds 660 inlined closures.

Where the 397 stand.

position sends what happens
statement 146 an if
return 142 an if with return in each branch
value of a block 79 the same, or the outer wrapper's value
assignment 9 an if with the assignment in each branch
receiver of a send 14 hoisted into $n
argument of a send 6 hoisted into $n
element of a brace array 1 hoisted into $n
cascade 0

Ten of the 14 receivers are the receiver of another inlined send, in nine methods such as Point >> printOn: and IRASTTranslator >> aliasTemporally:. They are and: under ifTrue: 4, under ifFalse: 2, under ifTrue:ifFalse: 1, and or: under ifTrue: 2, under ifTrue:ifFalse: 1. Of the 21 sends in operand position, 18 have blocks that are one pure expression each.

The aliases, by cause. The image was translated to IR three times. The first run had the tagger as it is. The second had a tagger that marks sends only. The third had none.

tagging aliases methods with aliases
as it is 384 283
sends only, no receiver rule 227 157
none 203 142

The receiver rule costs 157 aliases in 126 methods. The send rule costs 24 in 15. Evaluation order, which is not the inliner's, costs 203 in 142. The right sides of the 384 aliases:

right side aliases
a send that is not inlinable 251
a slot 85
a temp 23
an inlinable send 21
a global 3
an external variable 1

The receivers of the four ifNil: selectors. 165 sends:

receiver sends gets a $n
a send 74 yes, and it must: a send runs once
a slot 68 yes
a temp 11 yes
an argument 9 no
a global 3 yes

The 82 on a slot, a temp or a global need none. §3.3 measures their removal at 81.

The loop selectors. 22 sends: whileFalse: 9, whileTrue: 8, timesRepeat: 3, to:do: 1, whileTrue 1. 20 have literal blocks everywhere a loop needs them, in 18 methods. 16 are statements. The other 4 are the value of a block, all four whileTrue: in Number >> to:by: and to:by:do:. Against them stand 235 sends of the collection iteration selectors, 196 with a literal block:

selector with a literal block
do: 85
collect: 37
keysAndValuesDo: 16
do:separatedBy: 15
select: 8
reject: 7

ifEmpty: and ifNotEmpty: with their two-armed forms add 61 with literal blocks, and at:ifAbsent: 21. None of those can be inlined without knowing the receiver's class.

2.4 Two defects

Probes after the census found two defects that it could not see. Both are latent. A scan found neither shape in amber or in its eight sibling checkouts. It read their 5,355 methods from the source: strings of the compiled .js, and parsed them. The scanner found both shapes in a control file first.

Sibling inlined blocks share one variable. visitIRInlinedClosure: declares the temps and arguments of an inlined block with var. JavaScript hoists a var to the function. So two inlined blocks of one method that declare the same name use one variable. Smalltalk gives each block its own. Four probes, run under both generators:

source plain inlined
a ifNotNil: [ :v \| cbs add: [ v ] ]. b ifNotNil: [ :v \| cbs add: [ v ] ], with a 1 and b 2, then each block's value (1 2) (2 2)
true ifTrue: [ \| t \| t := 1. cbs add: [ t ] ]. true ifTrue: [ \| t \| t := 2. cbs add: [ t ] ], then each block's value (1 2) (2 2)
true ifTrue: [ \| t \| t := 1 ]. true ifTrue: [ \| t \| r := t ]. ^ r nil 1
true ifTrue: [ \| t \| t := 7 ]. true ifTrue: [ \| t \| t ifNil: [ t := 0 ]. r := t ]. ^ r 0 7

The inliner emits this for the first:

if(a != null && !a.a$nil){
var v;
v=a;
[$recv(cbs)._add_((function(){
return v;

}))
][0];
}
if(b != null && !b.a$nil){
var v;
v=b;
$recv(cbs)._add_((function(){
return v;

}));
}

A program meets this when it registers event handlers from two ifNotNil: [ :each | … ]. The two branches of one send may share a name safely, because only one of them runs. The development image declares 58 names in inlined blocks, and no function declares one twice.

A block in an inlined send's receiver is never inlined. inlinedSend:withBlock: adds the receiver to the inlined node without visiting it (§1.4). An inlinable receiver loses nothing, because the aliasing has already hoisted it into a variable. The receiver of an ifNil: is hoisted too. Any other receiver stays where it is, and nothing visits a block inside it. So an inlinable send in that block stays a send. For foo: c ^ (c anySatisfy: [ :e | e > 2 or: [ e < 0 ] ]) ifTrue: [ 1 ] ifFalse: [ 2 ] the inliner emits:

if($core.assert($recv(c)._anySatisfy_((function(e){
return $recv($recv(e).__gt((2)))._or_((function(){
return $recv(e).__lt((0));
}));
})))){
return (1);
} else {
return (2);
}

Four probed shapes leave such a send. Two are an or: under ifTrue:ifFalse:, returned and assigned. One is an and: under ifTrue:, and one an ifTrue:ifFalse: under and:. The same block is inlined as an argument, in self yourself: (c anySatisfy: [ … ]). It is inlined in the receiver of an ifNil: too. The answers are right. The code is slower, and a non-Boolean raises a different error. In (c anySatisfy: [ :e | e or: [ false ] ]) ifTrue: [ 1 ] ifFalse: [ 2 ], an element 3 raises MessageNotUnderstood, as the plain generator's code does. The same or: as an argument raises NonBooleanReceiver.

3. Spikes

Each spike patched the running image from a script, through Compiler >> install:forClass:protocol:, and compiled a set of methods with both generators. The methods were installed on DoIt, run, and their answers compared as printStrings. Where the two generators disagreed before the spike, the spike inherits the disagreement. Nothing of the spikes is in the tree.

3.1 The loops

The spike inlines whileTrue:, whileFalse:, timesRepeat: and to:do: in statement position. It adds four node classes, IRInlinedWhileTrue, IRInlinedWhileFalse, IRInlinedTimesRepeat and IRInlinedToDo, and 30 methods. Seven of the methods replace existing ones.

stage part changed new
3000-inlinerTagging ASTPreInliner >> visitSendNode: marks the stop bound of to:do: 1
IRSendInliner class: inlinedSelectors, inlinedSelectorsNeedingIdempotentReceiver (the count of timesRepeat:), shouldInline:, and a new loopSelectors 3 1
5000-astToIr nothing
6000-inliner IRInliner: shouldInlineSend: asks the path whether the parent is a sequence; shouldInlineAssignment: and shouldInlineReturn: refuse loops 3
IRSendInliner: the four selectors, inlinedLoop:condition:body:, inlineLoopClosure:, mustBeUnaryClosure: 7
the IR the four classes, each with acceptDagVisitor: 4
8000-irToJs IRInliningJSTranslator: four visitIRInlined…:, visitInlinedLoop:negated:, visitLoopBody: 6
JSStream: nextPutWhile:do:, nextPutForever:, nextPutBreakUnless:, nextPutFor:while:step:do:, nextPutLets: 5

The transformer list, IRVisitor, the IR node base, IRASTTranslator and the aliasing were not touched. The aliasing served the loops as it is. The stop bound and the repeat count got a $1 through the tagger's mark. 1 to: 3 do: got none.

What comes out, for foo | s | s := 0. 1 to: 3 do: [ :i | s := s + i ]. ^ s and for a condition with two statements:

for(let i=(1);i<=(3);i++){
s=$recv(s).__plus(i);
s;
}
return s;
for(;;){
i=$recv(i).__plus((1));
if(!($core.assert($recv(i).__lt((3))))) break;
$self._yourself();
}

A one-statement condition becomes while($core.assert(…)). A non-local return at method level is a return inside the loop, and the method has no try. Inside a real block it is the throw, as for the conditionals.

The oracle. 27 methods:

  • the four loops, a two-statement condition, and a condition with a temp;
  • a bound and a count evaluated once, and a descending to:do:;
  • non-local returns at method level and inside a real block;
  • a loop variable and a body temp captured by blocks, and a temp of an inlined conditional captured inside the loop and inside a real block;
  • nested loops;
  • a loop as the value of a block, in return position, in assignment position and as an argument;
  • a non-boolean condition, and a receiver block in a variable.

The plain generator and the spike agree on 26. The one they disagree on is below.

What did not fit. Three parts of the inliner had to be written around.

  • shouldInline: requires every argument to be a literal block. to:do: has a number as its first argument. whileTrue: has its block as the receiver, where the test looks for super. The spike gave the test a case per selector.
  • inlineClosure: assigns each block argument from the receiver. The loop variable of to:do: is assigned by the loop. The spike wrote a second template, inlineLoopClosure:, that keeps the arguments.
  • inlinedSend:withBlock: puts the receiver first and inlines the arguments. whileTrue:'s receiver is the block to inline. The spike wrote a second builder.
  • The wrapping inliners wrap the last value of each branch. A loop has no branch whose last value is the loop's value. The spike refuses loops in assignment and return position and leaves them as sends. That covers 16 of the image's 20 loop sites. The other four, the value of a block, stay sends for a reason the oracle found.

The value of whileTrue:. A first version of the spike inlined a loop in return position and dropped the return. It assumed that the loop answers nil. The oracle disagreed: foo | i | i := 0. ^ [ i < 3 ] whileTrue: [ i := i + 1 ] answers a BlockClosure under the plain generator. BlockClosure >> whileTrue: is an inlineJS: method without a ^, and IRASTTranslator appends ^ self to it. So in Amber a loop answers its receiver block. Pharo's whileTrue: answers nil. An inlined loop cannot answer a block that no longer exists. So a loop can be inlined only where its value is unused. The IR shows that only for a statement.

var and let. The spike writes the temps of a loop body, and the loop variable, with let. A second pass rewrote them with var, as visitIRInlinedClosure: writes the temps of an inlined conditional today:

captured by a block inside the loop let var
the loop variable of to:do: (1 2 3) (4 4 4)
a temp of the loop body (1 2 3) (3 3 3)
a temp of an ifTrue: inlined inside the loop (3 3 3) (3 3 3)

The third row is the one case of the 27 on which the finished spike disagrees with the oracle. The existing visitIRInlinedClosure: emits the ifTrue: inside the loop with var. JavaScript hoists a var to the function. Without loops, var goes wrong only where two inlined blocks of one method declare the same name (§2.4). Inside a loop, it goes wrong for every temp that a block captures. An inlined block is a block only as long as its variables are its own. The fix of §2.4, let, is the one that inlined loops need.

Measured. 1,000,000 iterations, best of five after three warm-ups, with debug contexts on, two runs:

loop plain inlined
[ i <= n ] whileTrue: [ s := s + i. i := i + 1 ] 275–278 ms 114–117 ms
1 to: n do: [ :i \| s := s + i ] 367–372 ms 36–37 ms
1 to: n do: [ :i \| i odd ifTrue: [ s := s + i ] ] 853–895 ms 340–372 ms
n timesRepeat: [ s := s + 1 ] 371–376 ms 38–45 ms

A to:do: iteration with one send costs 37 ns inlined. The same iteration as a send costs 370 ns. That is the closure call, the $core.assert on the condition block's answer, and the arithmetic sends of the kernel's to:do:. The October analysis estimated the gain at "roughly double". It is 2.4× where the condition is Smalltalk, and 10× where the counter is JavaScript.

What a landing would still need. A number guard for timesRepeat: and to:do:. The spike compares the counter with <= and trusts the receiver to be a number. The 2011 inliner guarded its speculation with checkClass:; a kernel helper beside assert is the shape of it. let for the inlined temps, which is the fix of §2.4. to:by:do:, whileTrue, whileFalse and repeat, each a class and three to five methods more. A decision on the value of a loop, with Pharo's nil as the candidate. The oracle's 27 methods as tests on AbstractCompilerTest, run in the four contexts.

3.2 The fold: and: and or: as expressions

The title asks whether one inlined send can take part in another. It does, through $n (§2.1). The spike asks what it costs to drop the $n. The send becomes the expression ($core.assert(x) ? (y) : false) when its block is one pure expression without temps.

The spike adds IRInlinedAnd and IRInlinedOr and 18 methods, four of them replacing existing ones.

stage part changed new
3000-inlinerTagging ASTPreInliner >> visitSendNode: leaves an expression-shaped send unmarked 1
IRSendInliner class: expressionSelectors, isExpressionShaped:, isOneExpressionBlock:, isPureExpression: on the AST; isExpressionShapedSend:, isPureInstruction: on the IR 6
6000-inliner IRSendInliner: and:, or:, inlineSend:; inlinedExpression:withBlock:, prefersExpressionForm 3 2
IRWrappingSendInliner >> prefersExpressionForm answers false 1
IRInliner >> replaceChild:with: 1
the IR two classes with acceptDagVisitor: 2
8000-irToJs visitIRInlinedAnd:, visitIRInlinedOr: 2

What comes out, for ^ (x and: [ y ]) ifTrue: [ 1 ] ifFalse: [ 2 ], for ^ (x and: [ y and: [ z ] ]) ifTrue: [ 1 ] ifFalse: [ 2 ] and for ^ Array with: (x and: [ y ]) with: (x or: [ y ]):

if($core.assert(($core.assert(x) ? (y) : false))){
return (1);
} else {
return (2);
}
if($core.assert(($core.assert(x) ? (($core.assert(y) ? (z) : false)) : false))){
return $recv($globals.Array)._with_with_(($core.assert(x) ? (y) : false),($core.assert(x) ? true : (y)));

A block with a temp, an assignment or a non-local return inside keeps the statement form and its $1. So does a block with a statement-form inline inside. In return and assignment position the statement form stays, because the wrapping inliners answer prefersExpressionForm with false.

The oracle. 17 methods. The plain generator and the spike agree on 15. The two they disagree on are NonBooleanReceiver against MessageNotUnderstood, on a receiver 3. The unpatched inliner disagrees the same way.

The image. Translated under the spike: 371 aliases in 274 methods, against 384 in 283; 22 expression nodes.

What the spike ran into. Two things, and both are about the mechanism.

  • The inliner never visits the receiver of a send it inlines (§1.4). The first run of the spike left the and: unmarked. The ifTrue:ifFalse: was emitted with a send in its condition: if($core.assert($recv(x)._and_((function(){ return y; })))). The receiver had to be visited in inlineSend:. Today the tagger turns an inlinable receiver into a variable first. So the missing visit costs only the blocks inside a receiver, the second defect of §2.4. The fold leaves an inlinable receiver in place, so it needs the visit that fixes §2.4.
  • IRVisitor >> replace:with: replaces in the node before the last on the path. The wrapping inliners jump from the return to its send, and from the send to the receiver. When the spike visited the receiver from there, the node before the last on the path was the return. The return does not hold the receiver. IRInstruction >> replace:with: signalled "Object is not in the collection". The spike replaces only when the parent holds the node, and otherwise relies on what visit: answers. A visitor that answers its replacement instead of replacing in place would not have met this (§5 item 4).

The fold is a new form. It costs what a new selector costs, and it buys 13 aliases.

3.3 The receiver rule

isIdempotent answers the aliasing's question: may this read move to the left of the arguments? A temp may not, because an argument to its right could assign it. The receiver rule asks another question: may this be read twice in a row? A temp, a slot and a global may. The spike changes one method, ASTPreInliner >> visitSendNode:, so that a receiver is marked only when it is not a VariableNode.

For foo | t | t := nil. ^ t ifNil: [ 1 ] the result is if(t == null || t.a$nil){ return (1); } else { return t; }, with no $1. The oracle has 13 methods. Their receivers are temps, globals, arguments and sends. Some assign the temp inside the block. Some use the argument form. One runs inside a real block, and one has a non-local return. The two generators agree on all 13.

Translated under the spike, the image has 303 aliases in 218 methods, against 384 in 283. 65 methods lose their var $1; line. The change is one method of the tagger and a Recompile. of what it changes.

3.4 The fixes against the suite

The two fixes of §2.4 and the receiver rule of §3.3 were tried in a full development image. That image is amber/devel, with its tests. Each change was checked three ways. Every method was compiled before and after, and the emitted code compared. The probes ran under both generators. Then the image was recompiled under the change, and the whole SUnit suite ran in it.

change methods it touches methods whose emitted code changes
visit the receiver, in inlinedSend:withBlock: and its two-block sibling 2 0
let for inlined temps, in visitIRInlinedClosure: and a new JSStream >> nextPutLets: 2 53
the receiver rule, in ASTPreInliner >> visitSendNode: 1 84

The suite ran three times: unpatched, under both fixes, and under the receiver rule. Each time it gave 819 runs, no failure and no error.

Visiting the receiver changes no method of the image, so no Recompile. follows it. Under it, six receiver probes are inlined and agree with the plain generator. They are the four shapes of §2.4 and two more. One nests a receiver block inside a receiver block. One returns non-locally from a receiver block. let changes the 53 methods that declare a temp or an ifNotNil: argument in an inlined block. It changes nothing in what they do. Under it, the four probes of §2.4 agree with the plain generator. So do three controls. One uses the same name in the two branches of one send. One nests an inlined block that reads the outer one's temp. One assigns a temp through a wrapped inline. Of the 84 methods that the receiver rule changes, 67 lose their alias declaration.

let would be the first ES2015 token that the emitter writes. That is within bounds. The r.js optimizer reads ES2017 in what it bundles, and the kernel has been written at ES2017 since 2026-10-17. The scaffold builds with optimize: "none", so no project loses its minification. Still, ANALYSIS-2026-10-archaisms.md plans the emitter's syntax raise as a deliberate step of its own. This fix would take that step. A fix within ES5 exists: names unique to each inlined block, and its temps reset on entry. It would fix the defect of §2.4, but not the one that loops would bring. With let as with var, the debugger cannot see an inlined block's temps (§4.4).

3.5 Derived inlines

The maintainer proposed a pragma, <inline>, for a kernel method. Its body would become the expansion of the selector's sends. Only a few primitives would stay in the compiler. A method of the same selector in another class would be flagged, perhaps by a warning. The aim is to derive the inlined forms in Smalltalk wherever that is possible.

Most of the bodies exist already. Boolean writes five of its methods over ifTrue:ifFalse:. Two of them show the two shapes:

and: aBlock
	^ self
		ifTrue: "aBlock" [ aBlock value ]
		ifFalse: [ false ]

ifTrue: aBlock
	"inlined in the Compiler"
	^ self ifTrue: aBlock ifFalse: []

or: takes the shape of and:. ifFalse: and ifFalse:ifTrue: take the shape of ifTrue:, and hand their blocks on. The nil family is written another way. ProtoObject and UndefinedObject each implement its four selectors for their own instances.

The spike adds a stage, 1000-expandInlines, to AstGenerator. So the debugger's interpreter meets its result as well. The stage runs before semantic analysis. It rewrites a send whose selector has a body. It does so when every argument is a literal block and the receiver is not super. In the body, it puts the nodes of the send in place of self and of each argument name. Each of them occurs once in every body. A block [ aBlock value ] becomes the send's own block. A block argument of the body gets a fresh name. The stage is one JavaScript function. To install it, the spike replaces one method of AstGenerator and adds another.

The spike reads Boolean's five bodies from the image as they are. It adds three new bodies for the nil family:

ifNil: aBlock ^ self ifNil: aBlock ifNotNil: [ :it | it ]
ifNotNil: aBlock ^ self ifNil: [] ifNotNil: aBlock
ifNotNil: aBlock ifNil: anotherBlock ^ self ifNil: anotherBlock ifNotNil: aBlock

Two primitives remain: ifTrue:ifFalse: and ifNil:ifNotNil:. The second cannot be derived from the first. A nil test written in Smalltalk is a send, of isNil or of ==. The inliner's test, x == null || x.a$nil, sends nothing.

The image. The lang image has 314 sends of the eight derived selectors. The stage expands every one of them.

what changes under the stage methods of 2,404
the emitted code 174
only the send and block indexes that the debugger reads 13
the list of sends that the method records 243

The image keeps its 384 alias variables in 283 methods. 43 methods expand only and:, or: and the two swapped forms. None of them changes its code. The inliner already builds those four from the two primitives (§1.5). The changes of code come from the one-armed forms. As a statement, a one-armed form has a class of its own today. As a value, the wrapping inliner gives it its other arm. The changes take four shapes:

shape where methods
an empty else ifTrue: as a statement 40
an empty first branch ifFalse: or ifNotNil: as a statement 52
the receiver assigned to a fresh name, which is then answered ifNil: 84
nil answered instead of the receiver ifNotNil: as a value 12

A method may show more than one shape. For foo: x x ifNil: [ ^ 1 ]. ^ 2, the stage emits this:

if(x == null || x.a$nil){
return (1);
} else {
var inline$1;
inline$1=x;
inline$1;
}
return (2);

A rewriting pass could give the first three shapes their code of today. It would drop an empty branch, and negate the test where the empty branch comes first. Where a block only answers its argument, it would answer the receiver. That pass was not tried (§5 item 4).

The fourth shape comes from the body. In that branch the receiver is nil, or JavaScript's null or undefined. Today's code answers it as it is, as UndefinedObject >> ifNotNil: answers self. The body answers nil, as the plain generator does. Smalltalk cannot tell the two apart. A send to null or undefined goes through $recv, which answers nil. UndefinedObject >> == asks the argument isNil. Ten probes answer the same for nil, null and undefined, under both generators. They test identity, equality, isNil, printString, includes: and class. Only JavaScript code sees the difference.

The oracle. It has 14 shapes, in 26 runs. Each run was compiled three ways: with the plain generator, the inlining one, and the inlining one under the stage. The answers were compared as printStrings, with JavaScript's null and undefined taken as nil, as Smalltalk takes them. The stage agrees with the plain generator in 25 runs, and so does today's code. The one left is a block of one argument to and:. It is refused at compile time (§2.2). The stage leaves that send alone, and the inliner refuses it. Compared by name, three more runs differ. true ifFalse: [ 0 ] answers nil inlined, but JavaScript's undefined through a real send (§4.4). In the two runs of the fourth shape, the stage answers nil. Today's code answers the null or undefined it was given. A non-local return through an expanded form is flattened as before, with no try.

One shape names a temp it at the call site, as the ifNil: body names its block argument. It passes because of the fresh name. Without the fresh name, semantic analysis signals ShadowingVariableError. Amber refuses shadowing, so a capture cannot pass unnoticed.

Keeping the receiver. The maintainer prefers the receiver as it is: the inlined code then changes no value. The kernel points the same way. It has one name for nil as a value, and another for nil as a receiver. Since 2017 the first has been the second, with the note TODO null. The body that keeps the receiver names self twice:

ifNotNil: aBlock ^ self ifNil: [ self ] ifNotNil: aBlock

A variable may be read twice (§3.3). 14 of the 46 sends of ifNotNil: have a variable for receiver, and the stage expanded them under this body. For an argument, the code is today's. For a temp or a slot, the branch reads the variable again where today's code reads its alias. As a statement, the branch reads the variable and does nothing else, and the rewriting pass would drop it. The oracle then agrees with today's code in all 26 runs, by name too. The other 32 sends need their receiver bound once, by value. That binding was not tried. The loop bodies need it as well (below).

The suite. The development image was recompiled under the stage, and the suite ran in it: 819 runs, one failure. ASTPositionTest >> testNodeAtPosition asks for the node under the cursor in true ifTrue: [ 1 ]. It gets an ifTrue:ifFalse:.

The interpreter. The debugger asks CompiledMethod >> ast for a method's tree. That tree now holds the expansion. So the interpreter sends a primitive where the source writes a derived form. Take an object that implements ifTrue:ifFalse: and and: itself. For x and: [ true ], the interpreter used to run the object's and:. Under the stage, it runs the object's ifTrue:ifFalse:. Compiled code signals NonBooleanReceiver, before and after. So the interpreter still differs from compiled code, but only at the primitives. Now take an object whose own isNil and ifNil: claim nil. For x ifNil: [ #wasNil ], the interpreter used to run that ifNil:. Under the stage, it answers the object, as compiled code does.

What the spike ran into.

  • The tools see the expansion. A method records the sends of its tree after the stage. 243 methods record other sends than their source writes. Helios looks for senders in that record, so it would miss them. Navigation meets the expansion too, in the failing test. The bodies' own blocks take block indexes, and swapped arguments reorder the send indexes. An expanded send would have to keep the selector that its source writes.
  • A cascade has no receiver before semantic analysis. Only its first message carries one. The stage leaves the later messages alone. No method of the image has a derived selector there.
  • The nodes of the AST take no new children. SendNode, AssignmentNode, BlockNode, ReturnNode and MethodNode derive their children from their slots. Their dagChildren: signals an error. So visitDagNodeVariantRedux: cannot rebuild them, and the stage rebuilds a node through its accessors.

Binding instead of rewriting. The pragma can be read without inlining. A send of the selector with literal blocks is bound to the method at compile time, whatever its receiver. Compiled code binds by inlining. The interpreter could bind by calling the method, and leave the source's tree alone. Then the tools would keep what the source writes. The spike called Boolean's methods directly, on an object that is not a Boolean:

method answers inlined code answers
Boolean >> and: NonBooleanReceiver NonBooleanReceiver
Boolean >> or: NonBooleanReceiver NonBooleanReceiver
Boolean >> ifTrue: the object's own ifTrue:ifFalse: NonBooleanReceiver
Boolean >> ifTrue:ifFalse: the value of the second block NonBooleanReceiver

and: and or: compile to the primitive, because their blocks are literal. ifTrue: hands its block on to a real send of ifTrue:ifFalse:. The primitive's own method tests self == true. So binding needs every body in the shape of and:, with value inside a literal block. And the primitives' methods need the inliner's test.

What it costs beyond the spike. These follow from the design. They were not tried.

  • A body is read when a sender compiles. So a change of a body is an emitter change: the senders keep the old expansion until they are recompiled. amberc compiles with the bodies of the image that it loaded, which are the previous ones.
  • The scaffold's deploy bundles strip a method's source and keep its pragmas. A compiler in a deployed application would know which selectors have a body, but not the bodies.
  • No sibling checkout defines any of the ten selectors. In amber, a warning would meet Boolean, ProtoObject and UndefinedObject. It would meet the inliner as well. IRSendInliner and IRWrappingSendInliner name 14 methods after the selectors, and reach them through perform:.
  • A loop cannot be derived from conditionals. whileTrue: would be a third primitive. to:do: and timesRepeat: could be bodies over it, but such bodies need temps and statements. The stage would then have to bind arguments by value and rename temps.

Derived inlines move the cost of a new form from the compiler to the kernel. A new shape still costs a primitive.

4. Assessment

4.1 Where the rigidity is

The hypothesis named three things: the tagging stage, the class per form, and the inliner three stages later. The spikes sort them.

The class per form is not it. A node class is a definition and acceptDagVisitor:. The loop spike added four, the fold two, and nothing else had to know. IRVisitor has no method for them and needs none, because the inliner builds them and the translator alone reads them. The emitter's method per form is the real content. A generic node with a shape would still need it (§5 item 8).

The split is part of it. The tagger decides on the AST what the inliner will do on the IR. The two must agree. Today they agree by over-approximation. The tagger marks sends the inliner refuses (§2.2) and receivers the emitter could read twice (§3.3). Every new form adds a rule to both sides. The fold needed a shape predicate twice, once on BlockNode and once on IRClosure. A derived form of §3.5 adds no rule to either side. Its stage hands the inliner only sends that the inliner takes.

The templates are most of it. The inliner is written for one shape. A value is the receiver and blocks are the arguments. An if is the result, and the value of the result is the last statement of each branch. inlineClosure: encodes "an argument is the receiver". inlinedClosure:wrapFinalValueIn: encodes "the value is the last statement of a branch". shouldInline: encodes "every argument is a block". The conditionals fit all three. The loops fit none, and the fold fits the second one only by refusing it. A new form is a new template beside the old one. The inliner grows a special case per shape.

Derived inlines would move it. Under §3.5, a form that composes the primitives is a kernel method. It needs no template and no rule in the tagger. Only a new primitive meets the templates, and a loop would be one. So the rigidity would stay with the primitives: two conditionals today, and a loop if one is added.

The aliasing is not it. It served every spike as it is. Its one cost is the $n in operand position. That is the price of JavaScript's if being a statement. The fold shows what removing that price costs.

4.2 What it costs today

  • 384 alias variables in 283 of 2,404 methods. The inliner causes 181 of them: 157 from the receiver rule, 24 from sends in operand position. 81 of the 157 are needless.
  • A send inside another inlined send is two ifs and a $n where one condition would do. The image has 10 such sites.
  • Every loop is a send and a closure, at 2.4× to 10× the cost of a JavaScript loop. The image has 20 such sites, and user code has every loop it writes.
  • Two inlined blocks of one method that declare the same name share one variable (§2.4).
  • An inlinable send inside a block of an inlined send's receiver stays a send (§2.4).
  • Two divergences from the plain generator. NonBooleanReceiver at runtime, and InliningError at compile time for a block of the wrong arity.

4.3 What holds

  • The transformer list took every spike without a change, the stage of §3.5 included. Its seams are where they were said to be.
  • The IR is fourteen classes that an emitter walks, with nine inlined ones beside them. Adding a node costs nothing elsewhere.
  • The aliasing handles the evaluation order of hoisted statements once. It serves the inliner's statements as it serves a cascade's.
  • Non-local return flattening is scope-based, so a new inlined form gets it for free. The loop spike's return inside for came from it. So did the expanded forms of §3.5.
  • The test matrix is the oracle this document used. Every disagreement it found was real.

So "the core is at its limits" holds for one core. The transformer list is not at its limits. The IR is not. The inliner is. It is a conditional inliner, and the conditionals are done. Derived inlines would reduce them to two primitives (§3.5).

4.4 Smaller findings

  • IRInlinedSend >> internalVariables and visitInlinedSend: are left from $receiver (§1.5). Nothing reads the first beyond an empty collection. Nothing implements the second.
  • No test touches an IR class. The October analysis's "testable in isolation" is a possibility, not a practice.
  • (x and: [ y ]) as a statement emits else { false; }, a branch that does nothing. No site in the image has it.
  • An empty block that runs as a real closure answers JavaScript's undefined. [] compiles to a function with no return. An inlined empty branch answers nil, since #1242. So true ifFalse: [ 0 ] answers nil when it is inlined. Through a real send it answers undefined, because Boolean >> ifFalse: passes [] on to a real send of ifTrue:ifFalse:. Smalltalk takes both answers for nil (§3.5).
  • Seven class comments are stale or copied. Compiler's names InlinedCodeGenerator. IRNonLocalReturn's points to a class IRNonLocalReturnHandling, which does not exist. Those of IRInlinedIfNil and IRInlinedIfNotNil say ifNil:ifNotNil:. IRWrappingSendInliner and IRNonLocalReturnInliner carry the comments of IRSendInliner and IRReturnInliner. The example in IRAssignmentInliner's comment lacks a parenthesis. It also lacks the else that #1260 added.
  • IRVisitor >> visitIRNonLocalReturnHandling: visits that missing class. Nothing sends it.
  • A send marked by the tagger and refused by shouldInline: is hoisted for nothing when it is an operand (§2.2). No site in the image has it.
  • IRInliner visits the children of a send it does not inline, and not the receiver of one it does. That asymmetry is the second defect of §2.4. It is also the first thing a fold meets.
  • The debugger cannot see an inlined block's temps. Inside an inlined block, thisContext is the method's context, and its locals hold the method's temps only. The plain generator gives the block a context of its own, whose locals hold the block's temps. The probe put a send in the block, since a block without sends gets no context under either generator. With var, the method's context could list the inlined temps, though sibling names would collide. With let, it cannot list them at all.

5. Possibilities

Ordered by what they buy against what they cost; each names what it would touch.

  1. The two defects (§2.4, §3.4), each its own commit with its test. Visit the receiver in inlinedSend:withBlock: and its sibling: two lines, and no emitted code changes, so no Recompile. follows. Declare an inlined block's temps with let, after the decision of §3.4. That is one method of the translator and one of JSStream. A Recompile. of the 53 methods follows it. The probes of §2.4 belong on AbstractCompilerTest, which runs each in the four contexts. Both defects survive the stage of §3.5.

  2. The receiver rule (§3.3, §3.4). One method, ASTPreInliner >> visitSendNode:: mark the receiver only when it is not a variable. 81 aliases and 65 var $1; lines leave the lang image. The commit is the .st with its .js. A Recompile. follows it, since the emitted code of 84 methods of the development image changes. The oracle's 13 methods belong on AbstractCompilerTest. Under §3.5 the rule stays, with ifNil:ifNotNil: alone in its list.

  3. Dead code and stale comments (§1.5, §4.4), each its own commit. IRInlinedSend >> internalVariables goes, with the two lines that add its empty answer. So do visitInlinedSend: and IRVisitor >> visitIRNonLocalReturnHandling:. The seven class comments are corrected. Removing a public method is an API removal, written in lang/API-CHANGES.txt, so the maintainer picks its release line.

  4. A rewriting pass on visitDagNodeVariantRedux:. The maintainer's first answer to #1260 was a pass over the tree. It makes everything an ifTrue:ifFalse: and removes the branches that do nothing. The derived inlines of item 5 do the first half of that, in Smalltalk. This pass is the second half. It could give the one-armed forms their code of today (§3.5). It would also remove the else { false; } of §4.4. That pass is a tree-to-tree rewrite. The Redux variant in Kernel-Dag.st is the visitor shape for it, on the IR. On the AST, five node classes take no new children (§3.5). A visit answers the node, or a copy with new children. No replace:with: through the path is needed. The fold's second obstacle (§3.2) does not exist there. The inliner itself could move to it. visitIRSend: would answer the inlined node. The wrapping inliners would answer theirs from visitIRAssignment: and visitIRReturn:, without the two-step replace of inlineSend:andReplace:. What stays as it is: the scope rewriting for non-local returns (§1.4), which is outside the tree either way. Compiler-Inlining.st, with PathDagVisitor >> visitDagNodeVariantRedux: as it is.

  5. Derived inlines (§3.5), after item 4 and two decisions. Where the stage runs. In AstGenerator, the interpreter and the navigation meet the expansion. In the code generators alone, they keep the source's tree. And how an expanded send keeps the selector that its source writes. The recorded sends need that in either place. Then the kernel. <inline> goes on eight methods. Boolean's three bodies that hand their block on take the shape of and:. ProtoObject gets one body for each nil form, and UndefinedObject loses its four. The body of ifNotNil: keeps the receiver, so the stage binds a receiver that is not a variable. The two primitives' methods take the inliner's tests. The removed methods go into lang/API-CHANGES.txt. The inliner loses its methods for the eight forms. With item 4, it also loses four of its six classes. A Recompile. follows. The redefinition warning would spare the inliner's dispatch, or those methods take other names. It buys a written meaning for eight selectors, kept in the kernel. A new form then costs no compiler code. And the interpreter could bind those sends, and agree with compiled code at every derived form.

  6. The loop selectors (§3.1), after item 1 and three decisions. What a loop answers. Pharo's nil would let the four block-value sites inline too. It is a change of BlockClosure >> whileTrue: and its siblings. The number guard: a kernel helper beside assert. The selector list: to:by:do:, the unary whileTrue, repeat, each a class and three to five methods. Then the spike's 30 methods and four classes, cleaned, and its 27 methods as tests. The gain is 2.4× to 10× on loop-bound user code. The image has 20 sites. Item 5 would change the shape of this work. whileTrue: would be the one loop primitive, and the other selectors would be bodies over it. Two of the decisions would then be kernel text. What a loop answers is what its body returns. The selector list is the set of methods that carry <inline>. But such bodies need temps, so the stage must first bind arguments by value and rename temps. A body sends <= and + to its counter, as a Smalltalk condition does. §3.1 measured 2.4× for such a condition, and 10× where the counter is JavaScript. A body of to:do: was not measured.

  7. and: and or: as expressions (§3.2). Two classes and 18 methods for 13 aliases. Worth doing only with item 4, where the shape predicate lives once.

  8. One generic node with a shape. IRInlinedSend with a form symbol would replace six classes of two methods each. The emitter would dispatch on the symbol, and keep a method per form. The inliner would keep a method per form. Twelve methods fewer, nothing else changes. Not worth a commit on its own. Items 4 and 5 make it moot: two of the six classes would stay.

  9. Inlining on the AST, before translation. The tagger would become the inliner. It would rewrite a SendNode of an inlinable selector into a conditional node. IRASTTranslator would translate that node into the IR of today. The aliasing would read hasOpeningStatements instead of shouldBeAliased. The wrapping would move into visitAssignmentNode: and visitReturnNode:. The interpreter and the debugger would see nothing of it, since AstGenerator stops at 2500. The count is the same node classes on the AST and the same wrappers in the translator. It saves one walk, and one tree for the shape predicates. It relocates the inliner and does not shrink it. That verdict holds for the primitives. The derived forms of item 5 are another matter. Their bodies are Smalltalk, so they expand on the AST, and the primitives stay where they are.

  10. Inlining at emission. IRInliningJSTranslator would write if when it meets an IRSend of an inlinable selector with closure arguments. It would write ?: when it meets one as an operand with pure blocks. The position is known there, which the fold had to recover. But the aliasing must still happen at 5000, so the tagger stays. The non-local return flattening must happen before the method's try is written, so a pre-pass stays. And the inlined IR goes, which a second backend or a rewriting pass could have read. It removes the node classes and keeps the two things that cost.

What to leave alone: the transformer list, the IR node base, the aliasing, the scope-based flattening, and the test matrix. They are what the spikes stood on.


Appendix: how the numbers were produced

Throwaway Node scripts in the session scratchpad on R:, not committed. Each loads the image with RequireJS from the repository's node_modules. The paths are amber → lang/base and amber/core → lang/src, with amber_core mapped to amber/core. Each requires amber/lang and amber/core/Platform-Node and waits for initialize(). Each keeps a timer alive, since RequireJS gives no error for a callback that fails.

  • harness.js — compile(source, {inlined}) runs Compiler >> start:forClass:protocol: and compileNode: with InliningCodeGenerator or CodeGenerator on DoIt. It answers compiledSource. stripCtx removes the //>>excludeStart("ctx") sections for reading. The [expr][0] wrappers of the send indexes stay, as they stay in deploy code.
  • shapes.js — the 51 shapes of §2, each compiled both ways into one file.
  • irdump.js — the IR of §1.2. The stages after 5000-astToIr or 6000-inliner are replaced with an identity function through Compiler >> transformerAt:put:. A JavaScript function is a BlockClosure to the image, so a => a serves as a transformer.
  • census.js — over every method with source whose owner is the class or trait, on both sides, from api.traitsOrClasses. The tagged AST is built with the stages from 5000 on replaced. A walk with a path classifies every send of the ten selectors by position and by block shape. The IR after 5000 is built three times. The tagger is as it is, then a JavaScript tagger that marks sends only, then none. Each time internalVariables is counted. The IR after 6000 is walked for the IRInlined* nodes and the surviving sends.
  • census2.js — the loop sends by position, and the iteration selectors with literal blocks.
  • spike-loops.js — the patch of §3.1 as Smalltalk sources installed with Compiler >> install:forClass:protocol:, and the four classes made with subclass:slots:package:. The 27 oracle methods run under both generators. The captured cases run again with var. The benchmark takes the best of five after three warm-ups, timed with process.hrtime.bigint().
  • spike-fold.js, fold-novisit.js — the patch of §3.2 and its oracle, then the image translated to IR under it. The second script leaves out the receiver visit in inlineSend: and prints what the first run of the spike emitted.
  • spike-receiver.js — the one-method patch of §3.3, its oracle, and the image under it.
  • issues.py — the three issue threads from the saved lolg.it pages, for the quotes of §1.5.
  • probe-bugs.js, probe-ctx.js, probe-error.js — the defects of §2.4 and the debugger's view of §4.4, each source compiled and run under both generators. The second puts a send in the block. Then the plain generator gives the block a context of its own. The third compares two errors of one or:: in a receiver's block, and as an argument.
  • scan-siblings.js — the scan of §2.4. It reads the source: strings of the compiled .js of amber and the eight sibling checkouts. It parses each with Compiler >> parse: and walks the tree for both shapes. Parsing alone is enough for that, with no semantic analysis. A control file with both shapes ran first. The counts match the source: lines of each checkout.
  • spike-fixes.js, spike-p0.js — §3.4. They load amber/devel instead of amber/lang, and build the suite as sdk/lib/NodeTestRunner.st does. The patches are installed, every method is compiled before and after, and the emitted code is compared. Compiler class >> recompileAll runs before the suite's second run.
  • spike-templates.js — §3.5. It loads amber/devel. The stage is a JavaScript function. A replaced AstGenerator >> transformersDictionary asks a new inlineExpander for it, and a global switch turns it on for one compilation. Boolean's five bodies are read from localMethods, without their comments. The script compiles every method with the stage and without, and runs the oracle three ways. It runs two methods through ASTInterpreter on an AIContext, without the stage and under it. Then it recompiles the image under the stage and runs the suite.
  • spike-templates2.js — the lang image under the stage. It compares the code after removing the ctx sections and the [expr][0] wrappers, and sorts what remains by shape. It calls Boolean's methods directly on an object that is not a Boolean.
  • spike-templates3.js — the alias variables with and without the stage, and the two defects under it. Also SendNode >> dagChildren:, and three non-local returns through expanded forms.
  • probe-empty.js — the empty block of §4.4, as a real closure and through a real send of ifFalse:.
  • spike-templates4.js, probe-keep-receiver.js, probe-keep-receiver2.js — the shapes of §3.5 counted again, each by occurrence, for the table. Then the receiver kept. The ten probes on nil, null and undefined, under both generators. The oracle compared by name and as Smalltalk sees it. The body of ifNotNil: that names self twice, expanded where the receiver is a variable, with the code it emits.