heap.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. // Constructs an empty Heap.
  18. explicit Heap(Nonnull<Arena*> arena) : arena_(arena){};
  19. Heap(const Heap&) = delete;
  20. auto operator=(const Heap&) -> Heap& = delete;
  21. // Returns the value at the given address in the heap after
  22. // checking that it is alive.
  23. auto Read(const Address& a, SourceLocation source_loc) const
  24. -> ErrorOr<Nonnull<const Value*>>;
  25. // Writes the given value at the address in the heap after
  26. // checking that the address is alive.
  27. auto Write(const Address& a, Nonnull<const Value*> v,
  28. SourceLocation source_loc) -> ErrorOr<Success>;
  29. // Put the given value on the heap and mark it as alive.
  30. auto AllocateValue(Nonnull<const Value*> v) -> AllocationId override;
  31. // Marks this allocation, and all of its sub-objects, as dead.
  32. void Deallocate(AllocationId allocation) override;
  33. void Deallocate(const Address& a);
  34. // Print all the values on the heap to the stream `out`.
  35. void Print(llvm::raw_ostream& out) const;
  36. LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
  37. auto arena() const -> Arena& override { return *arena_; }
  38. private:
  39. // Signal an error if the allocation is no longer alive.
  40. auto CheckAlive(AllocationId allocation, SourceLocation source_loc) const
  41. -> ErrorOr<Success>;
  42. Nonnull<Arena*> arena_;
  43. std::vector<Nonnull<const Value*>> values_;
  44. std::vector<bool> alive_;
  45. };
  46. } // namespace Carbon
  47. #endif // CARBON_EXPLORER_INTERPRETER_HEAP_H_