lowering_block_worklist.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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_TOOLCHAIN_LOWERING_LOWERING_BLOCK_WORKLIST_H_
  5. #define CARBON_TOOLCHAIN_LOWERING_LOWERING_BLOCK_WORKLIST_H_
  6. #include "llvm/ADT/DenseSet.h"
  7. #include "llvm/ADT/SmallVector.h"
  8. #include "toolchain/semantics/semantics_node.h"
  9. namespace Carbon {
  10. // A worklist for blocks that need to be lowered.
  11. //
  12. // The blocks form a tree, where the sequence of blocks that are pushed
  13. // following a `Pop` that returned block B are the children of B. Blocks are
  14. // popped in a preorder depth-first traversal over this tree, where blocks that
  15. // are children of the same block are popped in the same order in which they
  16. // were pushed.
  17. //
  18. // This traversal order is intended to produce readable IR:
  19. //
  20. // - In the absence of control flow back-edges, branches will typically branch
  21. // to blocks emitted later, although this is not guaranteed.
  22. // - A branch and the blocks that it branches to will typically be placed close
  23. // together.
  24. class LoweringBlockWorklist {
  25. public:
  26. // Add a block to the work list.
  27. auto Push(SemanticsNodeBlockId id) -> void { worklist_.push_back(id); }
  28. // Pop the next block to lower.
  29. auto Pop() -> SemanticsNodeBlockId {
  30. // Reverse the order of the blocks added since the last `Pop`, so that we
  31. // pop them in the order that they were `Pushed` in.
  32. std::reverse(worklist_.begin() + size_after_last_pop_, worklist_.end());
  33. SemanticsNodeBlockId result = worklist_.pop_back_val();
  34. size_after_last_pop_ = worklist_.size();
  35. return result;
  36. }
  37. auto empty() -> bool { return worklist_.empty(); }
  38. private:
  39. llvm::SmallVector<SemanticsNodeBlockId> worklist_;
  40. int size_after_last_pop_ = 0;
  41. };
  42. } // namespace Carbon
  43. #endif // CARBON_TOOLCHAIN_LOWERING_LOWERING_BLOCK_WORKLIST_H_