arena.h 1.5 KB

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