User Tools

Site Tools


compilers:codgen_tutorial

This is an old revision of the document!


A PCRE internal error occured. This might be caused by a faulty plugin

=== Tutorial on code generation === == Step 1: Preparation == * If you have not completed the semantic analyser, [[http://deva.web.elte.hu/compilers/semantic-analyser.zip|download this version]] and test it on all [[http://deva.web.elte.hu/compilers/while-tests.zip|test files]]. * Review the lecture notes on the [[compilers:assembly|assembly]] and [[compilers:codegen|code generation]] topics and make sure you understand the concepts. == Step 2: Extend the symbol table == * Create a function in the Parser class that is able to return a fresh label (for example ''label0'', ''label1'', ''label2'' ...) each time it is called. (Use a static int attribute to store the label index and use the ''stringstream'' type build the label.) * Add a ''string label;'' field to the data type stored in the symbol table. * Change the constructor of that data type to get the label as parameter. * Change the C++ code at the declaration rules so that a new label is generated for each declaration and passed to the constructor. == Step 3: Change the semantic type of expressions == * Create a struct or class in ''semantics.h'' that is able to store both the //type// of an expression and also its //generated code//. Create a two-parameter constructor for this type. * Make the new struct/class the semantic value of ''expression''s. (See the ''%type'' and the ''%union'' in ''while.y''.) * Make the C++ code fragments in the expression-related rules consistent with the above change. == Step 4: Generate code for expressions == * Implement the code generation templates for expressions. == Step 5: Generate code for instructions == * Add semantic type of string to //instruction//s. * Implement the code generation templates for instructions. == Step 6: Generate code for variable declarations == * In the start rule, iterate through the symbol table and generate a ''label: resd 1'' or ''label: resb 1'' line for each variable. * Concatenate these lines to form the ''section .bss'' together. == Step 7: Completion == * In the start rule, put together the code of the instructions (in the ''.text'' section) and the code of the declarations (in the ''.bss'' section), and add the necessary ''extern'' and ''global'' declarations at the beginning to form a complete assembly file. * Test the generated code using ''nasm'' and running the executable.

compilers/codgen_tutorial.1481796297.txt.gz · Last modified: 2016/12/15 11:04 by deva