Skip to content

Commit

Permalink
[llvm] Use std::size instead of llvm::array_lengthof
Browse files Browse the repository at this point in the history
LLVM contains a helpful function for getting the size of a C-style
array: `llvm::array_lengthof`. This is useful prior to C++17, but not as
helpful for C++17 or later: `std::size` already has support for C-style
arrays.

Change call sites to use `std::size` instead.

Differential Revision: https://reviews.llvm.org/D133429
  • Loading branch information
JoeLoser committed Sep 8, 2022
1 parent 7aec9dd commit 5e96cea
Show file tree
Hide file tree
Showing 69 changed files with 182 additions and 192 deletions.
25 changes: 13 additions & 12 deletions llvm/include/llvm/CodeGen/TargetLowering.h
Original file line number Diff line number Diff line change
Expand Up @@ -935,7 +935,7 @@ class TargetLoweringBase {
/// promotions or expansions.
bool isTypeLegal(EVT VT) const {
assert(!VT.isSimple() ||
(unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
(unsigned)VT.getSimpleVT().SimpleTy < std::size(RegClassForVT));
return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
}

Expand Down Expand Up @@ -1110,7 +1110,8 @@ class TargetLoweringBase {
if (VT.isExtended()) return Expand;
// If a target-specific SDNode requires legalization, require the target
// to provide custom legalization for it.
if (Op >= array_lengthof(OpActions[0])) return Custom;
if (Op >= std::size(OpActions[0]))
return Custom;
return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
}

Expand Down Expand Up @@ -1417,8 +1418,8 @@ class TargetLoweringBase {
/// expander for it.
LegalizeAction
getCondCodeAction(ISD::CondCode CC, MVT VT) const {
assert((unsigned)CC < array_lengthof(CondCodeActions) &&
((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) &&
assert((unsigned)CC < std::size(CondCodeActions) &&
((unsigned)VT.SimpleTy >> 3) < std::size(CondCodeActions[0]) &&
"Table isn't big enough!");
// See setCondCodeAction for how this is encoded.
uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
Expand Down Expand Up @@ -1526,15 +1527,15 @@ class TargetLoweringBase {

/// Return the type of registers that this ValueType will eventually require.
MVT getRegisterType(MVT VT) const {
assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
assert((unsigned)VT.SimpleTy < std::size(RegisterTypeForVT));
return RegisterTypeForVT[VT.SimpleTy];
}

/// Return the type of registers that this ValueType will eventually require.
MVT getRegisterType(LLVMContext &Context, EVT VT) const {
if (VT.isSimple()) {
assert((unsigned)VT.getSimpleVT().SimpleTy <
array_lengthof(RegisterTypeForVT));
std::size(RegisterTypeForVT));
return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
}
if (VT.isVector()) {
Expand Down Expand Up @@ -1567,7 +1568,7 @@ class TargetLoweringBase {
Optional<MVT> RegisterVT = None) const {
if (VT.isSimple()) {
assert((unsigned)VT.getSimpleVT().SimpleTy <
array_lengthof(NumRegistersForVT));
std::size(NumRegistersForVT));
return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
}
if (VT.isVector()) {
Expand Down Expand Up @@ -1635,7 +1636,7 @@ class TargetLoweringBase {
/// If true, the target has custom DAG combine transformations that it can
/// perform for the specified node.
bool hasTargetDAGCombine(ISD::NodeType NT) const {
assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
assert(unsigned(NT >> 3) < std::size(TargetDAGCombineArray));
return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
}

Expand Down Expand Up @@ -2298,7 +2299,7 @@ class TargetLoweringBase {
/// specified value type. This indicates the selector can handle values of
/// that class natively.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
assert((unsigned)VT.SimpleTy < std::size(RegClassForVT));
RegClassForVT[VT.SimpleTy] = RC;
}

Expand All @@ -2315,7 +2316,7 @@ class TargetLoweringBase {
/// type and indicate what to do about it. Note that VT may refer to either
/// the type of a result or that of an operand of Op.
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action) {
assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
assert(Op < std::size(OpActions[0]) && "Table isn't big enough!");
OpActions[(unsigned)VT.SimpleTy][Op] = Action;
}
void setOperationAction(ArrayRef<unsigned> Ops, MVT VT,
Expand Down Expand Up @@ -2417,7 +2418,7 @@ class TargetLoweringBase {
void setCondCodeAction(ArrayRef<ISD::CondCode> CCs, MVT VT,
LegalizeAction Action) {
for (auto CC : CCs) {
assert(VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) &&
assert(VT.isValid() && (unsigned)CC < std::size(CondCodeActions) &&
"Table isn't big enough!");
assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
/// The lower 3 bits of the SimpleTy index into Nth 4bit set from the
Expand Down Expand Up @@ -2454,7 +2455,7 @@ class TargetLoweringBase {
/// PerformDAGCombine virtual method.
void setTargetDAGCombine(ArrayRef<ISD::NodeType> NTs) {
for (auto NT : NTs) {
assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
assert(unsigned(NT >> 3) < std::size(TargetDAGCombineArray));
TargetDAGCombineArray[NT >> 3] |= 1 << (NT & 7);
}
}
Expand Down
8 changes: 4 additions & 4 deletions llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4311,7 +4311,7 @@ LegalizerHelper::LegalizeResult LegalizerHelper::fewerElementsVectorShuffle(
// The input vector this mask element indexes into.
unsigned Input = (unsigned)Idx / NewElts;

if (Input >= array_lengthof(Inputs)) {
if (Input >= std::size(Inputs)) {
// The mask element does not index into any input vector.
Ops.push_back(-1);
continue;
Expand All @@ -4322,7 +4322,7 @@ LegalizerHelper::LegalizeResult LegalizerHelper::fewerElementsVectorShuffle(

// Find or create a shuffle vector operand to hold this input.
unsigned OpNo;
for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
for (OpNo = 0; OpNo < std::size(InputUsed); ++OpNo) {
if (InputUsed[OpNo] == Input) {
// This input vector is already an operand.
break;
Expand All @@ -4333,7 +4333,7 @@ LegalizerHelper::LegalizeResult LegalizerHelper::fewerElementsVectorShuffle(
}
}

if (OpNo >= array_lengthof(InputUsed)) {
if (OpNo >= std::size(InputUsed)) {
// More than two input vectors used! Give up on trying to create a
// shuffle vector. Insert all elements into a BUILD_VECTOR instead.
UseBuildVector = true;
Expand All @@ -4356,7 +4356,7 @@ LegalizerHelper::LegalizeResult LegalizerHelper::fewerElementsVectorShuffle(
// The input vector this mask element indexes into.
unsigned Input = (unsigned)Idx / NewElts;

if (Input >= array_lengthof(Inputs)) {
if (Input >= std::size(Inputs)) {
// The mask element is "undef" or indexes off the end of the input.
SVOps.push_back(MIRBuilder.buildUndef(EltTy).getReg(0));
continue;
Expand Down
14 changes: 7 additions & 7 deletions llvm/lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2378,7 +2378,7 @@ void DAGTypeLegalizer::SplitVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N,
&DL](SmallVectorImpl<int> &Mask) {
// Check if all inputs are shuffles of the same operands or non-shuffles.
MapVector<std::pair<SDValue, SDValue>, SmallVector<unsigned>> ShufflesIdxs;
for (unsigned Idx = 0; Idx < array_lengthof(Inputs); ++Idx) {
for (unsigned Idx = 0; Idx < std::size(Inputs); ++Idx) {
SDValue Input = Inputs[Idx];
auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Input.getNode());
if (!Shuffle ||
Expand Down Expand Up @@ -2425,7 +2425,7 @@ void DAGTypeLegalizer::SplitVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N,
ShufflesIdxs[std::make_pair(P.first.second, P.first.first)].clear();
}
// Check if any concat_vectors can be simplified.
SmallBitVector UsedSubVector(2 * array_lengthof(Inputs));
SmallBitVector UsedSubVector(2 * std::size(Inputs));
for (int &Idx : Mask) {
if (Idx == UndefMaskElem)
continue;
Expand All @@ -2445,7 +2445,7 @@ void DAGTypeLegalizer::SplitVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N,
}
if (UsedSubVector.count() > 1) {
SmallVector<SmallVector<std::pair<unsigned, int>, 2>> Pairs;
for (unsigned I = 0; I < array_lengthof(Inputs); ++I) {
for (unsigned I = 0; I < std::size(Inputs); ++I) {
if (UsedSubVector.test(2 * I) == UsedSubVector.test(2 * I + 1))
continue;
if (Pairs.empty() || Pairs.back().size() == 2)
Expand Down Expand Up @@ -2489,7 +2489,7 @@ void DAGTypeLegalizer::SplitVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N,
// Try to remove extra shuffles (except broadcasts) and shuffles with the
// reused operands.
Changed = false;
for (unsigned I = 0; I < array_lengthof(Inputs); ++I) {
for (unsigned I = 0; I < std::size(Inputs); ++I) {
auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Inputs[I].getNode());
if (!Shuffle)
continue;
Expand Down Expand Up @@ -2589,7 +2589,7 @@ void DAGTypeLegalizer::SplitVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N,
}
// Adjust mask in case of reused inputs. Also, need to insert constant
// inputs at first, otherwise it affects the final outcome.
if (UniqueInputs.size() != array_lengthof(Inputs)) {
if (UniqueInputs.size() != std::size(Inputs)) {
auto &&UniqueVec = UniqueInputs.takeVector();
auto &&UniqueConstantVec = UniqueConstantInputs.takeVector();
unsigned ConstNum = UniqueConstantVec.size();
Expand Down Expand Up @@ -2627,7 +2627,7 @@ void DAGTypeLegalizer::SplitVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N,
// Build a shuffle mask for the output, discovering on the fly which
// input vectors to use as shuffle operands.
unsigned FirstMaskIdx = High * NewElts;
SmallVector<int> Mask(NewElts * array_lengthof(Inputs), UndefMaskElem);
SmallVector<int> Mask(NewElts * std::size(Inputs), UndefMaskElem);
copy(makeArrayRef(OrigMask).slice(FirstMaskIdx, NewElts), Mask.begin());
assert(!Output && "Expected default initialized initial value.");
TryPeekThroughShufflesInputs(Mask);
Expand All @@ -2647,7 +2647,7 @@ void DAGTypeLegalizer::SplitVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N,
return SecondIteration;
};
processShuffleMasks(
Mask, array_lengthof(Inputs), array_lengthof(Inputs),
Mask, std::size(Inputs), std::size(Inputs),
/*NumOfUsedRegs=*/1,
[&Output, &DAG = DAG, NewVT]() { Output = DAG.getUNDEF(NewVT); },
[&Output, &DAG = DAG, NewVT, &DL, &Inputs,
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/CodeGen/TargetLoweringBase.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -950,7 +950,7 @@ TargetLoweringBase::getTypeConversion(LLVMContext &Context, EVT VT) const {
// If this is a simple type, use the ComputeRegisterProp mechanism.
if (VT.isSimple()) {
MVT SVT = VT.getSimpleVT();
assert((unsigned)SVT.SimpleTy < array_lengthof(TransformToType));
assert((unsigned)SVT.SimpleTy < std::size(TransformToType));
MVT NVT = TransformToType[SVT.SimpleTy];
LegalizeTypeAction LA = ValueTypeActions.getTypeAction(SVT);

Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/DWP/DWP.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ void writeIndexTable(
const MapVector<uint64_t, UnitIndexEntry> &IndexEntries,
uint32_t DWARFUnitIndex::Entry::SectionContribution::*Field) {
for (const auto &E : IndexEntries)
for (size_t I = 0; I != array_lengthof(E.second.Contributions); ++I)
for (size_t I = 0; I != std::size(E.second.Contributions); ++I)
if (ContributionOffsets[I])
Out.emitIntValue(E.second.Contributions[I].*Field, 4);
}
Expand Down
7 changes: 3 additions & 4 deletions llvm/lib/IR/DebugInfoMetadata.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -329,16 +329,15 @@ void GenericDINode::recalculateHash() {
} \
} while (false)
#define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS) \
return storeImpl(new (array_lengthof(OPS), Storage) \
return storeImpl(new (std::size(OPS), Storage) \
CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \
Storage, Context.pImpl->CLASS##s)
#define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS) \
return storeImpl(new (0u, Storage) \
CLASS(Context, Storage, UNWRAP_ARGS(ARGS)), \
Storage, Context.pImpl->CLASS##s)
#define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS) \
return storeImpl(new (array_lengthof(OPS), Storage) \
CLASS(Context, Storage, OPS), \
return storeImpl(new (std::size(OPS), Storage) CLASS(Context, Storage, OPS), \
Storage, Context.pImpl->CLASS##s)
#define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS) \
return storeImpl(new (NUM_OPS, Storage) \
Expand Down Expand Up @@ -850,7 +849,7 @@ DICompileUnit *DICompileUnit::getImpl(
Macros,
SysRoot,
SDK};
return storeImpl(new (array_lengthof(Ops), Storage) DICompileUnit(
return storeImpl(new (std::size(Ops), Storage) DICompileUnit(
Context, Storage, SourceLanguage, IsOptimized,
RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/MC/MCAsmBackend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ const MCFixupKindInfo &MCAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
{"FK_SecRel_8", 0, 64, 0},
};

assert((size_t)Kind <= array_lengthof(Builtins) && "Unknown fixup kind");
assert((size_t)Kind <= std::size(Builtins) && "Unknown fixup kind");
return Builtins[Kind];
}

Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/MC/MCDwarf.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
0, // length of DW_LNS_set_epilogue_begin
1 // DW_LNS_set_isa
};
assert(array_lengthof(StandardOpcodeLengths) >=
assert(std::size(StandardOpcodeLengths) >=
(Params.DWARF2LineOpcodeBase - 1U));
return Emit(
MCOS, Params,
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/Object/MachOObjectFile.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2329,7 +2329,7 @@ void MachOObjectFile::getRelocationTypeName(
"ARM64_RELOC_ADDEND"
};

if (RType >= array_lengthof(Table))
if (RType >= std::size(Table))
res = "Unknown";
else
res = Table[RType];
Expand Down
4 changes: 2 additions & 2 deletions llvm/lib/Support/ARMAttributeParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ Error ARMAttributeParser::ABI_align_needed(AttrType tag) {
uint64_t value = de.getULEB128(cursor);

std::string description;
if (value < array_lengthof(strings))
if (value < std::size(strings))
description = strings[value];
else if (value <= 12)
description = "8-byte alignment, " + utostr(1ULL << value) +
Expand All @@ -233,7 +233,7 @@ Error ARMAttributeParser::ABI_align_preserved(AttrType tag) {
uint64_t value = de.getULEB128(cursor);

std::string description;
if (value < array_lengthof(strings))
if (value < std::size(strings))
description = std::string(strings[value]);
else if (value <= 12)
description = std::string("8-byte stack alignment, ") +
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/Support/CrashRecoveryContext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ static void uninstallExceptionOrSignalHandlers() {

static const int Signals[] =
{ SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP };
static const unsigned NumSignals = array_lengthof(Signals);
static const unsigned NumSignals = std::size(Signals);
static struct sigaction PrevActions[NumSignals];

static void CrashRecoverySignalHandler(int Signal) {
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/Support/NativeFormatting.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ void llvm::write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style,
std::max(static_cast<unsigned>(W), std::max(1u, Nibbles) + PrefixChars);

char NumberBuffer[kMaxWidth];
::memset(NumberBuffer, '0', llvm::array_lengthof(NumberBuffer));
::memset(NumberBuffer, '0', std::size(NumberBuffer));
if (Prefix)
NumberBuffer[1] = 'x';
char *EndPtr = NumberBuffer + NumChars;
Expand Down
10 changes: 5 additions & 5 deletions llvm/lib/Support/Triple.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -982,13 +982,13 @@ std::string Triple::normalize(StringRef Str) {
// If they are not there already, permute the components into their canonical
// positions by seeing if they parse as a valid architecture, and if so moving
// the component to the architecture position etc.
for (unsigned Pos = 0; Pos != array_lengthof(Found); ++Pos) {
for (unsigned Pos = 0; Pos != std::size(Found); ++Pos) {
if (Found[Pos])
continue; // Already in the canonical position.

for (unsigned Idx = 0; Idx != Components.size(); ++Idx) {
// Do not reparse any components that already matched.
if (Idx < array_lengthof(Found) && Found[Idx])
if (Idx < std::size(Found) && Found[Idx])
continue;

// Does this component parse as valid for the target position?
Expand Down Expand Up @@ -1036,7 +1036,7 @@ std::string Triple::normalize(StringRef Str) {
// components to the right.
for (unsigned i = Pos; !CurrentComponent.empty(); ++i) {
// Skip over any fixed components.
while (i < array_lengthof(Found) && Found[i])
while (i < std::size(Found) && Found[i])
++i;
// Place the component at the new position, getting the component
// that was at this position - it will be moved right.
Expand All @@ -1057,15 +1057,15 @@ std::string Triple::normalize(StringRef Str) {
if (CurrentComponent.empty())
break;
// Advance to the next component, skipping any fixed components.
while (++i < array_lengthof(Found) && Found[i])
while (++i < std::size(Found) && Found[i])
;
}
// The last component was pushed off the end - append it.
if (!CurrentComponent.empty())
Components.push_back(CurrentComponent);

// Advance Idx to the component's new position.
while (++Idx < array_lengthof(Found) && Found[Idx])
while (++Idx < std::size(Found) && Found[Idx])
;
} while (Idx < Pos); // Add more until the final position is reached.
}
Expand Down
10 changes: 5 additions & 5 deletions llvm/lib/Support/Unix/Signals.inc
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,8 @@ static const int InfoSigs[] = {
};

static const size_t NumSigs =
array_lengthof(IntSigs) + array_lengthof(KillSigs) +
array_lengthof(InfoSigs) + 1 /* SIGPIPE */;
std::size(IntSigs) + std::size(KillSigs) +
std::size(InfoSigs) + 1 /* SIGPIPE */;


static std::atomic<unsigned> NumRegisteredSignals = ATOMIC_VAR_INIT(0);
Expand Down Expand Up @@ -298,7 +298,7 @@ static void RegisterHandlers() { // Not signal-safe.
enum class SignalKind { IsKill, IsInfo };
auto registerHandler = [&](int Signal, SignalKind Kind) {
unsigned Index = NumRegisteredSignals.load();
assert(Index < array_lengthof(RegisteredSignalInfo) &&
assert(Index < std::size(RegisteredSignalInfo) &&
"Out of space for signal handlers!");

struct sigaction NewHandler;
Expand Down Expand Up @@ -566,13 +566,13 @@ void llvm::sys::PrintStackTrace(raw_ostream &OS, int Depth) {
#if defined(HAVE_BACKTRACE)
// Use backtrace() to output a backtrace on Linux systems with glibc.
if (!depth)
depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace)));
depth = backtrace(StackTrace, static_cast<int>(std::size(StackTrace)));
#endif
#if defined(HAVE__UNWIND_BACKTRACE)
// Try _Unwind_Backtrace() if backtrace() failed.
if (!depth)
depth = unwindBacktrace(StackTrace,
static_cast<int>(array_lengthof(StackTrace)));
static_cast<int>(std::size(StackTrace)));
#endif
if (!depth)
return;
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/Support/Windows/Path.inc
Original file line number Diff line number Diff line change
Expand Up @@ -687,7 +687,7 @@ static bool isReservedName(StringRef path) {
return true;

// Then compare against the list of ancient reserved names.
for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
for (size_t i = 0; i < std::size(sReservedNames); ++i) {
if (path.equals_insensitive(sReservedNames[i]))
return true;
}
Expand Down
Loading

0 comments on commit 5e96cea

Please sign in to comment.