Nim frontend

Hey all!

Writing to introduce nlvm - a Nim language frontend for LLVM.

Nim is nice little statically typed language that has been around for a while, and nlvm is a compiler for it, itself written in Nim. It has lots of features in particular related to compile-time compilation including strong macro support, generics etc.

From a technical point of view, the “upstream” Nim compiler compiles Nim code into C and then passes it to a regular C compiler - nlvm shortcuts the process by going straight to LLVM IR - thus, from Nim’s point of view, nlvm is a “backend” that outputs IR instead of C and from LLVM’s point of view, it’s a language frontend like clang.

This setup in particular ensures a high degree of compatiblity with the langauge, avoiding the reimplementation of parsing, semantics etc and instead focuses on generating highly efficient IR compared to the C backend that must take into account the limitations of C itself.

Looking at features relevant to the LLVM integration, Nim is garbage collected and has Python-like exceptions in the language - nlvm does not (yet) use the GC feature set of LLVM, but it does integrate with the DWARF exception handling model taking inspiration from the clang implementation and adding finally support on top.

The frontend also supports JIT via ORC allowing Nim code to be used much like scripts.

Notably, the frontend is quite small - less than 10kLOC if you count only the nlvm parts - for anyone interested in a non-trivial but still complete frontend implementation, this might be just the thing - the integration is based on the LLVM-C exports in llvm.

In terms of future work, there are lots of interesting areas:

  • more platforms (currently only x86_64 linux and wasm are supported)
  • more dynamic / reloadable JIT (aka REPL)
  • compilation caches like LTO does
  • using ORC instead of the internal Nim VM for compile-time work
  • dedicated optimization pipeline tuned to Nim
  • your idea here :slight_smile:

With that, a big thank you to everyone that’s worked on LLVM and I hope to see you around :wink: