inst_block_stack.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. #include "toolchain/check/inst_block_stack.h"
  5. #include "common/vlog.h"
  6. #include "llvm/ADT/STLExtras.h"
  7. #include "llvm/ADT/StringExtras.h"
  8. namespace Carbon::Check {
  9. auto InstBlockStack::Push(SemIR::InstBlockId id) -> void {
  10. CARBON_VLOG() << name_ << " Push " << id_stack_.size() << "\n";
  11. CARBON_CHECK(id_stack_.size() < (1 << 20))
  12. << "Excessive stack size: likely infinite loop";
  13. id_stack_.push_back(id);
  14. insts_stack_.PushArray();
  15. }
  16. auto InstBlockStack::Push(SemIR::InstBlockId id,
  17. llvm::ArrayRef<SemIR::InstId> inst_ids) -> void {
  18. Push(id);
  19. insts_stack_.AppendToTop(inst_ids);
  20. }
  21. auto InstBlockStack::PeekOrAdd(int depth) -> SemIR::InstBlockId {
  22. CARBON_CHECK(static_cast<int>(id_stack_.size()) > depth) << "no such block";
  23. int index = id_stack_.size() - depth - 1;
  24. auto& slot = id_stack_[index];
  25. if (!slot.is_valid()) {
  26. slot = sem_ir_->inst_blocks().AddDefaultValue();
  27. }
  28. return slot;
  29. }
  30. auto InstBlockStack::Pop() -> SemIR::InstBlockId {
  31. CARBON_CHECK(!empty()) << "no current block";
  32. auto id = id_stack_.pop_back_val();
  33. auto insts = insts_stack_.PeekArray();
  34. // Finalize the block.
  35. if (!insts.empty() && id != SemIR::InstBlockId::Unreachable) {
  36. if (id.is_valid()) {
  37. sem_ir_->inst_blocks().Set(id, insts);
  38. } else {
  39. id = sem_ir_->inst_blocks().Add(insts);
  40. }
  41. }
  42. insts_stack_.PopArray();
  43. CARBON_VLOG() << name_ << " Pop " << id_stack_.size() << ": " << id << "\n";
  44. return id.is_valid() ? id : SemIR::InstBlockId::Empty;
  45. }
  46. auto InstBlockStack::PopAndDiscard() -> void {
  47. CARBON_CHECK(!empty()) << "no current block";
  48. id_stack_.pop_back();
  49. insts_stack_.PopArray();
  50. CARBON_VLOG() << name_ << " PopAndDiscard " << id_stack_.size() << "\n";
  51. }
  52. auto InstBlockStack::PrintForStackDump(llvm::raw_ostream& output) const
  53. -> void {
  54. output << name_ << ":\n";
  55. for (const auto& [i, id] : llvm::enumerate(id_stack_)) {
  56. output << "\t" << i << ".\t" << id << "\t{";
  57. llvm::ListSeparator sep;
  58. for (auto id : insts_stack_.PeekArrayAt(i)) {
  59. output << sep << id;
  60. }
  61. output << "}\n";
  62. }
  63. }
  64. } // namespace Carbon::Check