heap.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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_EXPLORER_INTERPRETER_HEAP_H_
  5. #define CARBON_EXPLORER_INTERPRETER_HEAP_H_
  6. #include <vector>
  7. #include "common/ostream.h"
  8. #include "explorer/common/nonnull.h"
  9. #include "explorer/common/source_location.h"
  10. #include "explorer/interpreter/address.h"
  11. #include "explorer/interpreter/heap_allocation_interface.h"
  12. #include "explorer/interpreter/value.h"
  13. namespace Carbon {
  14. // A Heap represents the abstract machine's dynamically allocated memory.
  15. class Heap : public HeapAllocationInterface {
  16. public:
  17. enum class ValueState {
  18. Uninitialized,
  19. Alive,
  20. Dead,
  21. };
  22. // Constructs an empty Heap.
  23. explicit Heap(Nonnull<Arena*> arena) : arena_(arena){};
  24. Heap(const Heap&) = delete;
  25. auto operator=(const Heap&) -> Heap& = delete;
  26. // Returns the value at the given address in the heap after
  27. // checking that it is alive.
  28. auto Read(const Address& a, SourceLocation source_loc) const
  29. -> ErrorOr<Nonnull<const Value*>>;
  30. // Writes the given value at the address in the heap after
  31. // checking that the address is alive.
  32. auto Write(const Address& a, Nonnull<const Value*> v,
  33. SourceLocation source_loc) -> ErrorOr<Success>;
  34. auto GetAllocationId(Nonnull<const Value*> v) const
  35. -> std::optional<AllocationId> override;
  36. // Put the given value on the heap and mark its state.
  37. // Mark UninitializedValue as uninitialized and other values as alive.
  38. auto AllocateValue(Nonnull<const Value*> v) -> AllocationId override;
  39. // Marks this allocation, and all of its sub-objects, as dead.
  40. void Deallocate(AllocationId allocation) override;
  41. void Deallocate(const Address& a);
  42. // Print all the values on the heap to the stream `out`.
  43. void Print(llvm::raw_ostream& out) const;
  44. LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
  45. auto arena() const -> Arena& override { return *arena_; }
  46. private:
  47. // Signal an error if the allocation is no longer alive.
  48. auto CheckAlive(AllocationId allocation, SourceLocation source_loc) const
  49. -> ErrorOr<Success>;
  50. // Signal an error if the allocation has not been initialized.
  51. auto CheckInit(AllocationId allocation, SourceLocation source_loc) const
  52. -> ErrorOr<Success>;
  53. Nonnull<Arena*> arena_;
  54. std::vector<Nonnull<const Value*>> values_;
  55. std::vector<ValueState> states_;
  56. };
  57. } // namespace Carbon
  58. #endif // CARBON_EXPLORER_INTERPRETER_HEAP_H_