LangImpl10.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. :orphan:
  2. ======================================================
  3. Kaleidoscope: Conclusion and other useful LLVM tidbits
  4. ======================================================
  5. .. contents::
  6. :local:
  7. Tutorial Conclusion
  8. ===================
  9. Welcome to the final chapter of the "`Implementing a language with
  10. LLVM <index.html>`_" tutorial. In the course of this tutorial, we have
  11. grown our little Kaleidoscope language from being a useless toy, to
  12. being a semi-interesting (but probably still useless) toy. :)
  13. It is interesting to see how far we've come, and how little code it has
  14. taken. We built the entire lexer, parser, AST, code generator, an
  15. interactive run-loop (with a JIT!), and emitted debug information in
  16. standalone executables - all in under 1000 lines of (non-comment/non-blank)
  17. code.
  18. Our little language supports a couple of interesting features: it
  19. supports user defined binary and unary operators, it uses JIT
  20. compilation for immediate evaluation, and it supports a few control flow
  21. constructs with SSA construction.
  22. Part of the idea of this tutorial was to show you how easy and fun it
  23. can be to define, build, and play with languages. Building a compiler
  24. need not be a scary or mystical process! Now that you've seen some of
  25. the basics, I strongly encourage you to take the code and hack on it.
  26. For example, try adding:
  27. - **global variables** - While global variables have questional value
  28. in modern software engineering, they are often useful when putting
  29. together quick little hacks like the Kaleidoscope compiler itself.
  30. Fortunately, our current setup makes it very easy to add global
  31. variables: just have value lookup check to see if an unresolved
  32. variable is in the global variable symbol table before rejecting it.
  33. To create a new global variable, make an instance of the LLVM
  34. ``GlobalVariable`` class.
  35. - **typed variables** - Kaleidoscope currently only supports variables
  36. of type double. This gives the language a very nice elegance, because
  37. only supporting one type means that you never have to specify types.
  38. Different languages have different ways of handling this. The easiest
  39. way is to require the user to specify types for every variable
  40. definition, and record the type of the variable in the symbol table
  41. along with its Value\*.
  42. - **arrays, structs, vectors, etc** - Once you add types, you can start
  43. extending the type system in all sorts of interesting ways. Simple
  44. arrays are very easy and are quite useful for many different
  45. applications. Adding them is mostly an exercise in learning how the
  46. LLVM `getelementptr <../LangRef.html#getelementptr-instruction>`_ instruction
  47. works: it is so nifty/unconventional, it `has its own
  48. FAQ <../GetElementPtr.html>`_!
  49. - **standard runtime** - Our current language allows the user to access
  50. arbitrary external functions, and we use it for things like "printd"
  51. and "putchard". As you extend the language to add higher-level
  52. constructs, often these constructs make the most sense if they are
  53. lowered to calls into a language-supplied runtime. For example, if
  54. you add hash tables to the language, it would probably make sense to
  55. add the routines to a runtime, instead of inlining them all the way.
  56. - **memory management** - Currently we can only access the stack in
  57. Kaleidoscope. It would also be useful to be able to allocate heap
  58. memory, either with calls to the standard libc malloc/free interface
  59. or with a garbage collector. If you would like to use garbage
  60. collection, note that LLVM fully supports `Accurate Garbage
  61. Collection <../GarbageCollection.html>`_ including algorithms that
  62. move objects and need to scan/update the stack.
  63. - **exception handling support** - LLVM supports generation of `zero
  64. cost exceptions <../ExceptionHandling.html>`_ which interoperate with
  65. code compiled in other languages. You could also generate code by
  66. implicitly making every function return an error value and checking
  67. it. You could also make explicit use of setjmp/longjmp. There are
  68. many different ways to go here.
  69. - **object orientation, generics, database access, complex numbers,
  70. geometric programming, ...** - Really, there is no end of crazy
  71. features that you can add to the language.
  72. - **unusual domains** - We've been talking about applying LLVM to a
  73. domain that many people are interested in: building a compiler for a
  74. specific language. However, there are many other domains that can use
  75. compiler technology that are not typically considered. For example,
  76. LLVM has been used to implement OpenGL graphics acceleration,
  77. translate C++ code to ActionScript, and many other cute and clever
  78. things. Maybe you will be the first to JIT compile a regular
  79. expression interpreter into native code with LLVM?
  80. Have fun - try doing something crazy and unusual. Building a language
  81. like everyone else always has, is much less fun than trying something a
  82. little crazy or off the wall and seeing how it turns out. If you get
  83. stuck or want to talk about it, feel free to email the `llvm-dev mailing
  84. list <http://lists.llvm.org/mailman/listinfo/llvm-dev>`_: it has lots
  85. of people who are interested in languages and are often willing to help
  86. out.
  87. Before we end this tutorial, I want to talk about some "tips and tricks"
  88. for generating LLVM IR. These are some of the more subtle things that
  89. may not be obvious, but are very useful if you want to take advantage of
  90. LLVM's capabilities.
  91. Properties of the LLVM IR
  92. =========================
  93. We have a couple of common questions about code in the LLVM IR form -
  94. let's just get these out of the way right now, shall we?
  95. Target Independence
  96. -------------------
  97. Kaleidoscope is an example of a "portable language": any program written
  98. in Kaleidoscope will work the same way on any target that it runs on.
  99. Many other languages have this property, e.g. lisp, java, haskell,
  100. javascript, python, etc (note that while these languages are portable,
  101. not all their libraries are).
  102. One nice aspect of LLVM is that it is often capable of preserving target
  103. independence in the IR: you can take the LLVM IR for a
  104. Kaleidoscope-compiled program and run it on any target that LLVM
  105. supports, even emitting C code and compiling that on targets that LLVM
  106. doesn't support natively. You can trivially tell that the Kaleidoscope
  107. compiler generates target-independent code because it never queries for
  108. any target-specific information when generating code.
  109. The fact that LLVM provides a compact, target-independent,
  110. representation for code gets a lot of people excited. Unfortunately,
  111. these people are usually thinking about C or a language from the C
  112. family when they are asking questions about language portability. I say
  113. "unfortunately", because there is really no way to make (fully general)
  114. C code portable, other than shipping the source code around (and of
  115. course, C source code is not actually portable in general either - ever
  116. port a really old application from 32- to 64-bits?).
  117. The problem with C (again, in its full generality) is that it is heavily
  118. laden with target specific assumptions. As one simple example, the
  119. preprocessor often destructively removes target-independence from the
  120. code when it processes the input text:
  121. .. code-block:: c
  122. #ifdef __i386__
  123. int X = 1;
  124. #else
  125. int X = 42;
  126. #endif
  127. While it is possible to engineer more and more complex solutions to
  128. problems like this, it cannot be solved in full generality in a way that
  129. is better than shipping the actual source code.
  130. That said, there are interesting subsets of C that can be made portable.
  131. If you are willing to fix primitive types to a fixed size (say int =
  132. 32-bits, and long = 64-bits), don't care about ABI compatibility with
  133. existing binaries, and are willing to give up some other minor features,
  134. you can have portable code. This can make sense for specialized domains
  135. such as an in-kernel language.
  136. Safety Guarantees
  137. -----------------
  138. Many of the languages above are also "safe" languages: it is impossible
  139. for a program written in Java to corrupt its address space and crash the
  140. process (assuming the JVM has no bugs). Safety is an interesting
  141. property that requires a combination of language design, runtime
  142. support, and often operating system support.
  143. It is certainly possible to implement a safe language in LLVM, but LLVM
  144. IR does not itself guarantee safety. The LLVM IR allows unsafe pointer
  145. casts, use after free bugs, buffer over-runs, and a variety of other
  146. problems. Safety needs to be implemented as a layer on top of LLVM and,
  147. conveniently, several groups have investigated this. Ask on the `llvm-dev
  148. mailing list <http://lists.llvm.org/mailman/listinfo/llvm-dev>`_ if
  149. you are interested in more details.
  150. Language-Specific Optimizations
  151. -------------------------------
  152. One thing about LLVM that turns off many people is that it does not
  153. solve all the world's problems in one system. One specific
  154. complaint is that people perceive LLVM as being incapable of performing
  155. high-level language-specific optimization: LLVM "loses too much
  156. information". Here are a few observations about this:
  157. First, you're right that LLVM does lose information. For example, as of
  158. this writing, there is no way to distinguish in the LLVM IR whether an
  159. SSA-value came from a C "int" or a C "long" on an ILP32 machine (other
  160. than debug info). Both get compiled down to an 'i32' value and the
  161. information about what it came from is lost. The more general issue
  162. here, is that the LLVM type system uses "structural equivalence" instead
  163. of "name equivalence". Another place this surprises people is if you
  164. have two types in a high-level language that have the same structure
  165. (e.g. two different structs that have a single int field): these types
  166. will compile down into a single LLVM type and it will be impossible to
  167. tell what it came from.
  168. Second, while LLVM does lose information, LLVM is not a fixed target: we
  169. continue to enhance and improve it in many different ways. In addition
  170. to adding new features (LLVM did not always support exceptions or debug
  171. info), we also extend the IR to capture important information for
  172. optimization (e.g. whether an argument is sign or zero extended,
  173. information about pointers aliasing, etc). Many of the enhancements are
  174. user-driven: people want LLVM to include some specific feature, so they
  175. go ahead and extend it.
  176. Third, it is *possible and easy* to add language-specific optimizations,
  177. and you have a number of choices in how to do it. As one trivial
  178. example, it is easy to add language-specific optimization passes that
  179. "know" things about code compiled for a language. In the case of the C
  180. family, there is an optimization pass that "knows" about the standard C
  181. library functions. If you call "exit(0)" in main(), it knows that it is
  182. safe to optimize that into "return 0;" because C specifies what the
  183. 'exit' function does.
  184. In addition to simple library knowledge, it is possible to embed a
  185. variety of other language-specific information into the LLVM IR. If you
  186. have a specific need and run into a wall, please bring the topic up on
  187. the llvm-dev list. At the very worst, you can always treat LLVM as if it
  188. were a "dumb code generator" and implement the high-level optimizations
  189. you desire in your front-end, on the language-specific AST.
  190. Tips and Tricks
  191. ===============
  192. There is a variety of useful tips and tricks that you come to know after
  193. working on/with LLVM that aren't obvious at first glance. Instead of
  194. letting everyone rediscover them, this section talks about some of these
  195. issues.
  196. Implementing portable offsetof/sizeof
  197. -------------------------------------
  198. One interesting thing that comes up, if you are trying to keep the code
  199. generated by your compiler "target independent", is that you often need
  200. to know the size of some LLVM type or the offset of some field in an
  201. llvm structure. For example, you might need to pass the size of a type
  202. into a function that allocates memory.
  203. Unfortunately, this can vary widely across targets: for example the
  204. width of a pointer is trivially target-specific. However, there is a
  205. `clever way to use the getelementptr
  206. instruction <http://nondot.org/sabre/LLVMNotes/SizeOf-OffsetOf-VariableSizedStructs.txt>`_
  207. that allows you to compute this in a portable way.
  208. Garbage Collected Stack Frames
  209. ------------------------------
  210. Some languages want to explicitly manage their stack frames, often so
  211. that they are garbage collected or to allow easy implementation of
  212. closures. There are often better ways to implement these features than
  213. explicit stack frames, but `LLVM does support
  214. them, <http://nondot.org/sabre/LLVMNotes/ExplicitlyManagedStackFrames.txt>`_
  215. if you want. It requires your front-end to convert the code into
  216. `Continuation Passing
  217. Style <http://en.wikipedia.org/wiki/Continuation-passing_style>`_ and
  218. the use of tail calls (which LLVM also supports).