[StringExtras] Add a helper class for comma-separated lists
authorKazu Hirata <kazu@google.com>
Sun, 10 Jan 2021 22:32:02 +0000 (14:32 -0800)
committerKazu Hirata <kazu@google.com>
Sun, 10 Jan 2021 22:32:02 +0000 (14:32 -0800)
commit407b1e65a464081e28c325273b65e8eafdfad1d4
tree1f83237968cd7ddbff5c8dda5509c2f3c7bd5a18
parent7be3285248bf54d0784a76174cf44cf7c1e780a5
[StringExtras] Add a helper class for comma-separated lists

This patch introduces a helper class SubsequentDelim to simplify loops
that generate a comma-separated lists.

For example, consider the following loop, taken from
llvm/lib/CodeGen/MachineBasicBlock.cpp:

    for (auto I = pred_begin(), E = pred_end(); I != E; ++I) {
      if (I != pred_begin())
        OS << ", ";
      OS << printMBBReference(**I);
    }

The new class allows us to rewrite the loop as:

    SubsequentDelim SD;
    for (auto I = pred_begin(), E = pred_end(); I != E; ++I)
      OS << SD << printMBBReference(**I);

where SD evaluates to the empty string for the first time and ", " for
subsequent iterations.

Unlike interleaveComma, defined in llvm/include/llvm/ADT/STLExtras.h,
SubsequentDelim can accommodate a wider variety of loops, including:

- those that conditionally skip certain items,
- those that need iterators to call getSuccProbability(I), and
- those that iterate over integer ranges.

As an example, this patch cleans up MachineBasicBlock::print.

Differential Revision: https://reviews.llvm.org/D94377
llvm/include/llvm/ADT/StringExtras.h
llvm/lib/CodeGen/MachineBasicBlock.cpp
llvm/unittests/ADT/StringExtrasTest.cpp