-1

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. – Robert Harvey 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 – Robert Bräutigam Apr 3 '18 at 17:51
  • Take also a look at GCCJIT. It is a good (but less known) competitor to LLVM – Basile Starynkevitch Apr 3 '18 at 19:36
  • If your compiler's language is broadly compatible, you could target JVM, so the output of your compiler would be executable anywhere Java is available. This approach would also fix the biggest problem for a random compiler's portability; that it also needs a defined execution environment. – ddyer Apr 4 '18 at 23:49
10

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.