Thomas Denney

MUJI Stationery

MUJI, the minimalist “no-brand” Japanese retail store, sells an excellent collection of stationery. Usually after removing any stickers or packaging from their products there is no branding left. However, I’d argue that their products are branded in the sense that they are distinctly recognisable, particularly by their quality. MUJI stationery is not the cheap, prototypical “no-brand” stationery that you might purchase from a supermarket, for example.

MUJI fountain pen and notebook
MUJI fountain pen and notebook

I don’t have too much to say about the MUJI fountain pen. Unusually for a sub-$20/£20 pen it has an all-aluminium body. The design is simple, but looks a lot better than similarly priced pens. The nib is a Schmidt fine, and its fine. It writes fine. It flexes fine. It looks fine. I prefer Bock nibs, but I’ve no major complaints about the Schmidt nib. The pen can take an international converter or cartridge, although I only had luck fitting some international converters into mine (I suspect it might have a manufacturing defect as the nib sometimes wobbles a little).

However, my main experience of MUJI pens is not with the fountain pen, but with their gel pens. Today, MUJI sell round polycarbonate gel pens in a wide variety of colours and point sizes. Conveniently, you can buy them in bulk and purchase refills too. For an inexpensive gel pen, they write smoothly and you can buy them with very thin line widths.

MUJI hexagonal gel pen
MUJI hexagonal gel pen

My favourite MUJI pen is no longer sold as far as I can tell. At least as recently as 2018, MUJI sold hexagonal polycarbonate gel pens. I’ve owned dozens of them, and they were popular amongst my friends and family: to solve a lifetime of pen purchases, one friend even bought all the refills in stock in a San Franciscan MUJI.

By the summer of 2019 I couldn’t find them anywhere: I checked MUJI stores across cities and continents. They’re absent from MUJI’s website (although a picture on the fountain pen page clearly still shows one).

MUJI hexagonal gel pen

Although the current round pens carry a similar refill and write just as well, I’m still a little sentimental for the hexagonal pens. I alternated between fountain pens and these MUJI pens for most of the mathematics I wrote at university: their narrower line width was useful for drawing out intricate symbols next to prose.

For the time being I’ve got plenty of the pens and their refills kicking around, but I’d love to know the story of their disappearance.

Westminster Bridge

Westminster Bridge

Lamy 2000

Lamy 2000

Alongside most of the world I am working from home amidst the Covid-19 crisis. The UK will review its lockdown tomorrow, but it will be a long time before life returns to normal. The extra time afforded by my significantly shorter commute has given me the opportunity to cook, watch movies, and enjoy my fountain pen collection.1

I bought a Lamy 2000 after completing my undergraduate degree, but used it little through my master’s. It had long been my grail pen but I had no need to write Verilog by hand, so it remained largely unused.2 Prior to the 2000 I owned the Lamy Studio, Vista, and Safari. All of these are great pens and exploration inevitably lead me to the 2000.

My immediate reaction to the 2000 was that it looked so much cooler than all my other Lamy pens. The Studio certainly has a distinctive shape and clip whilst the Safari/Vista design is purely functional and almost authoritarian: the triangular grip dictates how you must hold the pen.

On the other hand, the 2000 is ingenious in its simplicity. Ignoring the cap, you’d be forgiven for thinking the pen is a single part. The joins separating the body from the grip and the body from the twist mechanism are deliberately obscured. Unlike most fountain pens, disassembly is rarely required as the pen can be refilled just by dipping it in ink and rotating the end cap. This unibody design predates the MacBook by forty years.

Lamy 2000

Although enamoured with the pen’s appearance, I didn’t initially enjoy writing with it as much as I expected. I initially had a faulty pen that leaked and ink didn’t flow well through the second nearly as well as some of my TWSBI or Pilot pens. However, over time I adjusted to the pen, and found I preferred the “fine” thickness to my other, thicker nibs. The rhodium-plated gold nib is also the smoothest nib I’ve ever used, and surprisingly forgiving on poor quality paper. Today I have no complaints whatsoever about the functionality of the pen, and I’ve never had difficulties caring for or cleaning it.

Expensive fountain pens tend to be heavier than their cheaper counterparts, especially north of $200. In part this is due to the use of metal parts over plastic, but I suspect it mostly plays into the psychology of heavier objects feeling more substantial and therefore more valuable. The 2000 eschews this, and is instead finished in Makrolon (polycarbonate) so that it weighs in at just 25g, little more than the 17g Lamy Safari, even though it costs an order of magnitude more. I’d argue that this gives the 2000 a significant advantage over other pens in its price category: I can hold it and write with it for much longer than a Pilot Vanishing Point, for example.

Like the Lamy Studio — but unlike the Safari — the 2000 gives you flexibility in the way you hold it. The grip isn’t entirely symmetrical: it cuts off to form a straight edge with the nib. When viewed from below the symmetry returns: the outline of the nib mirrors flat area around the breather hole.

Lamy 2000

The 2000 features a narrow window near the section to indicate remaining ink. Windows are a common feature of Lamy pens, but unlike the Safari the slits only give you a vague sense of how much you’ve got left. Although windows are certainly useful, I don’t particularly like it as it edges away from the design’s uniformity. The window doesn’t feature on the “metal” finish of the pen, but inevitably I own the pen in black. The pen is light enough that the filled and unfilled weights are noticeably different.

A disadvantage of the uniformity is that the pen loses modularity: there is no choice over nib or ink refill mechanism. This is not entirely a bad thing: I’m a great lover of bold designs that are unafraid to make choices for you.3 In any case, I can’t imagine there are many people installing a $200 gold nib in a $20 Safari.

Lamy 2000

The 2000 is by far my favourite pen. I’m certainly not alone in my love for this pen and my affection is perhaps even clichéd. However, I believe represents the best of what fountain pens can be: comfortable to write with, easy to hold, and a hell of a great design. It is to this pen I point when I need to justify my view that fountain pens are the best writing instruments we have. In times such as these, we should celebrate that which represents the very best of what we can be, if only to bring a little more cheer into the world.


  1. My most recent experiment was fresh pasta: using only a rolling pin to roll and fold the pasta probably burned more calories than I actually consumed.↩︎

  2. I didn’t enjoy typing the Verilog too much either, but I was at least happy with the final processor that I designed for my thesis.↩︎

  3. I have a fantasy of a “zero-decision” restaurant: you would walk in, be seated and served a single starter, then main, and finally dessert. Each course would be partnered by a single appropriate wine. Perhaps finish with coffee. Then leave, paying a bill that includes the tip and taxes, rounded to a suitable pleasing amount. No choice whatsoever: the only decision you can make is to walk through the door. My libertarian side does not advocate that all restaurants should be like this, but I’d love to experience one.↩︎

The British Airways Safety Videos

If you’re a frequent traveler (or were, back in The Good Old Pre-Corona Days), you may have seen the British Airways Safety Video or its sequel. These videos are played at the start of flights with in-flight entertainment systems and feature British actors and celebrities but are otherwise like any other in-flight safety video.

The two videos feature Gillian Anderson, Rowan Atkinson, Jim Broadbent, Rob Brydon, Asim Chaudry, Warwick Davis, Chiwetel Ejiofor, Ian McKellen, Thandie Newton, Gordon Ramsay, Naomie Harris, Michael Caine, Joanna Lumley, Jourdan Dunn, David Walliams, and Olivia Colman.

Whilst watching these videos I’ve often wondered what else these actors have appeared in together: the videos deliberately have ensemble British casts, as do plenty of other films and TV shows (Love Actually, Harry Potter, Doctor Who, etc). Sadly I’ve now found time to assemble that list. Films and TV shows with more than two of the collaborators are in bold.

  • 2012: Chiwetel Ejiofor, Thandie Newton
  • A Cock and Bull Story: Gillian Anderson, Rob Brydon, Naomie Harris, David Walliams
  • Accused: Naomie Harris, Olivia Colman
  • Animals United: Jim Broadbent, David Walliams
  • Any Human Heart: Gillian Anderson, Jim Broadbent
  • Arena: Jim Broadbent, Ian McKellen
  • BBC2 Playhouse: Jim Broadbent, Ian McKellen
  • Billionaire Boy: Warwick Davies, David Walliams
  • Black Books: Rob Brydon, David Walliams, Olivia Colman
  • Blackadder and Blackadder’s Christmas Carol: Jim Broadbent, Rowan Atkinson
  • Boogie Woogie: Gillian Anderson, Warwick Davies
  • Children of Men: Chiwetel Ejiofor, Michael Caine
  • Cold Comfort Farm: Ian McKellen, Joanna Lumley
  • Comedy Lab: Warwick Davies, Olivia Colman
  • Comic Relief: Doctor Who - The Curse of Fatal Death: Rowan Atkinson, Jim Broadbent, Joanna Lumley
  • Comic Relief: Upstairs Downstairs Abbey: Joanna Lumley, Olivia Colman
  • Coronation Street: Ian McKellen, Joanna Lumley &emdash; this surprised me!
  • Cruise of the Gods: Rob Brydon, David Walliams
  • Doctor Who: Warwick Davies, Ian McKellen, David Walliams, Olivia Colman
  • Exiles: Jim Broadbent, Olivia Colman
  • Extras: Rob Brydon, Warwick Davies, Ian McKellen, Gordon Ramsay
  • Gangsta Granny: Rob Brydon, Joanna Lumley, David Walliams
  • Half of a Yellow Sun: Chiwetel Ejiofor, Thandie Newton
  • Harry Potter and the Half-Blood Prince and Harry Potter and the Deathly Hallows Part 2: Jim Broadbent, Warwick Davies
  • Hot Fuzz: Jim Broadbent, Olivia Colman
  • How to Lose Friends & Alienate People: Gillian Anderson, Thandie Newton
  • It Was An Accident: Chiwetel Ejiofor, Thandie Newton
  • Johnny English Reborn: Gillian Anderson, Rowan Atkinson
  • Jonathan Creek: Warwick Davies, Joanna Lumley
  • King Lear: Jim Broadbent, Ian McKellen
  • King of Thieves: Jim Broadbent, Michael Caine
  • Little Britain: Rob Brydon, David Walliams
  • Little Voice: Jim Broadbent, Michael Caine
  • Look Around You: David Walliams, Olivia Colman
  • Love Actually: Rowan Atkinson, Chiwetel Ejiofor
  • Maleficient: Mistress of Evil: Warwick Davies, Chiwetel Ejiofor
  • Marple: Rob Brydon, Joanna Lumley, David Walliams
  • Maybe Baby: Rowan Atkinson, Joanna Lumley
  • Mr Morgan’s Last Love: Gillian Anderson, Michael Caine
  • Murder in Mind: Rob Brydon, Chiwetel Ejiofor
  • Not the Nine O’Clock News: Rowan Atkinson, Jim Broadbent
  • Paddington: Jim Broadbent, Asim Chaudry
  • Paddington 2: Jim Broadbent, Joanna Lumley
  • Play for Today: Jim Broadbent, Ian McKellen
  • Prince Valliant: Warwick Davies, Joanna Lumley
  • Pudsey the Dog: The Movie: David Walliams, Olivia Colman
  • Red Nose Day Actually: Rowan Atkinson, Chiwetel Ejiofor
  • Revolting Rhymes: Rob Brydon, David Walliams
  • Richard III: Jim Broadbent, Ian McKellen
  • Room on the Broom: Gillian Anderson, Rob Brydon, David Walliams
  • Run Fatboy Run: Thandie Newton, David Walliams
  • Screen Two: Jim Broadbent, Chiwetel Ejiofor
  • Shaun of the Dead: Rob Brydon, Chiwetel Ejiofor
  • Sherlock Gnomes: Chiwetel Ejiofor, Michael Caine
  • Solo: A Star Wars Story: Warwick Davies, Thandie Newton
  • Spider-Plant Man: Rowan Atkinson, Jim Broadbent
  • Stardust: Ian McKellen, David Walliams
  • The Chronicles of Narnia: Prince Caspian: Warwick Davies, David Walliams
  • The Crown: Olivia Colman, Gillian Anderson
  • The Five(ish) Doctors: Ian McKellen, Olivia Colman
  • The Iron Lady: Jim Broadbent, Olivia Colman
  • The Magic Roundabout: Jim Broadbent, Ian McKellen, Joanna Lumley
  • The One Ronnie: Rob Brydon, David Walliams
  • The Simpsons: Gillian Anderson, Ian McKellen
  • The Wednesday Play: Ian McKellen, Joanna Lumley
  • This is Jinsy: Rob Brydon, Olivia Colman
  • Twist: Michael Caine, David Walliams
  • W1A: Asim Chaudry, Olivia Colman
  • Walliams and Friend: Joanna Lumley, David Walliams
  • Walter and Walter & June: Jim Broadbent, Ian McKellen
  • War and Peace: Gillian Anderson, Jim Broadbent

The following lists the number of times each actor appears in the above list. Jim Broadbent and David Walliams must have superb agents as they clearly lead the pack.

  • Gillian Anderson: 10
  • Rowan Atkinson: 8
  • Jim Broadbent: 23
  • Rob Brydon: 13
  • Asim Chaudry: 2
  • Warwick Davis: 11
  • Chiwetel Ejiofor: 11
  • Ian McKellen: 15
  • Thandie Newton: 6
  • Gordon Ramsay: 1
  • Naomie Harris: 2
  • Michael Caine: 6
  • Joanna Lumley: 13
  • Jourdan Dunn: 0
  • David Walliams: 20
  • Olivia Colman: 14

The list excludes cases where actors appear as themselves, nearly all of them have appeared on The One Show or The Graham Norton Show at some point, but it’s unlikely that any of them will have appeared at the same time (and would probably be far too much research on my part).

Abbey Road

Abbey Road pedestrian crossing
The pedestrian crossing near Abbey Road Studios today

In normal times, tourists would disembark the Jubilee Line at St John’s Wood and walk down Grove End Road to imitate The Beatles’ famous album cover outside Abbey Road Studios.1 On my morning runs I’d usually see a group gathered outside the studios hoping to dodge the traffic for a moment to take their souvenir photo.

Today there was nobody.

As the world enters lockdown we’ll see many more photos of tourist attractions, business centres, and sports stadiums devoid of people. Right now, these photos seem strange: the very absence of people from our shared places makes them feel lonely, spare, and purposeless. Without tourists and Beatles fans, this is just a pedestrian crossing. Without traffic, it barely need serve that purpose.

News organisations should share these photos: they are evidence that people are following guidance to stay home, and that is newsworthy. On Friday evening, after Boris Johnson announced pubs must close, thousands descended on their locals to get in one last pint. It was disheartening to see people wilfully miss the point, but at least we’re now seeing that people can and will listen to government guidance.

However, when we look back at the Covid-19 crisis I don’t think we’ll reflect too hard on photos of empty streets and spaces, precisely because they are empty. This crisis wasn’t caused by people, but people can manage it, and images of what people have done and will do will have far greater lasting impact. Not all of that is good: raiding supermarkets shelves is a selfish and unproductive approach to the coming weeks.2 But in others we will see the very best of humanity, and we should record and celebrate their efforts.

All of this is to say that my photo of Abbey Road is fairly pointless; a momentary capture of an unusually quiet morning in North London.


  1. Last week, I came across a group taking a similar photo at entirely the wrong pedestrian crossing a little further up Abbey Road. I’ve no idea if they’d made a genuine error or had eschewed the crowds outside the studios, but I found it delightful nevertheless.↩︎

  2. Also, toilet paper?! What are you all planning?↩︎

Californian Landscapes

Silver Lake
Silver Lake
Convict Lake
Convict Lake
Ice at the edge of Convict Lake
Ice at the edge of Convict Lake
Trees near Lake Tahoe
Trees near Lake Tahoe
Looking towards Lake Tahoe
Looking towards Lake Tahoe

Sujiko

A Sujiko puzzle. The digits 1-9 are arranged in each cell so that the value in each circle is the sum of the surrounding cells.

Sujiko is a puzzle often featured in British newspapers. The idea is simple: arrange the digits 1-9 in a 3x3 grid, using each digit exactly once, such that each 2x2 square’s sum matches a given value. To start the reader off, one or two of the cells are filled with clues.

My immediate reaction to discovering these puzzles yesterday is that they are ‘boring’, by which I mean trivially solvable by a computer. Secondly, I noted that the state search space for a potential solution is remarkably small compared to other common ‘newspaper puzzles’ like sudoku: there are around 6.67 × 1021 possible sudoku puzzles, but just 9! = 362,880 possible Sujiko puzzles. However, with 2 clues it is only necessary to check 7! = 5,040 possible digit permutations.

But the state search space can be further reduced! Once values for the five non-corner squares we can determine the values we would have to select for the corners (per the sum constraint); the solution is valid if we can select four values for the corners that have not already been used. Assuming two clues are given, this reduces the search space to 7 × 6 × 5 × 4 × 3 = 2,520 permutations in the worst case, but we can still do better!

Wikipedia notes two identities that can further reduce the search space:

In the case of the puzzle at the beginning of the article we only need to select one of 7 possible values for the centre square (x4), which then gives a value for the square to its right (x5). With a centre value selected and the opposite corner already known, we can find the value of the bottom-left corner (x6). From there we only need to fill x7 with one of four remaining digits: this will then constrain all other cells. Therefore there are only 28 permutations to check for the above puzzle — or any other puzzle with clues in the same position (including symmetry).

For any arrangement where the two clues are directly opposite (e.g. in x1 and x7 or x3 and x5) we should firstly fill the centre (x4) with one of 7 possibilities and then another non-corner (e.g. x7) with one of 6 possibilities. From there we can derive all other cells.

For arrangements where the 2 clues are on the same diagonal, It is then only necessary to select one of 6 values for one of the non-corner cells, from there another cell value can be derived, and after that only of four values needs to be selected for another non-corner cell: after this all other cell values can be derived: 24 permutations should be checked in all.

For puzzles with only one clue it is only necessary to place one value (of a possible 8), and preferably to minimise the number of subsequent permutations to check. In the worst case only 8 × 42 = 336 possibilities need to be checked.

From what I’ve seen, puzzles with 2 clues are labelled ‘hard’ whilst puzzles with a single clue are ‘extreme’ in difficulty. Clearly enumerating these by hand would be incredibly dull, but these can be enumerated in well under a micro second on a computer.

Last night I threw together a general purpose solver for these puzzles, and in my experiments it can solve the general case in under 3 μs (alternatively: it could solve every single Sujiko puzzle ever published in a British newspaper in under a thirtieth of a second). The main algorithm is just a recursive backtracking search with constraint propagation.

To accelerate the solver I wound up on a journey into SSE instructions (most of the puzzle state is stored in a single xmm register) at about 3AM, but I’m happy with the results. The solver could be accelerated further with a little more inline assembly to reduce main memory interaction and specialisation for each possible starting layout.

The United States is One of the Oldest Countries in the World

Globe

“Hey yo, I’m just like my country, // I’m young, scrappy, and hungry,” begins the song My Shot from the musical Hamilton. The image of the United States as a new, young nation independent from the empires of old is one reflected in both history and the present day: the history books tells us that the US is part of the “New World” that was “discovered” by Europeans in the modern era, and every year Americans celebrate their country’s birthday on the Fourth of July. However, when we consider the radical political change in the rest of the world since 1776 a different narrative emerges.

We begin by adopting and adapting the American definition: a nation began when it most recently adopted a new constitution or a law that declared a new nation, independence, or substantially different government. Ironically, this shifts the establishment of the US to 1787, when the constitution was ratified. Nevertheless, this definition places the US as the fifth oldest nation in the world, after the Vatican (1274), San Marino (1600), Morocco (1631), and Oman (1749).

This definition is far from perfect. The first problem is that nations are often established or re-established in homage to older nations. The modern Republic of France is politically divergent from the Kingdom of France1 yet they still occupy a similar territory, share the same name, and speak (roughly) the same language. Often when nations gain independence they revert to their pre-colonial borders and names, but with forms of government very distinct from colonial or imperial rule. The introduction of a formal constitution isn’t necessarily an indicator of a new nation: many just codify existing norms.

However, it isn’t necessarily wise to ignore governmental changes, because we would might miss the big gradual evolutions: the Roman Empire began in Rome in 27 BC, but the Byzantine Empire, one of its later forms, ended with the Fall of Constantinople in 1453 AD over 1,000km away. States are perhaps the biggest examples of the Ship of Theseus.

If we relax the definition of the establishment to most recent acquisition of independence or sovereignty the results remain similar: the US is the tenth eldest country.2 Even if we switch to first acquisition of sovereignty the US places 57th, which is still in the eldest third of countries.

Countries that first gained sovereignty or independence before the US are highlighted in brown. Former British territories are pink, former French territories are blue, former Spanish territories are yellow, and former Soviet states are red. All other countries gained sovereignty by other means.

The data are unsurprising when we consider events since the 18th century. The United Kingdom comprised separate kingdoms until 1707, and consequently any country that was not recognised as sovereign, but later gained independence from the British Empire later is newer. Plenty more countries formed during France and Spain’s decolonisation. The end of the imperial age affected the age of almost every country in the Southern Hemisphere from the early 19th century onwards. Eurasian sovereignty evolved radically over the 20th century as countries were absorbed into the Soviet Union, yet mutated once more before the close of the century with the bloc’s collapse. Simply put, US longevity depends on an early imperial exit and a distaste for communism.

An alternative definition would be to consider when the colloquial name of a country changes. This is a helpful proxy for countries established before constitutions were en vogue but language evolution is a hindrance: England is not necessarily a distinct country from the (rather charming) Old English Englaland. Languages and nations evolve asynchronously. It would be unreasonable to fix the definition to a particular language; using English would just reflect the international politics of the Anglosphere.

Ultimately, regardless of the path we take, any attempt to unambiguously define how countries are established will see the US in at least in the older half of nations. This is primarily the result of decolonisation in the mid-to-late twentieth century and the later collapse of the Soviet Union: until many countries left these supranational blocs they didn’t necessarily fit our modern definition of a nation. It is perhaps also a testament to the influence of the US’s Constitution (and in turn the Magna Carta, amongst other documents) that the US has fit within the modern definition of a nation for so long, and that so many countries modelled their governments after the US.


  1. Since the late eighteenth century, France has been a kingdom, a republic (1792), an empire (1804), a kingdom (1814), a monarchy (1830), a republic (1848), an empire (1852), a republic (1870), an occupied territory with a republican government in exile (1940), a provisional republic (1944), a republic (1946), and finally a revised republic (1958).↩︎

  2. In order: Portugal (1139), San Marino (1503), Spain (1516), Sweden (1523), Morocco (1631), Bhutan (1634), Liechtenstein (1719), Oman (1743), and Nepal (1768).↩︎

JIT Compilation on an ARM Cortex M0

For my bachelor’s thesis last year I implemented a JIT compiler for the BBC micro:bit, a micro-controller that is being used around the world to teach programming in schools. My compiler took bytecode for a virtual machine designed by my supervisor, compiled it to ARM Thumb bytecode, and executed the generated bytecode. The main challenge here is getting the JIT compiler to store the original virtual machine bytecode, auxiliary data structures, compiled bytecode, and program data in 16 KB of RAM. Rather than replicate my thesis in full here I’m just going to run through the basic steps involved to JIT compile and execute functions on a Cortex M0; I assume familiarity with C++ and ARM Assembly and calling conventions.

At a minimum, a JIT code generators needs to perform three basic steps:

  1. Generate a sequence of instructions encoded in the processor’s bytecode;
  2. Jump to that sequence of instructions, allowing the processor to execute them; and
  3. Return from the generated code to the environment.

The simplest way to get this working is to generate a sequence of instructions terminated by bx lr, which corresponds to a return in ARM assembly, and then to call that sequence of instructions as if it is a function:

typedef void (*f_void)(void);

static const uint16_t instrs[] = { 0x4770 };
asm("DSB");
asm("ISB");
f_void fp = (f_void)((unsigned)instrs | 0x1);
fp();

In this basic example our generated code is a compile time constant, but this example adapts to dynamically allocated arrays too. 0x4770 is the hexadecimal encoding of bx lr, the ARM instruction that corresponds to branching to the address in the link register, which will be the return address:

Note that the Cortex M0 executes Thumb bytecode, which is a compact version of the full ARM 32-bit instruction set; most instructions are represented in 2 bytes. The most significant 9 bits of this instruction encode that this is a branch and exchange instruction and the subsequent 4 bits encode the register that contains the address to jump to (the link register is register r14). The last three bits should be zero.

Next, two inline assembly instructions are issued. DSB is a data synchronisation barrier, and ensures that no instruction in program executes until after this instruction completes, i.e. the instruction ensures that all memory operations complete. Next, ISB is an instruction synchronisation barrier, and flushes the fetch pipeline of the processor. In this case, where our JIT’d code is actually in a static array, these instructions are not necessary. However, when generating instructions it is necessary to ensure that (a) our generated instructions are fully written to memory, and (b) the fetch pipeline doesn’t attempt to fetch the old value. These instructions must be issued across all ARM architectures (not just the Cortex M0) when running JIT’d code.

Memory protection typically prevents memory being both writeable and executable, so in JITs on other OSes it would generally be necessary to prevent writing and only permit executing the code. No such protection exists on the Cortex M0, so only DSB and ISB must be executed.

Next, we cast the pointer to the instructions sequence to a pointer to a function pointer so we can call the code. Our array will be 2-byte aligned (which is required for Thumb instructions), but when branching the LSB of the address we jump to must be 1 to indicate that the instruction we are jumping to is encoded in Thumb bytecode rather than full 4-byte ARM bytecode.

Supposing we have access to a memory allocator, we can adapt the above to dynamically generate the same function at runtime:

uint16_t* instrs = (uint16_t*)calloc(1, sizeof(uint16_t));

instrs[0] = 0x4770;
asm("DSB");
asm("ISB");
f_void fp = (f_void)((unsigned)instrs | 0x1);
fp();

free(instrs);

This function isn’t particularly interesting: it has no observable side-effects and doesn’t return anything. As a toy example, the following function JIT-compiles a function that sums between 0 and 4 integer values. The first four integer arguments are always passed in registers under ARM calling convention, and the result of an integer function is returned in r0.

typedef int (*f_4_int_to_int)(int, int, int, int);

int jit_int_sum(unsigned int n)
{
    std::vector<uint16_t> instrs;
    if (n == 0) {
        // MOV   Rd  Value
        // 00100 000 00000000
        // 2   0     0   0
        instrs.push_back(0x2000);
    } else {
        for (unsigned k = 1; k != n; ++k) {
            // Rd := Rn + Rm
            // Add     Rm  Rn  Rd
            // 0001100 000 xxx 000
            // 1   8    0    0
            instrs.push_back(0x1800 | (k << 3));
        }
    }
    instrs.push_back(0x4770); // Return

    asm("DSB");
    asm("ISB");
    auto fp = (f_4_int_to_int)((unsigned)instrs.data() | 0x1);
    return fp(1, 2, 3, 4);
}

Note that this time I’ve used a C++ vector to simplify the memory management. In this example we either clear the return register or sum up to three remaining registers into the first register. For simplicity, the function pointer is always cast to the same type and called with the same number of arguments, but the return value of the function will differ depending on the value of n.

Encoding instructions manually in hexadecimal (or binary) isn’t a particularly good use of your time. In my project I implemented a library for all Thumb instructions, and eventually I also implemented a decoder to help with debugging. Helpfully the decoder (printFunction) can take a pointer to an arbitrary ARM function, allowing runtime bytecode -> assembly conversion.

The next challenge is dealing with branches. In a traditional compiler this can be delegated to a linker, but in a JIT where all code bytecode must be generated it is necessary to deal with them yourself. The conditional branch is encoded as:

The condition is a 4-bit value and is used in conjunction with the condition flags of the CPU to determine if the branch is taken. I specify the values of these conditions in my instruction encoder here. The immediate value is a signed (two’s complement) 8-bit integer. If the condition holds, the value is sign extended to a 32-bit value, doubled, and added to the current program counter, so that the branch supports offsets from -256 bytes to +254 bytes. However, it is important to note that the program counter, at the time the branch instruction begins, is the address of the branch + 4 bytes. Therefore if the conditional branch needs to skip forward by 2 instructions, then the offset should be 0. If the branch needs to skip back 10 instructions, then the offset should be -12. The same encoding scheme is necessary for unconditional branches and bl/blx instructions (used for functional calls), although these both admit 11-bit offsets.

The examples above are able to freely use registers because they conform to the basics of ARM calling convention; dealing with function calls and access to other registers only requires that you follow this convention in generated code.

The full code of microjit is on GitHub. I’ve also uploaded a barebones example showing the examples from this post executing.

Pilot E95s

Pilot E95s

The Pilot E95s is a pocket fountain pen released by Pilot to celebrate their 95th anniversary. The pen sports a classic mid-century design based on the Pilot Elite, and it makes for a great combination of vintage design with modern manufacturing. I own the ivory and burgundy pen, but it is also comes in black (as all great products should). Both colour schemes feature a large 14K carat gold nib, which has been superb to write with.

Japanese nibs tend to come up narrower than American or European nibs and the Pilot E95s is no exception. I have the medium nib, but it comes up no thicker than fine Lamy nibs, as shown below.

J. Herbin Rouge Opéra, Pilot Iroshizuku Take-Sumi, and De Atramentis
Dunkelblau inks on Tomoe River paper (the nicest paper I've ever written on,
but sadly difficult to get hold of in the UK).
J. Herbin Rouge Opéra, Pilot Iroshizuku Take-Sumi, and De Atramentis Dunkelblau inks on Tomoe River paper (the nicest paper I've ever written on, but sadly difficult to get hold of in the UK).

The pen is compatible with Pilot's CON-20 and CON-40 converters. I'm not certain that there is enough space to use a cartridge. To the pen's detriment the converter is almost entirely covered by the screw thread for the body, making it impossible to see how much ink remains in the converter. The converter itself contains a ball that will rattle when the converter is empty, which can be irritating whilst writing.

The E95s is indisputably a premium fountain pen, and it's an affordable introduction to gold nibs. However, I found that it didn't feel like a premium fountain pen: it feels too lightweight. This is entirely down to resin construction, which makes it a lot lighter than other pens in its price category. At 17g, its weight is comparable to the larger TWSBI Go or Lamy Safari, although each of these are larger. I'm currently using a Lamy 2000 as my primary pen (25g) alongside a Pilot Vanishing Point (30g), so I've found that I notice the E95s's weight every time I write with it. Regardless of its weight, I could replace either of my daily drivers with the E95s if need be: its nib is incredibly smooth and it writes well on a variety of surfaces.

Whilst I researched this review I attempted to find out a little about the history of the pen, but instead I found a myriad of inconsistencies! Firstly, the name of the pen is different in the United States and Japan. In the US it is marketed as E95s (although the case of the “s” varies between suppliers and Pilot's websites), whilst it is called the Elite 95s in Japan. The name also affects the design, with the Japanese version inscribed with “Elite” rather than “E”, as in the American version. I think the “Elite” inscription looks better.

Pilot E95s

Most distributors describe that the E95s is based on the Pilot Elite, which was originally released in either 1962 or 1968. However, neither date is correct! Whilst it is certainly true that the Pilot Elite was sold in the 1960s, and embodies the design of that decade, Pilot Japan's website (Google Translate) states that the first Elite was released in 1954, and that the E95s is actually based on a later second edition released in 1974. This corroborates with the appearance of Elites that I've found on eBay, and this excellent post on the fountain pens subreddit compared the E95s with an older Elite. Noticeably, the nib of the E95s is much larger.

Pilot E95s boxed; the Vanishing Point comes in the same box
Pilot E95s boxed; the Vanishing Point comes in the same box

As well as its history, pricing and availability of the pen is sadly also inconsistent. In Japan, the pen retails for ¥10,000 (around $90 at the time of writing), but in the United States its retails at $170, although The Goulet Pen Company sells it at $136. I definitely prefer both the Lamy 2000 and Pilot Vanishing Point, which are priced similarly, which typically sport rhodium-plated and black-ionized gold nibs.

Older Pilot Elites, in varying conditions, are also available on eBay for prices that dip below $30, so this is a more affordable option. However, as a great modern introduction to gold nibs, the E95s serves nicely.