LangImpl09.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. :orphan:
  2. ======================================
  3. Kaleidoscope: Adding Debug Information
  4. ======================================
  5. .. contents::
  6. :local:
  7. Chapter 9 Introduction
  8. ======================
  9. Welcome to Chapter 9 of the "`Implementing a language with
  10. LLVM <index.html>`_" tutorial. In chapters 1 through 8, we've built a
  11. decent little programming language with functions and variables.
  12. What happens if something goes wrong though, how do you debug your
  13. program?
  14. Source level debugging uses formatted data that helps a debugger
  15. translate from binary and the state of the machine back to the
  16. source that the programmer wrote. In LLVM we generally use a format
  17. called `DWARF <http://dwarfstd.org>`_. DWARF is a compact encoding
  18. that represents types, source locations, and variable locations.
  19. The short summary of this chapter is that we'll go through the
  20. various things you have to add to a programming language to
  21. support debug info, and how you translate that into DWARF.
  22. Caveat: For now we can't debug via the JIT, so we'll need to compile
  23. our program down to something small and standalone. As part of this
  24. we'll make a few modifications to the running of the language and
  25. how programs are compiled. This means that we'll have a source file
  26. with a simple program written in Kaleidoscope rather than the
  27. interactive JIT. It does involve a limitation that we can only
  28. have one "top level" command at a time to reduce the number of
  29. changes necessary.
  30. Here's the sample program we'll be compiling:
  31. .. code-block:: python
  32. def fib(x)
  33. if x < 3 then
  34. 1
  35. else
  36. fib(x-1)+fib(x-2);
  37. fib(10)
  38. Why is this a hard problem?
  39. ===========================
  40. Debug information is a hard problem for a few different reasons - mostly
  41. centered around optimized code. First, optimization makes keeping source
  42. locations more difficult. In LLVM IR we keep the original source location
  43. for each IR level instruction on the instruction. Optimization passes
  44. should keep the source locations for newly created instructions, but merged
  45. instructions only get to keep a single location - this can cause jumping
  46. around when stepping through optimized programs. Secondly, optimization
  47. can move variables in ways that are either optimized out, shared in memory
  48. with other variables, or difficult to track. For the purposes of this
  49. tutorial we're going to avoid optimization (as you'll see with one of the
  50. next sets of patches).
  51. Ahead-of-Time Compilation Mode
  52. ==============================
  53. To highlight only the aspects of adding debug information to a source
  54. language without needing to worry about the complexities of JIT debugging
  55. we're going to make a few changes to Kaleidoscope to support compiling
  56. the IR emitted by the front end into a simple standalone program that
  57. you can execute, debug, and see results.
  58. First we make our anonymous function that contains our top level
  59. statement be our "main":
  60. .. code-block:: udiff
  61. - auto Proto = std::make_unique<PrototypeAST>("", std::vector<std::string>());
  62. + auto Proto = std::make_unique<PrototypeAST>("main", std::vector<std::string>());
  63. just with the simple change of giving it a name.
  64. Then we're going to remove the command line code wherever it exists:
  65. .. code-block:: udiff
  66. @@ -1129,7 +1129,6 @@ static void HandleTopLevelExpression() {
  67. /// top ::= definition | external | expression | ';'
  68. static void MainLoop() {
  69. while (1) {
  70. - fprintf(stderr, "ready> ");
  71. switch (CurTok) {
  72. case tok_eof:
  73. return;
  74. @@ -1184,7 +1183,6 @@ int main() {
  75. BinopPrecedence['*'] = 40; // highest.
  76. // Prime the first token.
  77. - fprintf(stderr, "ready> ");
  78. getNextToken();
  79. Lastly we're going to disable all of the optimization passes and the JIT so
  80. that the only thing that happens after we're done parsing and generating
  81. code is that the LLVM IR goes to standard error:
  82. .. code-block:: udiff
  83. @@ -1108,17 +1108,8 @@ static void HandleExtern() {
  84. static void HandleTopLevelExpression() {
  85. // Evaluate a top-level expression into an anonymous function.
  86. if (auto FnAST = ParseTopLevelExpr()) {
  87. - if (auto *FnIR = FnAST->codegen()) {
  88. - // We're just doing this to make sure it executes.
  89. - TheExecutionEngine->finalizeObject();
  90. - // JIT the function, returning a function pointer.
  91. - void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
  92. -
  93. - // Cast it to the right type (takes no arguments, returns a double) so we
  94. - // can call it as a native function.
  95. - double (*FP)() = (double (*)())(intptr_t)FPtr;
  96. - // Ignore the return value for this.
  97. - (void)FP;
  98. + if (!F->codegen()) {
  99. + fprintf(stderr, "Error generating code for top level expr");
  100. }
  101. } else {
  102. // Skip token for error recovery.
  103. @@ -1439,11 +1459,11 @@ int main() {
  104. // target lays out data structures.
  105. TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
  106. OurFPM.add(new DataLayoutPass());
  107. +#if 0
  108. OurFPM.add(createBasicAliasAnalysisPass());
  109. // Promote allocas to registers.
  110. OurFPM.add(createPromoteMemoryToRegisterPass());
  111. @@ -1218,7 +1210,7 @@ int main() {
  112. OurFPM.add(createGVNPass());
  113. // Simplify the control flow graph (deleting unreachable blocks, etc).
  114. OurFPM.add(createCFGSimplificationPass());
  115. -
  116. + #endif
  117. OurFPM.doInitialization();
  118. // Set the global so the code gen can use this.
  119. This relatively small set of changes get us to the point that we can compile
  120. our piece of Kaleidoscope language down to an executable program via this
  121. command line:
  122. .. code-block:: bash
  123. Kaleidoscope-Ch9 < fib.ks | & clang -x ir -
  124. which gives an a.out/a.exe in the current working directory.
  125. Compile Unit
  126. ============
  127. The top level container for a section of code in DWARF is a compile unit.
  128. This contains the type and function data for an individual translation unit
  129. (read: one file of source code). So the first thing we need to do is
  130. construct one for our fib.ks file.
  131. DWARF Emission Setup
  132. ====================
  133. Similar to the ``IRBuilder`` class we have a
  134. `DIBuilder <http://llvm.org/doxygen/classllvm_1_1DIBuilder.html>`_ class
  135. that helps in constructing debug metadata for an LLVM IR file. It
  136. corresponds 1:1 similarly to ``IRBuilder`` and LLVM IR, but with nicer names.
  137. Using it does require that you be more familiar with DWARF terminology than
  138. you needed to be with ``IRBuilder`` and ``Instruction`` names, but if you
  139. read through the general documentation on the
  140. `Metadata Format <http://llvm.org/docs/SourceLevelDebugging.html>`_ it
  141. should be a little more clear. We'll be using this class to construct all
  142. of our IR level descriptions. Construction for it takes a module so we
  143. need to construct it shortly after we construct our module. We've left it
  144. as a global static variable to make it a bit easier to use.
  145. Next we're going to create a small container to cache some of our frequent
  146. data. The first will be our compile unit, but we'll also write a bit of
  147. code for our one type since we won't have to worry about multiple typed
  148. expressions:
  149. .. code-block:: c++
  150. static DIBuilder *DBuilder;
  151. struct DebugInfo {
  152. DICompileUnit *TheCU;
  153. DIType *DblTy;
  154. DIType *getDoubleTy();
  155. } KSDbgInfo;
  156. DIType *DebugInfo::getDoubleTy() {
  157. if (DblTy)
  158. return DblTy;
  159. DblTy = DBuilder->createBasicType("double", 64, dwarf::DW_ATE_float);
  160. return DblTy;
  161. }
  162. And then later on in ``main`` when we're constructing our module:
  163. .. code-block:: c++
  164. DBuilder = new DIBuilder(*TheModule);
  165. KSDbgInfo.TheCU = DBuilder->createCompileUnit(
  166. dwarf::DW_LANG_C, DBuilder->createFile("fib.ks", "."),
  167. "Kaleidoscope Compiler", 0, "", 0);
  168. There are a couple of things to note here. First, while we're producing a
  169. compile unit for a language called Kaleidoscope we used the language
  170. constant for C. This is because a debugger wouldn't necessarily understand
  171. the calling conventions or default ABI for a language it doesn't recognize
  172. and we follow the C ABI in our LLVM code generation so it's the closest
  173. thing to accurate. This ensures we can actually call functions from the
  174. debugger and have them execute. Secondly, you'll see the "fib.ks" in the
  175. call to ``createCompileUnit``. This is a default hard coded value since
  176. we're using shell redirection to put our source into the Kaleidoscope
  177. compiler. In a usual front end you'd have an input file name and it would
  178. go there.
  179. One last thing as part of emitting debug information via DIBuilder is that
  180. we need to "finalize" the debug information. The reasons are part of the
  181. underlying API for DIBuilder, but make sure you do this near the end of
  182. main:
  183. .. code-block:: c++
  184. DBuilder->finalize();
  185. before you dump out the module.
  186. Functions
  187. =========
  188. Now that we have our ``Compile Unit`` and our source locations, we can add
  189. function definitions to the debug info. So in ``PrototypeAST::codegen()`` we
  190. add a few lines of code to describe a context for our subprogram, in this
  191. case the "File", and the actual definition of the function itself.
  192. So the context:
  193. .. code-block:: c++
  194. DIFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU.getFilename(),
  195. KSDbgInfo.TheCU.getDirectory());
  196. giving us an DIFile and asking the ``Compile Unit`` we created above for the
  197. directory and filename where we are currently. Then, for now, we use some
  198. source locations of 0 (since our AST doesn't currently have source location
  199. information) and construct our function definition:
  200. .. code-block:: c++
  201. DIScope *FContext = Unit;
  202. unsigned LineNo = 0;
  203. unsigned ScopeLine = 0;
  204. DISubprogram *SP = DBuilder->createFunction(
  205. FContext, P.getName(), StringRef(), Unit, LineNo,
  206. CreateFunctionType(TheFunction->arg_size(), Unit),
  207. false /* internal linkage */, true /* definition */, ScopeLine,
  208. DINode::FlagPrototyped, false);
  209. TheFunction->setSubprogram(SP);
  210. and we now have an DISubprogram that contains a reference to all of our
  211. metadata for the function.
  212. Source Locations
  213. ================
  214. The most important thing for debug information is accurate source location -
  215. this makes it possible to map your source code back. We have a problem though,
  216. Kaleidoscope really doesn't have any source location information in the lexer
  217. or parser so we'll need to add it.
  218. .. code-block:: c++
  219. struct SourceLocation {
  220. int Line;
  221. int Col;
  222. };
  223. static SourceLocation CurLoc;
  224. static SourceLocation LexLoc = {1, 0};
  225. static int advance() {
  226. int LastChar = getchar();
  227. if (LastChar == '\n' || LastChar == '\r') {
  228. LexLoc.Line++;
  229. LexLoc.Col = 0;
  230. } else
  231. LexLoc.Col++;
  232. return LastChar;
  233. }
  234. In this set of code we've added some functionality on how to keep track of the
  235. line and column of the "source file". As we lex every token we set our current
  236. current "lexical location" to the assorted line and column for the beginning
  237. of the token. We do this by overriding all of the previous calls to
  238. ``getchar()`` with our new ``advance()`` that keeps track of the information
  239. and then we have added to all of our AST classes a source location:
  240. .. code-block:: c++
  241. class ExprAST {
  242. SourceLocation Loc;
  243. public:
  244. ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
  245. virtual ~ExprAST() {}
  246. virtual Value* codegen() = 0;
  247. int getLine() const { return Loc.Line; }
  248. int getCol() const { return Loc.Col; }
  249. virtual raw_ostream &dump(raw_ostream &out, int ind) {
  250. return out << ':' << getLine() << ':' << getCol() << '\n';
  251. }
  252. that we pass down through when we create a new expression:
  253. .. code-block:: c++
  254. LHS = std::make_unique<BinaryExprAST>(BinLoc, BinOp, std::move(LHS),
  255. std::move(RHS));
  256. giving us locations for each of our expressions and variables.
  257. To make sure that every instruction gets proper source location information,
  258. we have to tell ``Builder`` whenever we're at a new source location.
  259. We use a small helper function for this:
  260. .. code-block:: c++
  261. void DebugInfo::emitLocation(ExprAST *AST) {
  262. DIScope *Scope;
  263. if (LexicalBlocks.empty())
  264. Scope = TheCU;
  265. else
  266. Scope = LexicalBlocks.back();
  267. Builder.SetCurrentDebugLocation(
  268. DebugLoc::get(AST->getLine(), AST->getCol(), Scope));
  269. }
  270. This both tells the main ``IRBuilder`` where we are, but also what scope
  271. we're in. The scope can either be on compile-unit level or be the nearest
  272. enclosing lexical block like the current function.
  273. To represent this we create a stack of scopes:
  274. .. code-block:: c++
  275. std::vector<DIScope *> LexicalBlocks;
  276. and push the scope (function) to the top of the stack when we start
  277. generating the code for each function:
  278. .. code-block:: c++
  279. KSDbgInfo.LexicalBlocks.push_back(SP);
  280. Also, we may not forget to pop the scope back off of the scope stack at the
  281. end of the code generation for the function:
  282. .. code-block:: c++
  283. // Pop off the lexical block for the function since we added it
  284. // unconditionally.
  285. KSDbgInfo.LexicalBlocks.pop_back();
  286. Then we make sure to emit the location every time we start to generate code
  287. for a new AST object:
  288. .. code-block:: c++
  289. KSDbgInfo.emitLocation(this);
  290. Variables
  291. =========
  292. Now that we have functions, we need to be able to print out the variables
  293. we have in scope. Let's get our function arguments set up so we can get
  294. decent backtraces and see how our functions are being called. It isn't
  295. a lot of code, and we generally handle it when we're creating the
  296. argument allocas in ``FunctionAST::codegen``.
  297. .. code-block:: c++
  298. // Record the function arguments in the NamedValues map.
  299. NamedValues.clear();
  300. unsigned ArgIdx = 0;
  301. for (auto &Arg : TheFunction->args()) {
  302. // Create an alloca for this variable.
  303. AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
  304. // Create a debug descriptor for the variable.
  305. DILocalVariable *D = DBuilder->createParameterVariable(
  306. SP, Arg.getName(), ++ArgIdx, Unit, LineNo, KSDbgInfo.getDoubleTy(),
  307. true);
  308. DBuilder->insertDeclare(Alloca, D, DBuilder->createExpression(),
  309. DebugLoc::get(LineNo, 0, SP),
  310. Builder.GetInsertBlock());
  311. // Store the initial value into the alloca.
  312. Builder.CreateStore(&Arg, Alloca);
  313. // Add arguments to variable symbol table.
  314. NamedValues[Arg.getName()] = Alloca;
  315. }
  316. Here we're first creating the variable, giving it the scope (``SP``),
  317. the name, source location, type, and since it's an argument, the argument
  318. index. Next, we create an ``lvm.dbg.declare`` call to indicate at the IR
  319. level that we've got a variable in an alloca (and it gives a starting
  320. location for the variable), and setting a source location for the
  321. beginning of the scope on the declare.
  322. One interesting thing to note at this point is that various debuggers have
  323. assumptions based on how code and debug information was generated for them
  324. in the past. In this case we need to do a little bit of a hack to avoid
  325. generating line information for the function prologue so that the debugger
  326. knows to skip over those instructions when setting a breakpoint. So in
  327. ``FunctionAST::CodeGen`` we add some more lines:
  328. .. code-block:: c++
  329. // Unset the location for the prologue emission (leading instructions with no
  330. // location in a function are considered part of the prologue and the debugger
  331. // will run past them when breaking on a function)
  332. KSDbgInfo.emitLocation(nullptr);
  333. and then emit a new location when we actually start generating code for the
  334. body of the function:
  335. .. code-block:: c++
  336. KSDbgInfo.emitLocation(Body.get());
  337. With this we have enough debug information to set breakpoints in functions,
  338. print out argument variables, and call functions. Not too bad for just a
  339. few simple lines of code!
  340. Full Code Listing
  341. =================
  342. Here is the complete code listing for our running example, enhanced with
  343. debug information. To build this example, use:
  344. .. code-block:: bash
  345. # Compile
  346. clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core mcjit native` -O3 -o toy
  347. # Run
  348. ./toy
  349. Here is the code:
  350. .. literalinclude:: ../../../examples/Kaleidoscope/Chapter9/toy.cpp
  351. :language: c++
  352. `Next: Conclusion and other useful LLVM tidbits <LangImpl10.html>`_