lowering.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_TOOLCHAIN_LOWERING_LOWERING_H_
  5. #define CARBON_TOOLCHAIN_LOWERING_LOWERING_H_
  6. #include "llvm/IR/IRBuilder.h"
  7. #include "llvm/IR/LLVMContext.h"
  8. #include "llvm/IR/Module.h"
  9. #include "toolchain/semantics/semantics_ir.h"
  10. #include "toolchain/semantics/semantics_node.h"
  11. namespace Carbon {
  12. // Use LowerToLLVM rather than calling this directly.
  13. //
  14. // This carries state for lowering. `Run()` should only be called once, and
  15. // handles the main execution.
  16. class Lowering {
  17. public:
  18. explicit Lowering(llvm::LLVMContext& llvm_context,
  19. llvm::StringRef module_name,
  20. const SemanticsIR& semantics_ir);
  21. // Lowers the SemanticsIR to LLVM IR.
  22. auto Run() -> std::unique_ptr<llvm::Module>;
  23. private:
  24. // Declare handlers for each SemanticsIR node.
  25. #define CARBON_SEMANTICS_NODE_KIND(Name) \
  26. auto Handle##Name##Node(SemanticsNodeId node_id, SemanticsNode node)->void;
  27. #include "toolchain/semantics/semantics_node_kind.def"
  28. // Runs lowering for a block.
  29. auto LowerBlock(SemanticsNodeBlockId block_id) -> void;
  30. // Returns a type for the given node.
  31. auto LowerNodeToType(SemanticsNodeId node_id) -> llvm::Type*;
  32. // State for building the LLVM IR.
  33. llvm::LLVMContext* llvm_context_;
  34. std::unique_ptr<llvm::Module> llvm_module_;
  35. llvm::IRBuilder<> builder_;
  36. // The input Semantics IR.
  37. const SemanticsIR* const semantics_ir_;
  38. // Blocks which we've observed and need to lower.
  39. llvm::SmallVector<std::pair<llvm::BasicBlock*, SemanticsNodeBlockId>>
  40. todo_blocks_;
  41. // Maps nodes in SemanticsIR to a lowered value. This will have one entry per
  42. // node, and will be non-null when lowered. It's expected to be sparse during
  43. // execution because while expressions will have entries, statements won't.
  44. // TODO: This will probably become a PointerUnion of Value and Type.
  45. // TODO: Long-term, we should examine the practical trade-offs of making this
  46. // a map; a map may end up lower memory consumption, but a vector offers cache
  47. // efficiency and better performance. As a consequence, the right choice is
  48. // unclear.
  49. llvm::SmallVector<llvm::Value*> lowered_nodes_;
  50. };
  51. } // namespace Carbon
  52. #endif // CARBON_TOOLCHAIN_LOWERING_LOWERING_H_