arena.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 EXECUTABLE_SEMANTICS_COMMON_ARENA_H_
  5. #define EXECUTABLE_SEMANTICS_COMMON_ARENA_H_
  6. #include <memory>
  7. #include <vector>
  8. #include "executable_semantics/common/ptr.h"
  9. #include "llvm/Support/ManagedStatic.h"
  10. namespace Carbon {
  11. class Arena {
  12. public:
  13. // Allocates an object in the arena, returning a pointer to it.
  14. template <typename T, typename... Args>
  15. auto New(Args&&... args) -> Ptr<T> {
  16. auto smart_ptr =
  17. std::make_unique<ArenaEntryTyped<T>>(std::forward<Args>(args)...);
  18. Ptr<T> ptr = smart_ptr->Instance();
  19. arena.push_back(std::move(smart_ptr));
  20. return ptr;
  21. }
  22. private:
  23. // Virtualizes arena entries so that a single vector can contain many types,
  24. // avoiding templated statics.
  25. class ArenaEntry {
  26. public:
  27. virtual ~ArenaEntry() = default;
  28. };
  29. // Templated destruction of a pointer.
  30. template <typename T>
  31. class ArenaEntryTyped : public ArenaEntry {
  32. public:
  33. template <typename... Args>
  34. explicit ArenaEntryTyped(Args&&... args)
  35. : instance(std::forward<Args>(args)...) {}
  36. auto Instance() -> Ptr<T> { return Ptr<T>(&instance); }
  37. private:
  38. T instance;
  39. };
  40. // Manages allocations in an arena for destruction at shutdown.
  41. std::vector<std::unique_ptr<ArenaEntry>> arena;
  42. };
  43. extern llvm::ManagedStatic<Arena> global_arena;
  44. } // namespace Carbon
  45. #endif // EXECUTABLE_SEMANTICS_COMMON_ARENA_H_