Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef CODEGEN_H
- #define CODEGEN_H
- #define __STDC_LIMIT_MACROS
- #define __STDC_CONSTANT_MACROS
- #include <llvm/Type.h>
- #include <llvm/Function.h>
- #include <stack>
- #include <map>
- #include <string>
- #include <tr1/memory>
- #include <iostream>
- class Program;
- class CodeScope;
- typedef std::tr1::shared_ptr<CodeScope> CodeScopePtr;
- /**
- code scope (variables etc.)
- */
- class CodeScope
- {
- public:
- CodeScope(llvm::BasicBlock *block, CodeScope *parent = NULL):
- m_block(block),
- m_parent(parent)
- {}
- ~CodeScope()
- {}
- /**
- TODO: switch to lookup() calls only
- check if scope contains declaration
- \param name variable
- */
- inline bool contains(const std::string &name) const
- {
- if (m_decls.find(name) == m_decls.end())
- {
- // look in parent's
- if (hasParent())
- return m_parent->contains(name);
- else
- return false;
- }
- return true;
- }
- inline llvm::BasicBlock *block() const
- {
- return m_block;
- }
- /**
- get variable type
- \param name variable
- */
- inline llvm::Value *lookup(const std::string &name) const
- {
- if (m_decls.find(name) == m_decls.end())
- {
- if (hasParent())
- return m_parent->lookup(name);
- else
- return NULL;
- }
- return m_decls.at(name);
- }
- inline void addDeclaration(const std::string &name, llvm::Value *v)
- {
- m_decls[name] = v;
- }
- private:
- /// check if scope has parent
- inline bool hasParent() const { return m_parent != NULL; }
- /// declarations
- std::map<std::string, llvm::Value *> m_decls;
- /// associated block
- llvm::BasicBlock *m_block;
- /// parent scope
- CodeScope *m_parent;
- };
- class CodeGenerator
- {
- public:
- CodeGenerator():
- m_module(NULL),
- m_mainFunction(NULL),
- m_error(false)
- {
- }
- /// generate
- bool generate(Program *program);
- /** add error to output
- \param line number
- \param msg error message
- */
- void error(const std::string &msg, unsigned int line = 0);
- /** add warning to output
- \param line number
- \param msg warning message
- */
- void warning(const std::string &msg, unsigned int line = 0);
- /// run program
- void run();
- /// get current local scope
- inline CodeScopePtr local() const
- {
- return m_scopes.top();
- }
- /// get current global scope
- inline CodeScopePtr global() const
- {
- return m_global;
- }
- inline void pushScope(CodeScope *scope)
- {
- m_scopes.push(CodeScopePtr(scope));
- }
- inline void popScope()
- {
- m_scopes.pop();
- }
- inline llvm::Module *module() const
- {
- return m_module;
- }
- inline llvm::Function *function() const
- {
- return m_mainFunction;
- }
- private:
- /// scope stack
- std::stack<CodeScopePtr> m_scopes;
- /// global scope
- CodeScopePtr m_global;
- /// module
- llvm::Module *m_module;
- /// main function
- llvm::Function *m_mainFunction;
- /// error flag
- bool m_error;
- };
- #endif // CODEGEN_H
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement