inst_block_stack.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 " << size_ << "\n";
  11. CARBON_CHECK(size_ < (1 << 20))
  12. << "Excessive stack size: likely infinite loop";
  13. if (size_ == static_cast<int>(stack_.size())) {
  14. stack_.emplace_back();
  15. }
  16. stack_[size_].Reset(id);
  17. ++size_;
  18. }
  19. auto InstBlockStack::Push(SemIR::InstBlockId id,
  20. llvm::ArrayRef<SemIR::InstId> inst_ids) -> void {
  21. Push(id);
  22. stack_[size_ - 1].content = inst_ids;
  23. }
  24. auto InstBlockStack::PeekOrAdd(int depth) -> SemIR::InstBlockId {
  25. CARBON_CHECK(size_ > depth) << "no such block";
  26. int index = size_ - depth - 1;
  27. auto& slot = stack_[index];
  28. if (!slot.id.is_valid()) {
  29. slot.id = sem_ir_->inst_blocks().AddDefaultValue();
  30. }
  31. return slot.id;
  32. }
  33. auto InstBlockStack::Pop() -> SemIR::InstBlockId {
  34. CARBON_CHECK(!empty()) << "no current block";
  35. --size_;
  36. auto& back = stack_[size_];
  37. // Finalize the block.
  38. if (!back.content.empty() && back.id != SemIR::InstBlockId::Unreachable) {
  39. if (back.id.is_valid()) {
  40. sem_ir_->inst_blocks().Set(back.id, back.content);
  41. } else {
  42. back.id = sem_ir_->inst_blocks().Add(back.content);
  43. }
  44. }
  45. CARBON_VLOG() << name_ << " Pop " << size_ << ": " << back.id << "\n";
  46. if (!back.id.is_valid()) {
  47. return SemIR::InstBlockId::Empty;
  48. }
  49. return back.id;
  50. }
  51. auto InstBlockStack::PopAndDiscard() -> void {
  52. CARBON_CHECK(!empty()) << "no current block";
  53. --size_;
  54. CARBON_VLOG() << name_ << " PopAndDiscard " << size_ << "\n";
  55. }
  56. auto InstBlockStack::PrintForStackDump(llvm::raw_ostream& output) const
  57. -> void {
  58. output << name_ << ":\n";
  59. for (const auto& [i, entry] : llvm::enumerate(stack_)) {
  60. output << "\t" << i << ".\t" << entry.id << "\t{";
  61. llvm::ListSeparator sep;
  62. for (auto id : entry.content) {
  63. output << sep << id;
  64. }
  65. output << "}\n";
  66. }
  67. }
  68. } // namespace Carbon::Check