I am writing a simple compiler. I have written lexer and parser and it now generates assembly code from given code. Now I need to write an assembler which generates machine code. But the problem is that I want to make my compiler portable. it should run at least on major architectures. One way of doing it is writing different assemblers for each architecture, but it seems too difficult and time-consuming.

Is there a "least common denominator" for most architectures that I could work with to make my compiler portable? For instance, is it only necessary to "write one backend that produces LLVM IR instead of assembly"?

  • 5
    Compile to some intermediate language, and then write an interpreter or just-in-time compiler for that intermediate language on each of your target platforms. See here for some ideas. You can also use C as your compilation target and recompile using each architecture's native C compiler. Apr 3 '18 at 17:12
  • 2
    To re-emphasize Robert's suggestion which he hid in a link: the LLVM compiler framework gives you a production-grade compiler backend across many architectures. So for your compiler, you only have to write one backend that produces LLVM IR instead of assembly, and you get the rest for free.
    – amon
    Apr 3 '18 at 17:50
  • 1
    Take a look at llvm.org Apr 3 '18 at 17:51
  • Take also a look at GCCJIT. It is a good (but less known) competitor to LLVM Apr 3 '18 at 19:36
  • 1
    I narrowed the question by asking for a "least common denominator" (and giving a plausible example of one), and wonder if the question can be reopened in its current form.
    – Tom Au
    Jul 31 '18 at 21:49

You cannot make a portable compiler (not in the sense you dream of).

You could make a compiler for a particular target machine -or language- (and that machine might even be something like LLVM or GCCJIT or Parrot which provide portability by defining some abstract model or intermediate language). It is common to compile to C (that is to choose C as your target language, leaving the burden of object code generation to the system's C compiler).

You could make a compiler with several backends (perhaps configurable at configure time, or even at run time). For example, x86-64, ARM, etc.. (and it also depends upon the target operating system and ABI). That does not make your compiler portable.

You might (or not) want to define some common (i.e. target neutral) intermediate representations in your compiler (and you could optimize with these intermediate representations).

Read the Dragon Book.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.