diff options
Diffstat (limited to 'src')
82 files changed, 268 insertions, 534 deletions
diff --git a/src/cfg/Relooper.cpp b/src/cfg/Relooper.cpp index 4404f2d20..1cdcbe2d0 100644 --- a/src/cfg/Relooper.cpp +++ b/src/cfg/Relooper.cpp @@ -62,9 +62,7 @@ static wasm::Expression* HandleFollowupMultiples(wasm::Expression* Ret, if (!Multiple) { break; } - for (auto& iter : Multiple->InnerMap) { - int Id = iter.first; - Shape* Body = iter.second; + for (auto& [Id, Body] : Multiple->InnerMap) { Curr->name = Builder.getBlockBreakName(Id); Curr->finalize(); // it may now be reachable, via a break auto* Outer = Builder.makeBlock(Curr); @@ -222,13 +220,13 @@ wasm::Expression* Block::Render(RelooperBuilder& Builder, bool InLoop) { Block* DefaultTarget = nullptr; // Find the default target, the one without a condition - for (auto& iter : ProcessedBranchesOut) { - if ((!SwitchCondition && !iter.second->Condition) || - (SwitchCondition && !iter.second->SwitchValues)) { + for (auto& [Target, Details] : ProcessedBranchesOut) { + if ((!SwitchCondition && !Details->Condition) || + (SwitchCondition && !Details->SwitchValues)) { assert(!DefaultTarget && "block has branches without a default (nullptr for the " "condition)"); // Must be exactly one default // nullptr - DefaultTarget = iter.first; + DefaultTarget = Target; } } // Since each Block* must* branch somewhere, this must be set @@ -338,9 +336,7 @@ wasm::Expression* Block::Render(RelooperBuilder& Builder, bool InLoop) { auto* Outer = Builder.makeBlock(); auto* Inner = Outer; std::vector<wasm::Name> Table; - for (auto& iter : ProcessedBranchesOut) { - Block* Target = iter.first; - Branch* Details = iter.second; + for (auto& [Target, Details] : ProcessedBranchesOut) { wasm::Name CurrName; if (Details->SwitchValues) { CurrName = wasm::Name(Base + "$case$" + std::to_string(Target->Id)); @@ -435,9 +431,9 @@ wasm::Expression* MultipleShape::Render(RelooperBuilder& Builder, bool InLoop) { wasm::If* FirstIf = nullptr; wasm::If* CurrIf = nullptr; std::vector<wasm::If*> finalizeStack; - for (auto& iter : InnerMap) { - auto* Now = Builder.makeIf(Builder.makeCheckLabel(iter.first), - iter.second->Render(Builder, InLoop)); + for (auto& [Id, Body] : InnerMap) { + auto* Now = + Builder.makeIf(Builder.makeCheckLabel(Id), Body->Render(Builder, InLoop)); finalizeStack.push_back(Now); if (!CurrIf) { FirstIf = CurrIf = Now; @@ -610,8 +606,7 @@ struct Optimizer : public RelooperRecursor { void CanonicalizeCode() { for (auto& Block : Parent->Blocks) { Block->Code = Canonicalize(Block->Code); - for (auto& iter : Block->BranchesOut) { - auto* Branch = iter.second; + for (auto& [_, Branch] : Block->BranchesOut) { if (Branch->Code) { Branch->Code = Canonicalize(Branch->Code); } @@ -647,7 +642,7 @@ struct Optimizer : public RelooperRecursor { Next = Replacement = NextNext; // If we've already seen this, stop - it's an infinite loop of // empty blocks we can skip through. - if (Seen.count(Replacement)) { + if (!Seen.emplace(Replacement).second) { // Stop here. Note that if we started from X and ended up with X // once more, then Replacement == First and so lower down we // will not report that we did any work, avoiding an infinite @@ -655,7 +650,6 @@ struct Optimizer : public RelooperRecursor { break; } else { // Otherwise, keep going. - Seen.insert(Replacement); continue; } } @@ -698,12 +692,10 @@ struct Optimizer : public RelooperRecursor { if (ParentBlock->BranchesOut.size() >= 2) { std::unordered_map<size_t, std::vector<BranchBlock>> HashedBranchesOut; std::vector<Block*> BlocksToErase; - for (auto& iter : ParentBlock->BranchesOut) { - Block* CurrBlock = iter.first; + for (auto& [CurrBlock, CurrBranch] : ParentBlock->BranchesOut) { #if RELOOPER_OPTIMIZER_DEBUG std::cout << " consider child " << CurrBlock->Id << '\n'; #endif - Branch* CurrBranch = iter.second; if (CurrBranch->Code) { // We can't merge code; ignore continue; @@ -712,9 +704,7 @@ struct Optimizer : public RelooperRecursor { auto& HashedSiblings = HashedBranchesOut[HashValue]; // Check if we are equivalent to any of them - if so, merge us. bool Merged = false; - for (auto& Pair : HashedSiblings) { - Branch* SiblingBranch = Pair.first; - Block* SiblingBlock = Pair.second; + for (auto& [SiblingBranch, SiblingBlock] : HashedSiblings) { if (HaveEquivalentContents(CurrBlock, SiblingBlock)) { #if RELOOPER_OPTIMIZER_DEBUG std::cout << " equiv! to " << SiblingBlock->Id << '\n'; @@ -809,8 +799,8 @@ struct Optimizer : public RelooperRecursor { } else { // If the block has no switch, the branches must not as well. #ifndef NDEBUG - for (auto& iter : ParentBlock->BranchesOut) { - assert(!iter.second->SwitchValues); + for (auto& [_, CurrBranch] : ParentBlock->BranchesOut) { + assert(!CurrBranch->SwitchValues); } #endif } @@ -923,9 +913,7 @@ private: if (A->BranchesOut.size() != B->BranchesOut.size()) { return false; } - for (auto& aiter : A->BranchesOut) { - Block* ABlock = aiter.first; - Branch* ABranch = aiter.second; + for (auto& [ABlock, ABranch] : A->BranchesOut) { if (B->BranchesOut.count(ABlock) == 0) { return false; } @@ -1030,11 +1018,11 @@ private: wasm::ExpressionAnalyzer::hash(Curr->SwitchCondition)); } wasm::rehash(digest, uint8_t(2)); - for (auto& Pair : Curr->BranchesOut) { + for (auto& [CurrBlock, CurrBranch] : Curr->BranchesOut) { // Hash the Block* as a pointer TODO: full hash? - wasm::rehash(digest, reinterpret_cast<size_t>(Pair.first)); + wasm::rehash(digest, reinterpret_cast<size_t>(CurrBlock)); // Hash the Branch info properly - wasm::hash_combine(digest, Hash(Pair.second)); + wasm::hash_combine(digest, Hash(CurrBranch)); } return digest; } @@ -1077,8 +1065,8 @@ void Relooper::Calculate(Block* Entry) { if (!contains(Live.Live, Curr)) { continue; } - for (auto& iter : Curr->BranchesOut) { - iter.first->BranchesIn.insert(Curr); + for (auto& [CurrBlock, _] : Curr->BranchesOut) { + CurrBlock->BranchesIn.insert(Curr); } } @@ -1092,9 +1080,9 @@ void Relooper::Calculate(Block* Entry) { void GetBlocksOut(Block* Source, BlockSet& Entries, BlockSet* LimitTo = nullptr) { - for (auto& iter : Source->BranchesOut) { - if (!LimitTo || contains(*LimitTo, iter.first)) { - Entries.insert(iter.first); + for (auto& [CurrBlock, _] : Source->BranchesOut) { + if (!LimitTo || contains(*LimitTo, CurrBlock)) { + Entries.insert(CurrBlock); } } } @@ -1174,8 +1162,7 @@ void Relooper::Calculate(Block* Entry) { assert(InnerBlocks.size() > 0); for (auto* Curr : InnerBlocks) { - for (auto& iter : Curr->BranchesOut) { - Block* Possible = iter.first; + for (auto& [Possible, _] : Curr->BranchesOut) { if (!contains(InnerBlocks, Possible)) { NextEntries.insert(Possible); } @@ -1289,8 +1276,7 @@ void Relooper::Calculate(Block* Entry) { // may have been seen before and invalidated already if (Ownership[Invalidatee]) { Ownership[Invalidatee] = nullptr; - for (auto& iter : Invalidatee->BranchesOut) { - Block* Target = iter.first; + for (auto& [Target, _] : Invalidatee->BranchesOut) { auto Known = Ownership.find(Target); if (Known != Ownership.end()) { Block* TargetOwner = Known->second; @@ -1330,8 +1316,7 @@ void Relooper::Calculate(Block* Entry) { continue; } // Add all children - for (auto& iter : Curr->BranchesOut) { - Block* New = iter.first; + for (auto& [New, _] : Curr->BranchesOut) { auto Known = Helper.Ownership.find(New); if (Known == Helper.Ownership.end()) { // New node. Add it, and put it in the queue @@ -1404,9 +1389,7 @@ void Relooper::Calculate(Block* Entry) { IndependentGroups.size()); MultipleShape* Multiple = Parent->AddMultipleShape(); BlockSet CurrEntries; - for (auto& iter : IndependentGroups) { - Block* CurrEntry = iter.first; - BlockSet& CurrBlocks = iter.second; + for (auto& [CurrEntry, CurrBlocks] : IndependentGroups) { PrintDebug(" multiple group with entry %d:\n", CurrEntry->Id); DebugDump(CurrBlocks, " "); // Create inner block @@ -1563,8 +1546,7 @@ void Relooper::Calculate(Block* Entry) { bool DeadEnd = true; BlockSet& SmallGroup = IndependentGroups[SmallEntry]; for (auto* Curr : SmallGroup) { - for (auto& iter : Curr->BranchesOut) { - Block* Target = iter.first; + for (auto& [Target, _] : Curr->BranchesOut) { if (!contains(SmallGroup, Target)) { DeadEnd = false; break; @@ -1685,8 +1667,8 @@ void Debugging::Dump(Shape* S, const char* prefix) { printf("<< Simple with block %d\n", Simple->Inner->Id); } else if (MultipleShape* Multiple = Shape::IsMultiple(S)) { printf("<< Multiple\n"); - for (auto& iter : Multiple->InnerMap) { - printf(" with entry %d\n", iter.first); + for (auto& [Entry, _] : Multiple->InnerMap) { + printf(" with entry %d\n", Entry); } } else if (Shape::IsLoop(S)) { printf("<< Loop\n"); diff --git a/src/cfg/cfg-traversal.h b/src/cfg/cfg-traversal.h index 9b2027c42..faaa3c830 100644 --- a/src/cfg/cfg-traversal.h +++ b/src/cfg/cfg-traversal.h @@ -536,8 +536,8 @@ private: void checkDuplicates(std::vector<BasicBlock*>& list) { std::unordered_set<BasicBlock*> seen; for (auto* curr : list) { - assert(seen.count(curr) == 0); - seen.insert(curr); + auto res = seen.emplace(curr); + assert(res.second); } } diff --git a/src/dataflow/graph.h b/src/dataflow/graph.h index 6256c4c1e..0380adf14 100644 --- a/src/dataflow/graph.h +++ b/src/dataflow/graph.h @@ -31,9 +31,7 @@ #include "ir/literal-utils.h" #include "wasm.h" -namespace wasm { - -namespace DataFlow { +namespace wasm::DataFlow { // Main logic to generate IR for a function. This is implemented as a // visitor on the wasm, where visitors return a Node* that either @@ -797,8 +795,6 @@ struct Graph : public UnifiedExpressionVisitor<Graph, Node*> { const Name FAKE_CALL = "fake$dfo$call"; }; -} // namespace DataFlow - -} // namespace wasm +} // namespace wasm::DataFlow #endif // wasm_dataflow_graph_h diff --git a/src/dataflow/node.h b/src/dataflow/node.h index a59f01357..10e781769 100644 --- a/src/dataflow/node.h +++ b/src/dataflow/node.h @@ -28,9 +28,7 @@ #include "ir/utils.h" #include "wasm.h" -namespace wasm { - -namespace DataFlow { +namespace wasm::DataFlow { // // The core IR representation in DataFlow: a Node. @@ -218,8 +216,6 @@ struct Node { } }; -} // namespace DataFlow - -} // namespace wasm +} // namespace wasm::DataFlow #endif // wasm_dataflow_node diff --git a/src/dataflow/users.h b/src/dataflow/users.h index 369d18bbb..faa41f7f9 100644 --- a/src/dataflow/users.h +++ b/src/dataflow/users.h @@ -27,9 +27,7 @@ #include "dataflow/graph.h" -namespace wasm { - -namespace DataFlow { +namespace wasm::DataFlow { // Calculates the users of each node. // users[x] = { y, z, .. } @@ -95,8 +93,6 @@ public: void removeAllUsesOf(Node* node) { users.erase(node); } }; -} // namespace DataFlow - -} // namespace wasm +} // namespace wasm::DataFlow #endif // wasm_dataflow_users diff --git a/src/dataflow/utils.h b/src/dataflow/utils.h index 1cd93764c..af59c4111 100644 --- a/src/dataflow/utils.h +++ b/src/dataflow/utils.h @@ -29,9 +29,7 @@ #include "dataflow/node.h" #include "wasm.h" -namespace wasm { - -namespace DataFlow { +namespace wasm::DataFlow { inline std::ostream& dump(Node* node, std::ostream& o, size_t indent = 0) { auto doIndent = [&]() { @@ -147,8 +145,6 @@ inline bool allInputsConstant(Node* node) { return false; } -} // namespace DataFlow - -} // namespace wasm +} // namespace wasm::DataFlow #endif // wasm_dataflow_utils diff --git a/src/ir/ExpressionManipulator.cpp b/src/ir/ExpressionManipulator.cpp index 55d170175..20856808e 100644 --- a/src/ir/ExpressionManipulator.cpp +++ b/src/ir/ExpressionManipulator.cpp @@ -17,9 +17,7 @@ #include "ir/load-utils.h" #include "ir/utils.h" -namespace wasm { - -namespace ExpressionManipulator { +namespace wasm::ExpressionManipulator { Expression* flexibleCopy(Expression* original, Module& wasm, CustomCopier custom) { @@ -118,6 +116,4 @@ void spliceIntoBlock(Block* block, Index index, Expression* add) { block->finalize(block->type); } -} // namespace ExpressionManipulator - -} // namespace wasm +} // namespace wasm::ExpressionManipulator diff --git a/src/ir/LocalGraph.cpp b/src/ir/LocalGraph.cpp index 9deea9153..2b26ee828 100644 --- a/src/ir/LocalGraph.cpp +++ b/src/ir/LocalGraph.cpp @@ -135,7 +135,7 @@ struct Flower : public CFGWalker<Flower, Visitor<Flower>, Info> { // Convert unordered_map to vector. flowBlock.lastSets.reserve(block->contents.lastSets.size()); for (auto set : block->contents.lastSets) { - flowBlock.lastSets.emplace_back(std::make_pair(set.first, set.second)); + flowBlock.lastSets.emplace_back(set); } } assert(entryFlowBlock != nullptr); @@ -232,9 +232,7 @@ LocalGraph::LocalGraph(Function* func) : func(func) { #ifdef LOCAL_GRAPH_DEBUG std::cout << "LocalGraph::dump\n"; - for (auto& pair : getSetses) { - auto* get = pair.first; - auto& sets = pair.second; + for (auto& [get, sets] : getSetses) { std::cout << "GET\n" << get << " is influenced by\n"; for (auto* set : sets) { std::cout << set << '\n'; @@ -282,8 +280,7 @@ bool LocalGraph::equivalent(LocalGet* a, LocalGet* b) { } void LocalGraph::computeSetInfluences() { - for (auto& pair : locations) { - auto* curr = pair.first; + for (auto& [curr, _] : locations) { if (auto* get = curr->dynCast<LocalGet>()) { for (auto* set : getSetses[get]) { setInfluences[set].insert(get); @@ -293,8 +290,7 @@ void LocalGraph::computeSetInfluences() { } void LocalGraph::computeGetInfluences() { - for (auto& pair : locations) { - auto* curr = pair.first; + for (auto& [curr, _] : locations) { if (auto* set = curr->dynCast<LocalSet>()) { FindAll<LocalGet> findAll(set->value); for (auto* get : findAll.list) { @@ -306,15 +302,12 @@ void LocalGraph::computeGetInfluences() { void LocalGraph::computeSSAIndexes() { std::unordered_map<Index, std::set<LocalSet*>> indexSets; - for (auto& pair : getSetses) { - auto* get = pair.first; - auto& sets = pair.second; + for (auto& [get, sets] : getSetses) { for (auto* set : sets) { indexSets[get->index].insert(set); } } - for (auto& pair : locations) { - auto* curr = pair.first; + for (auto& [curr, _] : locations) { if (auto* set = curr->dynCast<LocalSet>()) { auto& sets = indexSets[set->index]; if (sets.size() == 1 && *sets.begin() != curr) { @@ -324,9 +317,7 @@ void LocalGraph::computeSSAIndexes() { } } } - for (auto& pair : indexSets) { - auto index = pair.first; - auto& sets = pair.second; + for (auto& [index, sets] : indexSets) { if (sets.size() == 1) { SSAIndexes.insert(index); } diff --git a/src/ir/abstract.h b/src/ir/abstract.h index 18df7869e..3975386da 100644 --- a/src/ir/abstract.h +++ b/src/ir/abstract.h @@ -21,9 +21,7 @@ #include <wasm.h> -namespace wasm { - -namespace Abstract { +namespace wasm::Abstract { enum Op { // Unary @@ -310,8 +308,6 @@ inline BinaryOp getBinary(Type type, Op op) { WASM_UNREACHABLE("invalid type"); } -} // namespace Abstract - -} // namespace wasm +} // namespace wasm::Abstract #endif // wasm_ir_abstract_h diff --git a/src/ir/bits.h b/src/ir/bits.h index dc02bd8f8..21146b3d1 100644 --- a/src/ir/bits.h +++ b/src/ir/bits.h @@ -22,9 +22,7 @@ #include "wasm-builder.h" #include <ir/load-utils.h> -namespace wasm { - -namespace Bits { +namespace wasm::Bits { // get a mask to keep only the low # of bits inline int32_t lowBitMask(int32_t bits) { @@ -435,8 +433,6 @@ Index getMaxBits(Expression* curr, } } -} // namespace Bits - -} // namespace wasm +} // namespace wasm::Bits #endif // wasm_ir_bits_h diff --git a/src/ir/block-utils.h b/src/ir/block-utils.h index be24cf483..25d4d63bc 100644 --- a/src/ir/block-utils.h +++ b/src/ir/block-utils.h @@ -24,9 +24,8 @@ #include "wasm-builder.h" #include "wasm.h" -namespace wasm { +namespace wasm::BlockUtils { -namespace BlockUtils { // if a block has just one element, it can often be replaced // with that content template<typename T> @@ -68,8 +67,6 @@ inline Expression* simplifyToContentsWithPossibleTypeChange(Block* block, T* parent) { return simplifyToContents(block, parent, true); } -} // namespace BlockUtils - -} // namespace wasm +} // namespace wasm::BlockUtils #endif // wasm_ir_block_h diff --git a/src/ir/branch-utils.h b/src/ir/branch-utils.h index 603b922fb..58daf5e84 100644 --- a/src/ir/branch-utils.h +++ b/src/ir/branch-utils.h @@ -21,9 +21,7 @@ #include "wasm-traversal.h" #include "wasm.h" -namespace wasm { - -namespace BranchUtils { +namespace wasm::BranchUtils { // Some branches are obviously not actually reachable (e.g. (br $out // (unreachable))) @@ -428,8 +426,6 @@ private: } inner; }; -} // namespace BranchUtils - -} // namespace wasm +} // namespace wasm::BranchUtils #endif // wasm_ir_branch_h diff --git a/src/ir/debug.h b/src/ir/debug.h index d4ecf2b70..6dfd379d6 100644 --- a/src/ir/debug.h +++ b/src/ir/debug.h @@ -19,9 +19,7 @@ #include <wasm-traversal.h> -namespace wasm { - -namespace debug { +namespace wasm::debug { // Given an expression and a copy of it in another function, copy the debug // info into the second function. @@ -52,8 +50,6 @@ inline void copyDebugInfo(Expression* origin, } }; -} // namespace debug - -} // namespace wasm +} // namespace wasm::debug #endif // wasm_ir_debug_h diff --git a/src/ir/element-utils.h b/src/ir/element-utils.h index 1ec6c7e20..e7ff54b91 100644 --- a/src/ir/element-utils.h +++ b/src/ir/element-utils.h @@ -20,9 +20,7 @@ #include "wasm-builder.h" #include "wasm.h" -namespace wasm { - -namespace ElementUtils { +namespace wasm::ElementUtils { // iterate over functions referenced in an element segment template<typename T> @@ -48,8 +46,6 @@ inline void iterAllElementFunctionNames(const Module* wasm, T visitor) { } } -} // namespace ElementUtils - -} // namespace wasm +} // namespace wasm::ElementUtils #endif // wasm_ir_element_h diff --git a/src/ir/features.h b/src/ir/features.h index 791a4dded..3755412c9 100644 --- a/src/ir/features.h +++ b/src/ir/features.h @@ -22,9 +22,7 @@ #include <wasm-traversal.h> #include <wasm.h> -namespace wasm { - -namespace Features { +namespace wasm::Features { inline FeatureSet get(UnaryOp op) { FeatureSet ret; @@ -166,8 +164,6 @@ inline FeatureSet get(BinaryOp op) { return ret; } -} // namespace Features - -} // namespace wasm +} // namespace wasm::Features #endif // wasm_ir_features_h diff --git a/src/ir/flat.h b/src/ir/flat.h index 273acc42f..37b5dfb15 100644 --- a/src/ir/flat.h +++ b/src/ir/flat.h @@ -67,9 +67,7 @@ #include "pass.h" #include "wasm-traversal.h" -namespace wasm { - -namespace Flat { +namespace wasm::Flat { inline void verifyFlatness(Function* func) { struct VerifyFlatness @@ -127,8 +125,6 @@ inline void verifyFlatness(Module* module) { VerifyFlatness().run(&runner, module); } -} // namespace Flat - -} // namespace wasm +} // namespace wasm::Flat #endif // wasm_ir_flat_h diff --git a/src/ir/function-utils.h b/src/ir/function-utils.h index b1654d965..ebdef0cd4 100644 --- a/src/ir/function-utils.h +++ b/src/ir/function-utils.h @@ -20,9 +20,7 @@ #include "ir/utils.h" #include "wasm.h" -namespace wasm { - -namespace FunctionUtils { +namespace wasm::FunctionUtils { // Checks if two functions are equal in all functional aspects, // everything but their name (which can't be the same, in the same @@ -45,8 +43,6 @@ inline bool equal(Function* left, Function* right) { return left->imported() && right->imported(); } -} // namespace FunctionUtils - -} // namespace wasm +} // namespace wasm::FunctionUtils #endif // wasm_ir_function_h diff --git a/src/ir/gc-type-utils.h b/src/ir/gc-type-utils.h index 70db7b178..80a935462 100644 --- a/src/ir/gc-type-utils.h +++ b/src/ir/gc-type-utils.h @@ -19,9 +19,7 @@ #include "wasm.h" -namespace wasm { - -namespace GCTypeUtils { +namespace wasm::GCTypeUtils { // Helper code to evaluate a reference at compile time and check if it is of a // certain kind. Various wasm instructions check if something is a function or @@ -141,8 +139,6 @@ inline EvaluationResult evaluateKindCheck(Expression* curr) { return success ? Success : Failure; } -} // namespace GCTypeUtils - -} // namespace wasm +} // namespace wasm::GCTypeUtils #endif // wasm_ir_gc_type_utils_h diff --git a/src/ir/global-utils.h b/src/ir/global-utils.h index 34c0e56cf..26aec7790 100644 --- a/src/ir/global-utils.h +++ b/src/ir/global-utils.h @@ -25,9 +25,8 @@ #include "literal.h" #include "wasm.h" -namespace wasm { +namespace wasm::GlobalUtils { -namespace GlobalUtils { // find a global initialized to the value of an import, or null if no such // global inline Global* @@ -76,8 +75,6 @@ inline bool canInitializeGlobal(Expression* curr) { return false; } -} // namespace GlobalUtils - -} // namespace wasm +} // namespace wasm::GlobalUtils #endif // wasm_ir_global_h diff --git a/src/ir/label-utils.h b/src/ir/label-utils.h index 75c3b3a41..4ed73edb5 100644 --- a/src/ir/label-utils.h +++ b/src/ir/label-utils.h @@ -20,9 +20,7 @@ #include "wasm-traversal.h" #include "wasm.h" -namespace wasm { - -namespace LabelUtils { +namespace wasm::LabelUtils { // Handles branch/loop labels in a function; makes it easy to add new // ones without duplicates @@ -33,8 +31,7 @@ public: Name getUnique(std::string prefix) { while (1) { auto curr = Name(prefix + std::to_string(counter++)); - if (labels.find(curr) == labels.end()) { - labels.insert(curr); + if (labels.emplace(curr).second) { return curr; } } @@ -48,8 +45,6 @@ private: size_t counter = 0; }; -} // namespace LabelUtils - -} // namespace wasm +} // namespace wasm::LabelUtils #endif // wasm_ir_label_h diff --git a/src/ir/literal-utils.h b/src/ir/literal-utils.h index 21ade6d84..ad022344e 100644 --- a/src/ir/literal-utils.h +++ b/src/ir/literal-utils.h @@ -20,9 +20,7 @@ #include "wasm-builder.h" #include "wasm.h" -namespace wasm { - -namespace LiteralUtils { +namespace wasm::LiteralUtils { inline Expression* makeFromInt32(int32_t x, Type type, Module& wasm) { auto* ret = wasm.allocator.alloc<Const>(); @@ -64,8 +62,6 @@ inline Expression* makeZero(Type type, Module& wasm) { return builder.makeConstantExpression(Literal::makeZeros(type)); } -} // namespace LiteralUtils - -} // namespace wasm +} // namespace wasm::LiteralUtils #endif // wasm_ir_literal_utils_h diff --git a/src/ir/load-utils.h b/src/ir/load-utils.h index 62c31ef4e..011bdcbdf 100644 --- a/src/ir/load-utils.h +++ b/src/ir/load-utils.h @@ -19,9 +19,7 @@ #include "wasm.h" -namespace wasm { - -namespace LoadUtils { +namespace wasm::LoadUtils { // checks if the sign of a load matters, which is when an integer // load is of fewer bytes than the size of the type (so we must @@ -37,8 +35,6 @@ inline bool isSignRelevant(Load* load) { // check if a load can be signed (which some opts want to do) inline bool canBeSigned(Load* load) { return !load->isAtomic; } -} // namespace LoadUtils - -} // namespace wasm +} // namespace wasm::LoadUtils #endif // wasm_ir_load_h diff --git a/src/ir/manipulation.h b/src/ir/manipulation.h index fb1f0181e..54822f2bd 100644 --- a/src/ir/manipulation.h +++ b/src/ir/manipulation.h @@ -19,9 +19,8 @@ #include "wasm.h" -namespace wasm { +namespace wasm::ExpressionManipulator { -namespace ExpressionManipulator { // Re-use a node's memory. This helps avoid allocation when optimizing. template<typename InputType, typename OutputType> inline OutputType* convert(InputType* input) { @@ -75,8 +74,6 @@ inline Expression* copy(Expression* original, Module& wasm) { // Splice an item into the middle of a block's list void spliceIntoBlock(Block* block, Index index, Expression* add); -} // namespace ExpressionManipulator - -} // namespace wasm +} // namespace wasm::ExpressionManipulator #endif // wams_ir_manipulation_h diff --git a/src/ir/match.h b/src/ir/match.h index 0d8d3c20a..dcd899d9e 100644 --- a/src/ir/match.h +++ b/src/ir/match.h @@ -27,9 +27,7 @@ #include "ir/abstract.h" #include "wasm.h" -namespace wasm { - -namespace Match { +namespace wasm::Match { // The available matchers are: // @@ -872,8 +870,6 @@ inline decltype(auto) select(Select** binder, S1&& s1, S2&& s2, S3&& s3) { return Internal::SelectMatcher(binder, s1, s2, s3); } -} // namespace Match - -} // namespace wasm +} // namespace wasm::Match #endif // wasm_ir_match_h diff --git a/src/ir/memory-utils.h b/src/ir/memory-utils.h index 432fed0aa..3a0862cd7 100644 --- a/src/ir/memory-utils.h +++ b/src/ir/memory-utils.h @@ -25,9 +25,8 @@ #include "wasm-builder.h" #include "wasm.h" -namespace wasm { +namespace wasm::MemoryUtils { -namespace MemoryUtils { // Flattens memory into a single data segment, or no segment. If there is // a segment, it starts at 0. // If ensuredSegmentSize is provided, then a segment is always emitted, @@ -198,8 +197,6 @@ inline bool ensureLimitedSegments(Module& module) { memory.segments.swap(mergedSegments); return true; } -} // namespace MemoryUtils - -} // namespace wasm +} // namespace wasm::MemoryUtils #endif // wasm_ir_memory_h diff --git a/src/ir/module-splitting.cpp b/src/ir/module-splitting.cpp index 2028db13f..dc04cdba2 100644 --- a/src/ir/module-splitting.cpp +++ b/src/ir/module-splitting.cpp @@ -76,9 +76,7 @@ #include "wasm-builder.h" #include "wasm.h" -namespace wasm { - -namespace ModuleSplitting { +namespace wasm::ModuleSplitting { namespace { @@ -664,6 +662,4 @@ Results splitFunctions(Module& primary, const Config& config) { return {std::move(split.secondaryPtr), std::move(split.placeholderMap)}; } -} // namespace ModuleSplitting - -} // namespace wasm +} // namespace wasm::ModuleSplitting diff --git a/src/ir/module-splitting.h b/src/ir/module-splitting.h index cfbd45b14..2cc6760c0 100644 --- a/src/ir/module-splitting.h +++ b/src/ir/module-splitting.h @@ -42,9 +42,7 @@ #include "wasm.h" -namespace wasm { - -namespace ModuleSplitting { +namespace wasm::ModuleSplitting { struct Config { // The set of functions to keep in the primary module. All others are split @@ -76,8 +74,6 @@ struct Results { // Returns the new secondary module and modifies the `primary` module in place. Results splitFunctions(Module& primary, const Config& config); -} // namespace ModuleSplitting - -} // namespace wasm +} // namespace wasm::ModuleSplitting #endif // wasm_ir_module_splitting_h diff --git a/src/ir/module-utils.h b/src/ir/module-utils.h index d37457e96..1d56c1a3e 100644 --- a/src/ir/module-utils.h +++ b/src/ir/module-utils.h @@ -26,9 +26,7 @@ #include "support/unique_deferring_queue.h" #include "wasm.h" -namespace wasm { - -namespace ModuleUtils { +namespace wasm::ModuleUtils { // Copies a function into a module. If newName is provided it is used as the // name of the function (otherwise the original name is copied). @@ -155,10 +153,10 @@ inline void clearModule(Module& wasm) { // call this redirect all of its uses. template<typename T> inline void renameFunctions(Module& wasm, T& map) { // Update the function itself. - for (auto& pair : map) { - if (Function* F = wasm.getFunctionOrNull(pair.first)) { - assert(!wasm.getFunctionOrNull(pair.second) || F->name == pair.second); - F->name = pair.second; + for (auto& [oldName, newName] : map) { + if (Function* F = wasm.getFunctionOrNull(oldName)) { + assert(!wasm.getFunctionOrNull(newName) || F->name == newName); + F->name = newName; } } wasm.updateMaps(); @@ -415,9 +413,7 @@ template<typename T> struct CallGraphPropertyAnalysis { map.swap(analysis.map); // Find what is called by what. - for (auto& pair : map) { - auto* func = pair.first; - auto& info = pair.second; + for (auto& [func, info] : map) { for (auto* target : info.callsTo) { map[target].calledBy.insert(func); } @@ -568,10 +564,9 @@ inline void collectHeapTypes(Module& wasm, }); // Combine the function info with the module info. - for (const auto& pair : analysis.map) { - const Counts& functionCounts = pair.second; - for (const auto& innerPair : functionCounts) { - counts[innerPair.first] += innerPair.second; + for (auto& [_, functionCounts] : analysis.map) { + for (auto& [sig, count] : functionCounts) { + counts[sig] += count; } } @@ -582,8 +577,8 @@ inline void collectHeapTypes(Module& wasm, // previous ones. Each such type will appear in the type section once, so // we just need to visit it once. InsertOrderedSet<HeapType> newTypes; - for (auto& pair : counts) { - newTypes.insert(pair.first); + for (auto& [type, _] : counts) { + newTypes.insert(type); } while (!newTypes.empty()) { auto iter = newTypes.begin(); @@ -621,8 +616,6 @@ inline void collectHeapTypes(Module& wasm, } } -} // namespace ModuleUtils - -} // namespace wasm +} // namespace wasm::ModuleUtils #endif // wasm_ir_module_h diff --git a/src/ir/names.cpp b/src/ir/names.cpp index cbc703438..f18a08916 100644 --- a/src/ir/names.cpp +++ b/src/ir/names.cpp @@ -17,9 +17,7 @@ #include "ir/names.h" #include <sstream> -namespace wasm { - -namespace Names { +namespace wasm::Names { // Reserved words in JS that we will not emit up to size 4 - size 5 and above // would mean we use an astronomical number of symbols, which is not realistic @@ -72,6 +70,4 @@ std::string MinifiedNameGenerator::getName() { return name; } -} // namespace Names - -} // namespace wasm +} // namespace wasm::Names diff --git a/src/ir/names.h b/src/ir/names.h index 5fe77dd2b..af6ca1562 100644 --- a/src/ir/names.h +++ b/src/ir/names.h @@ -18,26 +18,23 @@ #include "wasm.h" -namespace wasm { - -namespace Names { +namespace wasm::Names { // Add explicit names for function locals not yet named, and do not // modify existing names inline void ensureNames(Function* func) { std::unordered_set<Name> seen; - for (auto& pair : func->localNames) { - seen.insert(pair.second); + for (auto& [_, name] : func->localNames) { + seen.insert(name); } Index nameIndex = seen.size(); for (Index i = 0; i < func->getNumLocals(); i++) { if (!func->hasLocalName(i)) { while (1) { auto name = Name::fromInt(nameIndex++); - if (seen.count(name) == 0) { + if (seen.emplace(name).second) { func->localNames[i] = name; func->localIndices[name] = i; - seen.insert(name); break; } } @@ -95,8 +92,6 @@ public: std::string getName(); }; -} // namespace Names - -} // namespace wasm +} // namespace wasm::Names #endif // wasm_ir_names_h diff --git a/src/ir/properties.cpp b/src/ir/properties.cpp index 4739fcaaf..b5d2df952 100644 --- a/src/ir/properties.cpp +++ b/src/ir/properties.cpp @@ -17,9 +17,7 @@ #include "ir/properties.h" #include "wasm-traversal.h" -namespace wasm { - -namespace Properties { +namespace wasm::Properties { bool isGenerative(Expression* curr, FeatureSet features) { // Practically no wasm instructions are generative. Exceptions occur only in @@ -38,6 +36,4 @@ bool isGenerative(Expression* curr, FeatureSet features) { return scanner.generative; } -} // namespace Properties - -} // namespace wasm +} // namespace wasm::Properties diff --git a/src/ir/properties.h b/src/ir/properties.h index 92f1bda66..8800f1049 100644 --- a/src/ir/properties.h +++ b/src/ir/properties.h @@ -22,9 +22,7 @@ #include "ir/match.h" #include "wasm.h" -namespace wasm { - -namespace Properties { +namespace wasm::Properties { inline bool emitsBoolean(Expression* curr) { if (auto* unary = curr->dynCast<Unary>()) { @@ -416,8 +414,6 @@ inline bool canEmitSelectWithArms(Expression* ifTrue, Expression* ifFalse) { // bool isGenerative(Expression* curr, FeatureSet features); -} // namespace Properties - -} // namespace wasm +} // namespace wasm::Properties #endif // wasm_ir_properties_h diff --git a/src/ir/struct-utils.h b/src/ir/struct-utils.h index f1741fb27..f68692363 100644 --- a/src/ir/struct-utils.h +++ b/src/ir/struct-utils.h @@ -59,9 +59,7 @@ struct StructValuesMap : public std::unordered_map<HeapType, StructValues<T>> { } void combineInto(StructValuesMap<T>& combinedInfos) const { - for (auto& kv : *this) { - auto type = kv.first; - auto& info = kv.second; + for (auto& [type, info] : *this) { for (Index i = 0; i < info.size(); i++) { combinedInfos[type][i].combine(info[i]); } @@ -70,9 +68,7 @@ struct StructValuesMap : public std::unordered_map<HeapType, StructValues<T>> { void dump(std::ostream& o) { o << "dump " << this << '\n'; - for (auto& kv : (*this)) { - auto type = kv.first; - auto& vec = kv.second; + for (auto& [type, vec] : (*this)) { o << "dump " << type << " " << &vec << ' '; for (auto x : vec) { x.dump(o); @@ -235,8 +231,7 @@ public: private: void propagate(StructValuesMap<T>& combinedInfos, bool toSubTypes) { UniqueDeferredQueue<HeapType> work; - for (auto& kv : combinedInfos) { - auto type = kv.first; + for (auto& [type, _] : combinedInfos) { work.push(type); } while (!work.empty()) { diff --git a/src/ir/table-utils.cpp b/src/ir/table-utils.cpp index 79b90d249..0d47f155b 100644 --- a/src/ir/table-utils.cpp +++ b/src/ir/table-utils.cpp @@ -19,9 +19,7 @@ #include "find_all.h" #include "module-utils.h" -namespace wasm { - -namespace TableUtils { +namespace wasm::TableUtils { std::set<Name> getFunctionsNeedingElemDeclare(Module& wasm) { // Without reference types there are no ref.funcs or elem declare. @@ -83,6 +81,4 @@ bool usesExpressions(ElementSegment* curr, Module* module) { return !allElementsRefFunc || hasTableOfSpecializedType; } -} // namespace TableUtils - -} // namespace wasm +} // namespace wasm::TableUtils diff --git a/src/ir/table-utils.h b/src/ir/table-utils.h index e4cf409c1..a94691e9f 100644 --- a/src/ir/table-utils.h +++ b/src/ir/table-utils.h @@ -23,9 +23,7 @@ #include "wasm-traversal.h" #include "wasm.h" -namespace wasm { - -namespace TableUtils { +namespace wasm::TableUtils { struct FlatTable { std::vector<Name> names; @@ -115,8 +113,6 @@ std::set<Name> getFunctionsNeedingElemDeclare(Module& wasm); // do so, and some do not, depending on their type and use.) bool usesExpressions(ElementSegment* curr, Module* module); -} // namespace TableUtils - -} // namespace wasm +} // namespace wasm::TableUtils #endif // wasm_ir_table_h diff --git a/src/ir/trapping.h b/src/ir/trapping.h index e6eca9e53..6272bbf0f 100644 --- a/src/ir/trapping.h +++ b/src/ir/trapping.h @@ -58,11 +58,11 @@ public: void addToModule() { if (!immediate) { - for (auto& pair : functions) { - wasm.addFunction(pair.second); + for (auto& [_, func] : functions) { + wasm.addFunction(func); } - for (auto& pair : imports) { - wasm.addFunction(pair.second); + for (auto& [_, func] : imports) { + wasm.addFunction(func); } } functions.clear(); diff --git a/src/ir/type-updating.cpp b/src/ir/type-updating.cpp index 998e12ebb..2920a4a95 100644 --- a/src/ir/type-updating.cpp +++ b/src/ir/type-updating.cpp @@ -189,9 +189,7 @@ void GlobalTypeRewriter::update() { } // Update type names. - for (auto& kv : oldToNewTypes) { - auto old = kv.first; - auto new_ = kv.second; + for (auto& [old, new_] : oldToNewTypes) { if (wasm.typeNames.count(old)) { wasm.typeNames[new_] = wasm.typeNames[old]; } diff --git a/src/passes/Asyncify.cpp b/src/passes/Asyncify.cpp index 5b96d6e86..7b03741d9 100644 --- a/src/passes/Asyncify.cpp +++ b/src/passes/Asyncify.cpp @@ -630,9 +630,7 @@ public: }); // Functions in the remove-list are assumed to not change the state. - for (auto& pair : scanner.map) { - auto* func = pair.first; - auto& info = pair.second; + for (auto& [func, info] : scanner.map) { if (removeList.match(func->name)) { info.inRemoveList = true; if (verbose && info.canChangeState) { @@ -645,9 +643,8 @@ public: // Remove the asyncify imports, if any, and any calls to them. std::vector<Name> funcsToDelete; - for (auto& pair : scanner.map) { - auto* func = pair.first; - auto& callsTo = pair.second.callsTo; + for (auto& [func, info] : scanner.map) { + auto& callsTo = info.callsTo; if (func->imported() && func->module == ASYNCIFY) { funcsToDelete.push_back(func->name); } diff --git a/src/passes/AvoidReinterprets.cpp b/src/passes/AvoidReinterprets.cpp index d1030f89e..c2607725d 100644 --- a/src/passes/AvoidReinterprets.cpp +++ b/src/passes/AvoidReinterprets.cpp @@ -54,13 +54,12 @@ static Load* getSingleLoad(LocalGraph* localGraph, } auto* value = Properties::getFallthrough(set->value, passOptions, module); if (auto* parentGet = value->dynCast<LocalGet>()) { - if (seen.count(parentGet)) { - // We are in a cycle of gets, in unreachable code. - return nullptr; + if (seen.emplace(parentGet).second) { + get = parentGet; + continue; } - get = parentGet; - seen.insert(get); - continue; + // We are in a cycle of gets, in unreachable code. + return nullptr; } if (auto* load = value->dynCast<Load>()) { return load; @@ -117,9 +116,7 @@ struct AvoidReinterprets : public WalkerPass<PostWalker<AvoidReinterprets>> { void optimize(Function* func) { std::set<Load*> unoptimizables; auto indexType = getModule()->memory.indexType; - for (auto& pair : infos) { - auto* load = pair.first; - auto& info = pair.second; + for (auto& [load, info] : infos) { if (info.reinterpreted && canReplaceWithReinterpret(load)) { // We should use another load here, to avoid reinterprets. info.ptrLocal = Builder::addVar(func, indexType); diff --git a/src/passes/CodeFolding.cpp b/src/passes/CodeFolding.cpp index 886b5b891..7a492dbea 100644 --- a/src/passes/CodeFolding.cpp +++ b/src/passes/CodeFolding.cpp @@ -617,10 +617,10 @@ private: for (auto& tail : next) { auto* item = getItem(tail, num); auto digest = hashes[item]; - if (seen.count(digest)) { + if (!seen.emplace(digest).second) { continue; } - seen.insert(digest); + auto& items = hashed[digest]; if (items.size() == 1) { continue; diff --git a/src/passes/ConstHoisting.cpp b/src/passes/ConstHoisting.cpp index 1caf0eb28..a85b9cdf2 100644 --- a/src/passes/ConstHoisting.cpp +++ b/src/passes/ConstHoisting.cpp @@ -54,9 +54,7 @@ struct ConstHoisting : public WalkerPass<PostWalker<ConstHoisting>> { void visitFunction(Function* curr) { std::vector<Expression*> prelude; - for (auto& pair : uses) { - auto value = pair.first; - auto& vec = pair.second; + for (auto& [value, vec] : uses) { auto num = vec.size(); if (worthHoisting(value, num)) { prelude.push_back(hoist(vec)); diff --git a/src/passes/DeadArgumentElimination.cpp b/src/passes/DeadArgumentElimination.cpp index b6694c514..89e47708b 100644 --- a/src/passes/DeadArgumentElimination.cpp +++ b/src/passes/DeadArgumentElimination.cpp @@ -210,10 +210,8 @@ struct DAEScanner std::vector<Item> work; work.emplace_back(entry, initial); while (!work.empty()) { - auto item = std::move(work.back()); + auto [block, indexes] = std::move(work.back()); work.pop_back(); - auto* block = item.first; - auto& indexes = item.second; // Ignore things we've already seen, or we've already seen to be used. auto& seenIndexes = seenBlockIndexes[block]; indexes.filter([&](const Index i) { @@ -295,19 +293,16 @@ struct DAE : public Pass { // Combine all the info. std::unordered_map<Name, std::vector<Call*>> allCalls; std::unordered_set<Name> tailCallees; - for (auto& pair : infoMap) { - auto& info = pair.second; - for (auto& pair : info.calls) { - auto name = pair.first; - auto& calls = pair.second; + for (auto& [_, info] : infoMap) { + for (auto& [name, calls] : info.calls) { auto& allCallsToName = allCalls[name]; allCallsToName.insert(allCallsToName.end(), calls.begin(), calls.end()); } for (auto& callee : info.tailCallees) { tailCallees.insert(callee); } - for (auto& pair : info.droppedCalls) { - allDroppedCalls[pair.first] = pair.second; + for (auto& [name, calls] : info.droppedCalls) { + allDroppedCalls[name] = calls; } } // If we refine return types then we will need to do more type updating @@ -315,13 +310,11 @@ struct DAE : public Pass { bool refinedReturnTypes = false; // We now have a mapping of all call sites for each function, and can look // for optimization opportunities. - for (auto& pair : allCalls) { - auto name = pair.first; + for (auto& [name, calls] : allCalls) { // We can only optimize if we see all the calls and can modify them. if (infoMap[name].hasUnseenCalls) { continue; } - auto& calls = pair.second; auto* func = module->getFunction(name); auto numParams = func->getNumParams(); // Refine argument types before doing anything else. This does not @@ -376,9 +369,7 @@ struct DAE : public Pass { // Track which functions we changed, and optimize them later if necessary. std::unordered_set<Function*> changed; // We now know which parameters are unused, and can potentially remove them. - for (auto& pair : allCalls) { - auto name = pair.first; - auto& calls = pair.second; + for (auto& [name, calls] : allCalls) { if (infoMap[name].hasUnseenCalls) { continue; } diff --git a/src/passes/Directize.cpp b/src/passes/Directize.cpp index 1dd05e934..6853f1faf 100644 --- a/src/passes/Directize.cpp +++ b/src/passes/Directize.cpp @@ -196,8 +196,8 @@ struct Directize : public Pass { }); TablesWithSet tablesWithSet; - for (auto& kv : analysis.map) { - for (auto name : kv.second) { + for (auto& [_, names] : analysis.map) { + for (auto name : names) { tablesWithSet.insert(name); } } diff --git a/src/passes/DuplicateFunctionElimination.cpp b/src/passes/DuplicateFunctionElimination.cpp index ce17a0a07..2e8c83cdd 100644 --- a/src/passes/DuplicateFunctionElimination.cpp +++ b/src/passes/DuplicateFunctionElimination.cpp @@ -62,8 +62,7 @@ struct DuplicateFunctionElimination : public Pass { // Find actually equal functions and prepare to replace them std::map<Name, Name> replacements; std::set<Name> duplicates; - for (auto& pair : hashGroups) { - auto& group = pair.second; + for (auto& [_, group] : hashGroups) { Index size = group.size(); if (size == 1) { continue; diff --git a/src/passes/DuplicateImportElimination.cpp b/src/passes/DuplicateImportElimination.cpp index a4d9065c5..faf2bb776 100644 --- a/src/passes/DuplicateImportElimination.cpp +++ b/src/passes/DuplicateImportElimination.cpp @@ -34,7 +34,7 @@ struct DuplicateImportElimination : public Pass { std::map<std::pair<Name, Name>, Name> seen; std::vector<Name> toRemove; for (auto* func : imports.importedFunctions) { - auto pair = std::make_pair(func->module, func->base); + auto pair = std::pair{func->module, func->base}; auto iter = seen.find(pair); if (iter != seen.end()) { auto previousName = iter->second; diff --git a/src/passes/Heap2Local.cpp b/src/passes/Heap2Local.cpp index fc3c18db0..19259e864 100644 --- a/src/passes/Heap2Local.cpp +++ b/src/passes/Heap2Local.cpp @@ -506,10 +506,9 @@ struct Heap2LocalOptimizer { // look at something that another allocation reached, which would be in a // different call to this function and use a different queue (any overlap // between calls would prove non-exclusivity). - if (seen.count(parent)) { + if (!seen.emplace(parent).second) { return false; } - seen.insert(parent); switch (getParentChildInteraction(parent, child)) { case ParentChildInteraction::Escapes: { diff --git a/src/passes/Inlining.cpp b/src/passes/Inlining.cpp index a79968c92..018654882 100644 --- a/src/passes/Inlining.cpp +++ b/src/passes/Inlining.cpp @@ -490,9 +490,7 @@ struct FunctionSplitter { std::vector<Name> finish() { std::vector<Name> ret; std::unordered_set<Name> inlineableNames; - for (auto& kv : splits) { - Name func = kv.first; - auto& split = kv.second; + for (auto& [func, split] : splits) { auto* inlineable = split.inlineable; if (inlineable) { inlineableNames.insert(inlineable->name); diff --git a/src/passes/LocalCSE.cpp b/src/passes/LocalCSE.cpp index d63c217de..f487986a3 100644 --- a/src/passes/LocalCSE.cpp +++ b/src/passes/LocalCSE.cpp @@ -195,9 +195,7 @@ struct RequestInfo { // A map of expressions to their request info. struct RequestInfoMap : public std::unordered_map<Expression*, RequestInfo> { void dump(std::ostream& o) { - for (auto& kv : *this) { - auto* curr = kv.first; - auto& info = kv.second; + for (auto& [curr, info] : *this) { o << *curr << " has " << info.requests << " reqs, orig: " << info.original << '\n'; } diff --git a/src/passes/LocalSubtyping.cpp b/src/passes/LocalSubtyping.cpp index a8174aa2d..b6e94b771 100644 --- a/src/passes/LocalSubtyping.cpp +++ b/src/passes/LocalSubtyping.cpp @@ -59,8 +59,7 @@ struct LocalSubtyping : public WalkerPass<PostWalker<LocalSubtyping>> { std::vector<std::vector<LocalSet*>> setsForLocal(numLocals); std::vector<std::vector<LocalGet*>> getsForLocal(numLocals); - for (auto& kv : localGraph.locations) { - auto* curr = kv.first; + for (auto& [curr, _] : localGraph.locations) { if (auto* set = curr->dynCast<LocalSet>()) { setsForLocal[set->index].push_back(set); } else { @@ -78,9 +77,7 @@ struct LocalSubtyping : public WalkerPass<PostWalker<LocalSubtyping>> { std::unordered_set<Index> usesDefault; if (getModule()->features.hasGCNNLocals()) { - for (auto& kv : localGraph.getSetses) { - auto* get = kv.first; - auto& sets = kv.second; + for (auto& [get, sets] : localGraph.getSetses) { auto index = get->index; if (func->isVar(index) && std::any_of(sets.begin(), sets.end(), [&](LocalSet* set) { diff --git a/src/passes/MergeLocals.cpp b/src/passes/MergeLocals.cpp index a55d81cf6..e478db739 100644 --- a/src/passes/MergeLocals.cpp +++ b/src/passes/MergeLocals.cpp @@ -193,9 +193,7 @@ struct MergeLocals // logic as before). LocalGraph postGraph(func); postGraph.computeSetInfluences(); - for (auto& pair : optimizedToCopy) { - auto* copy = pair.first; - auto* trivial = pair.second; + for (auto& [copy, trivial] : optimizedToCopy) { auto& trivialInfluences = preGraph.setInfluences[trivial]; for (auto* influencedGet : trivialInfluences) { // verify the set @@ -209,9 +207,7 @@ struct MergeLocals } } } - for (auto& pair : optimizedToTrivial) { - auto* copy = pair.first; - auto* trivial = pair.second; + for (auto& [copy, trivial] : optimizedToTrivial) { auto& copyInfluences = preGraph.setInfluences[copy]; for (auto* influencedGet : copyInfluences) { // verify the set diff --git a/src/passes/Metrics.cpp b/src/passes/Metrics.cpp index 4cd5d8ef4..566738161 100644 --- a/src/passes/Metrics.cpp +++ b/src/passes/Metrics.cpp @@ -170,11 +170,11 @@ struct Metrics std::vector<const char*> keys; // add total int total = 0; - for (auto i : counts) { - keys.push_back(i.first); + for (auto& [key, value] : counts) { + keys.push_back(key); // total is of all the normal stuff, not the special [things] - if (i.first[0] != '[') { - total += i.second; + if (key[0] != '[') { + total += value; } } keys.push_back("[total]"); diff --git a/src/passes/MinifyImportsAndExports.cpp b/src/passes/MinifyImportsAndExports.cpp index cad6bd9da..02675e49b 100644 --- a/src/passes/MinifyImportsAndExports.cpp +++ b/src/passes/MinifyImportsAndExports.cpp @@ -91,8 +91,8 @@ private: } module->updateMaps(); // Emit the mapping. - for (auto& pair : newToOld) { - std::cout << pair.second.str << " => " << pair.first.str << '\n'; + for (auto& [new_, old] : newToOld) { + std::cout << old.str << " => " << new_.str << '\n'; } if (minifyModules) { @@ -111,8 +111,8 @@ private: ModuleUtils::iterImports(*module, [&](Importable* curr) { curr->module = SINGLETON_MODULE_NAME; #ifndef NDEBUG - assert(seenImports.count(curr->base) == 0); - seenImports.insert(curr->base); + auto res = seenImports.emplace(curr->base); + assert(res.second); #endif }); } diff --git a/src/passes/OnceReduction.cpp b/src/passes/OnceReduction.cpp index 83ee7378b..fd38aeafe 100644 --- a/src/passes/OnceReduction.cpp +++ b/src/passes/OnceReduction.cpp @@ -130,9 +130,7 @@ struct Scanner : public WalkerPass<PostWalker<Scanner>> { } } - for (auto& kv : readGlobals) { - auto global = kv.first; - auto count = kv.second; + for (auto& [global, count] : readGlobals) { if (count > 0) { // This global has reads we cannot reason about, so do not optimize it. optInfo.onceGlobals.at(global) = false; @@ -287,7 +285,8 @@ struct Optimizer // instruction, optimize. auto optimizeOnce = [&](Name globalName) { assert(optInfo.onceGlobals.at(globalName)); - if (onceGlobalsWritten.count(globalName)) { + auto res = onceGlobalsWritten.emplace(globalName); + if (!res.second) { // This global has already been written, so this expr is not needed, // regardless of whether it is a global.set or a call. // @@ -297,7 +296,6 @@ struct Optimizer } else { // From here on, this global is set, hopefully allowing us to // optimize away others. - onceGlobalsWritten.insert(globalName); } }; @@ -379,8 +377,7 @@ struct OnceReduction : public Pass { // Combine the information. We found which globals appear to be "once", but // other information may have proven they are not so, in fact. Specifically, // for a function to be "once" we need its global to also be such. - for (auto& kv : optInfo.onceFuncs) { - Name& onceGlobal = kv.second; + for (auto& [_, onceGlobal] : optInfo.onceFuncs) { if (onceGlobal.is() && !optInfo.onceGlobals[onceGlobal]) { onceGlobal = Name(); } @@ -428,8 +425,7 @@ struct OnceReduction : public Pass { // Count how many once globals are set, and see if we have any more work // to do. Index currOnceGlobalsSet = 0; - for (auto& kv : optInfo.onceGlobalsSetInFuncs) { - auto& globals = kv.second; + for (auto& [_, globals] : optInfo.onceGlobalsSetInFuncs) { currOnceGlobalsSet += globals.size(); } assert(currOnceGlobalsSet >= lastOnceGlobalsSet); diff --git a/src/passes/OptimizeAddedConstants.cpp b/src/passes/OptimizeAddedConstants.cpp index 625a1bdcd..0af23c1cc 100644 --- a/src/passes/OptimizeAddedConstants.cpp +++ b/src/passes/OptimizeAddedConstants.cpp @@ -329,8 +329,7 @@ private: // but if x has other uses, then avoid doing so - we'll be doing that add // anyhow, so the load/store offset trick won't actually help. Parents parents(getFunction()->body); - for (auto& pair : localGraph->locations) { - auto* location = pair.first; + for (auto& [location, _] : localGraph->locations) { if (auto* set = location->dynCast<LocalSet>()) { if (auto* add = set->value->dynCast<Binary>()) { if (add->op == AddInt32) { diff --git a/src/passes/PickLoadSigns.cpp b/src/passes/PickLoadSigns.cpp index 3541b1055..f55013ff3 100644 --- a/src/passes/PickLoadSigns.cpp +++ b/src/passes/PickLoadSigns.cpp @@ -93,9 +93,7 @@ struct PickLoadSigns : public WalkerPass<ExpressionStackWalker<PickLoadSigns>> { void optimize() { // optimize based on the info we saw - for (auto& pair : loads) { - auto* load = pair.first; - auto index = pair.second; + for (auto& [load, index] : loads) { auto& usage = usages[index]; // if we can't optimize, give up if (usage.totalUsages == 0 || // no usages, so no idea diff --git a/src/passes/Precompute.cpp b/src/passes/Precompute.cpp index 591245ab5..621c2f886 100644 --- a/src/passes/Precompute.cpp +++ b/src/passes/Precompute.cpp @@ -381,8 +381,7 @@ private: // prepare the work list. we add things here that might change to a constant // initially, that means everything UniqueDeferredQueue<Expression*> work; - for (auto& pair : localGraph.locations) { - auto* curr = pair.first; + for (auto& [curr, _] : localGraph.locations) { work.push(curr); } // the constant value, or none if not a constant diff --git a/src/passes/PrintCallGraph.cpp b/src/passes/PrintCallGraph.cpp index e4576b84b..79938e650 100644 --- a/src/passes/PrintCallGraph.cpp +++ b/src/passes/PrintCallGraph.cpp @@ -86,10 +86,9 @@ struct PrintCallGraph : public Pass { } void visitCall(Call* curr) { auto* target = module->getFunction(curr->target); - if (visitedTargets.count(target->name) > 0) { + if (!visitedTargets.emplace(target->name).second) { return; } - visitedTargets.insert(target->name); std::cout << " \"" << currFunction->name << "\" -> \"" << target->name << "\"; // call\n"; } diff --git a/src/passes/ReReloop.cpp b/src/passes/ReReloop.cpp index 0559343d4..4499bb07b 100644 --- a/src/passes/ReReloop.cpp +++ b/src/passes/ReReloop.cpp @@ -228,9 +228,8 @@ struct ReReloop final : public Pass { for (Index i = 0; i < num; i++) { targetValues[targets[i]].insert(i); } - for (auto& iter : targetValues) { - parent.addSwitchBranch( - before, parent.getBreakTarget(iter.first), iter.second); + for (auto& [name, indices] : targetValues) { + parent.addSwitchBranch(before, parent.getBreakTarget(name), indices); } // the default may be among the targets, in which case, we can't add it // simply as it would be a duplicate, so create a temp block @@ -328,9 +327,7 @@ struct ReReloop final : public Pass { std::cout << "rerelooping " << function->name << '\n'; for (auto* block : relooper->Blocks) { std::cout << block << " block:\n" << block->Code << '\n'; - for (auto& pair : block->BranchesOut) { - auto* target = pair.first; - auto* branch = pair.second; + for (auto& [target, branch] : block->BranchesOut) { std::cout << "branch to " << target << "\n"; if (branch->Condition) { std::cout << " with condition\n" << branch->Condition << '\n'; diff --git a/src/passes/RemoveNonJSOps.cpp b/src/passes/RemoveNonJSOps.cpp index 5bbb9f701..1c112e760 100644 --- a/src/passes/RemoveNonJSOps.cpp +++ b/src/passes/RemoveNonJSOps.cpp @@ -125,9 +125,7 @@ struct RemoveNonJSOpsPass : public WalkerPass<PostWalker<RemoveNonJSOpsPass>> { MemoryUtils::ensureExists(module->memory); // Add missing globals - for (auto& pair : neededImportedGlobals) { - auto name = pair.first; - auto type = pair.second; + for (auto& [name, type] : neededImportedGlobals) { if (!getModule()->getGlobalOrNull(name)) { auto global = make_unique<Global>(); global->name = name; @@ -141,10 +139,9 @@ struct RemoveNonJSOpsPass : public WalkerPass<PostWalker<RemoveNonJSOpsPass>> { } void addNeededFunctions(Module& m, Name name, std::set<Name>& needed) { - if (needed.count(name)) { + if (!needed.emplace(name).second) { return; } - needed.insert(name); auto function = m.getFunction(name); FindAll<Call> calls(function->body); @@ -334,7 +331,7 @@ struct RemoveNonJSOpsPass : public WalkerPass<PostWalker<RemoveNonJSOpsPass>> { } void visitGlobalGet(GlobalGet* curr) { - neededImportedGlobals.insert(std::make_pair(curr->name, curr->type)); + neededImportedGlobals.insert({curr->name, curr->type}); } }; diff --git a/src/passes/RemoveUnusedModuleElements.cpp b/src/passes/RemoveUnusedModuleElements.cpp index 436e01885..8f8fc24a3 100644 --- a/src/passes/RemoveUnusedModuleElements.cpp +++ b/src/passes/RemoveUnusedModuleElements.cpp @@ -60,23 +60,23 @@ struct ReachabilityAnalyzer : public PostWalker<ReachabilityAnalyzer> { // main loop while (queue.size()) { - auto& curr = queue.back(); + auto curr = queue.back(); queue.pop_back(); - if (reachable.count(curr) == 0) { - reachable.insert(curr); - if (curr.first == ModuleElementKind::Function) { + if (reachable.emplace(curr).second) { + auto& [kind, value] = curr; + if (kind == ModuleElementKind::Function) { // if not an import, walk it - auto* func = module->getFunction(curr.second); + auto* func = module->getFunction(value); if (!func->imported()) { walk(func->body); } - } else if (curr.first == ModuleElementKind::Global) { + } else if (kind == ModuleElementKind::Global) { // if not imported, it has an init expression we need to walk - auto* global = module->getGlobal(curr.second); + auto* global = module->getGlobal(value); if (!global->imported()) { walk(global->init); } - } else if (curr.first == ModuleElementKind::Table) { + } else if (kind == ModuleElementKind::Table) { ModuleUtils::iterTableSegments( *module, curr.second, [&](ElementSegment* segment) { walk(segment->offset); diff --git a/src/passes/SimplifyLocals.cpp b/src/passes/SimplifyLocals.cpp index 7c768d4d4..8ed822774 100644 --- a/src/passes/SimplifyLocals.cpp +++ b/src/passes/SimplifyLocals.cpp @@ -280,9 +280,9 @@ struct SimplifyLocals void checkInvalidations(EffectAnalyzer& effects) { // TODO: this is O(bad) std::vector<Index> invalidated; - for (auto& sinkable : sinkables) { - if (effects.invalidates(sinkable.second.effects)) { - invalidated.push_back(sinkable.first); + for (auto& [index, info] : sinkables) { + if (effects.invalidates(info.effects)) { + invalidated.push_back(index); } } for (auto index : invalidated) { @@ -303,9 +303,9 @@ struct SimplifyLocals // 'try', we drop all sinkables that may throw. if (curr->is<Try>()) { std::vector<Index> invalidated; - for (auto& sinkable : self->sinkables) { - if (sinkable.second.effects.throws) { - invalidated.push_back(sinkable.first); + for (auto& [index, info] : self->sinkables) { + if (info.effects.throws) { + invalidated.push_back(index); } } for (auto index : invalidated) { @@ -407,9 +407,9 @@ struct SimplifyLocals if (set && self->canSink(set)) { Index index = set->index; assert(self->sinkables.count(index) == 0); - self->sinkables.emplace(std::make_pair( + self->sinkables.emplace(std::pair{ index, - SinkableInfo(currp, self->getPassOptions(), *self->getModule()))); + SinkableInfo(currp, self->getPassOptions(), *self->getModule())}); } if (!allowNesting) { @@ -493,8 +493,7 @@ struct SimplifyLocals // look for a local.set that is present in them all bool found = false; Index sharedIndex = -1; - for (auto& sinkable : sinkables) { - Index index = sinkable.first; + for (auto& [index, _] : sinkables) { bool inAll = true; for (size_t j = 0; j < breaks.size(); j++) { if (breaks[j].sinkables.count(index) == 0) { @@ -648,8 +647,7 @@ struct SimplifyLocals } } else { // Look for a shared index. - for (auto& sinkable : ifTrue) { - Index index = sinkable.first; + for (auto& [index, _] : ifTrue) { if (ifFalse.count(index) > 0) { goodIndex = index; found = true; diff --git a/src/passes/Souperify.cpp b/src/passes/Souperify.cpp index 90fd64777..913a58e81 100644 --- a/src/passes/Souperify.cpp +++ b/src/passes/Souperify.cpp @@ -86,10 +86,9 @@ struct UseFinder { LocalGraph& localGraph, std::vector<Expression*>& ret) { // If already handled, nothing to do here. - if (seenSets.count(set)) { + if (!seenSets.emplace(set).second) { return; } - seenSets.insert(set); // Find all the uses of that set. auto& gets = localGraph.setInfluences[set]; if (debug() >= 2) { diff --git a/src/passes/pass.cpp b/src/passes/pass.cpp index 198cb9ab5..99288cc6e 100644 --- a/src/passes/pass.cpp +++ b/src/passes/pass.cpp @@ -66,8 +66,8 @@ std::unique_ptr<Pass> PassRegistry::createPass(std::string name) { std::vector<std::string> PassRegistry::getRegisteredNames() { std::vector<std::string> ret; - for (auto pair : passInfos) { - ret.push_back(pair.first); + for (auto& [name, _] : passInfos) { + ret.push_back(name); } return ret; } diff --git a/src/support/bits.cpp b/src/support/bits.cpp index 749e6fb54..aa24edadb 100644 --- a/src/support/bits.cpp +++ b/src/support/bits.cpp @@ -22,9 +22,7 @@ #include <intrin.h> #endif -namespace wasm { - -namespace Bits { +namespace wasm::Bits { int popCount(uint8_t v) { // Small table lookup. @@ -198,6 +196,4 @@ uint32_t log2(uint32_t v) { uint32_t pow2(uint32_t v) { return v < 32 ? 1 << v : 0; } -} // namespace Bits - -} // namespace wasm +} // namespace wasm::Bits diff --git a/src/support/bits.h b/src/support/bits.h index a34bc5067..9c68a7a15 100644 --- a/src/support/bits.h +++ b/src/support/bits.h @@ -31,9 +31,7 @@ * avoiding implementations with large lookup tables. */ -namespace wasm { - -namespace Bits { +namespace wasm::Bits { int popCount(uint8_t); int popCount(uint16_t); @@ -96,8 +94,6 @@ template<typename T, typename U> inline static T rotateRight(T val, U count) { uint32_t log2(uint32_t v); uint32_t pow2(uint32_t v); -} // namespace Bits - -} // namespace wasm +} // namespace wasm::Bits #endif // wasm_support_bits_h diff --git a/src/support/colors.h b/src/support/colors.h index f2c446025..ec6147842 100644 --- a/src/support/colors.h +++ b/src/support/colors.h @@ -20,6 +20,7 @@ #include <iosfwd> namespace Colors { + void setEnabled(bool enabled); bool isEnabled(); @@ -58,6 +59,7 @@ inline void green(std::ostream& stream) {} inline void blue(std::ostream& stream) {} inline void bold(std::ostream& stream) {} #endif + } // namespace Colors #endif // wasm_support_color_h diff --git a/src/support/path.cpp b/src/support/path.cpp index 1cf5c736d..d3f5075c2 100644 --- a/src/support/path.cpp +++ b/src/support/path.cpp @@ -20,9 +20,7 @@ #include "support/path.h" -namespace wasm { - -namespace Path { +namespace wasm::Path { char getPathSeparator() { // TODO: use c++17's path separator @@ -93,6 +91,4 @@ std::string getBinaryenBinaryTool(const std::string& name) { return getBinaryenBinDir() + name; } -} // namespace Path - -} // namespace wasm +} // namespace wasm::Path diff --git a/src/support/path.h b/src/support/path.h index e9f675142..78e85ca5c 100644 --- a/src/support/path.h +++ b/src/support/path.h @@ -24,9 +24,7 @@ #include <cstdlib> #include <string> -namespace wasm { - -namespace Path { +namespace wasm::Path { char getPathSeparator(); std::string getDirName(const std::string& path); @@ -44,8 +42,6 @@ void setBinaryenBinDir(const std::string& dir); // Gets the path to a binaryen binary tool, like wasm-opt. std::string getBinaryenBinaryTool(const std::string& name); -} // namespace Path - -} // namespace wasm +} // namespace wasm::Path #endif // wasm_support_path_h diff --git a/src/support/space.h b/src/support/space.h index 9d940c872..a132d986b 100644 --- a/src/support/space.h +++ b/src/support/space.h @@ -48,9 +48,7 @@ struct DisjointSpans { // Insert the new span. We can then find its predecessor and successor. // They are disjoint by assumption, so the question is then does the new // span overlap with them, or not. - decltype(spans)::iterator iter; - bool inserted; - std::tie(iter, inserted) = spans.insert(span); + auto [iter, inserted] = spans.insert(span); if (!inserted) { // This exact span was already there, so there is definite overlap. return true; diff --git a/src/support/string.h b/src/support/string.h index 120835b80..a73121f6b 100644 --- a/src/support/string.h +++ b/src/support/string.h @@ -22,13 +22,12 @@ #define wasm_support_string_h #include "support/utilities.h" +#include <algorithm> #include <cctype> #include <string> #include <vector> -namespace wasm { - -namespace String { +namespace wasm::String { // Creates a vector of the split parts of a string, by a delimiter. class Split : public std::vector<std::string> { @@ -120,8 +119,6 @@ inline bool isNumber(const std::string& str) { return !str.empty() && std::all_of(str.begin(), str.end(), ::isdigit); } -} // namespace String - -} // namespace wasm +} // namespace wasm::String #endif // wasm_support_string_h diff --git a/src/tools/execution-results.h b/src/tools/execution-results.h index 8fc4c2eed..b689ffc66 100644 --- a/src/tools/execution-results.h +++ b/src/tools/execution-results.h @@ -185,8 +185,7 @@ struct ExecutionResults { std::cout << "ignoring comparison of ExecutionResults!\n"; return true; } - for (auto& iter : other.results) { - auto name = iter.first; + for (auto& [name, _] : other.results) { if (results.find(name) == results.end()) { std::cout << "[fuzz-exec] missing " << name << '\n'; return false; diff --git a/src/tools/wasm-metadce.cpp b/src/tools/wasm-metadce.cpp index 00fa87ce2..3a468e071 100644 --- a/src/tools/wasm-metadce.cpp +++ b/src/tools/wasm-metadce.cpp @@ -334,8 +334,7 @@ public: queue.pop_back(); auto& node = nodes[name]; for (auto target : node.reaches) { - if (reached.find(target) == reached.end()) { - reached.insert(target); + if (reached.emplace(target).second) { queue.push_back(target); } } @@ -368,8 +367,7 @@ public: // removed, including on the outside void printAllUnused() { std::set<std::string> unused; - for (auto& pair : nodes) { - auto name = pair.first; + for (auto& [name, _] : nodes) { if (reached.find(name) == reached.end()) { unused.insert(name.str); } @@ -386,14 +384,10 @@ public: std::cout << "root: " << root << '\n'; } std::map<Name, ImportId> importMap; - for (auto& pair : importIdToDCENode) { - auto& id = pair.first; - auto dceName = pair.second; + for (auto& [id, dceName] : importIdToDCENode) { importMap[dceName] = id; } - for (auto& pair : nodes) { - auto name = pair.first; - auto& node = pair.second; + for (auto& [name, node] : nodes) { std::cout << "node: " << name << '\n'; if (importMap.find(name) != importMap.end()) { std::cout << " is import " << importMap[name] << '\n'; diff --git a/src/tools/wasm-split/wasm-split.cpp b/src/tools/wasm-split/wasm-split.cpp index 2be368994..2732502ad 100644 --- a/src/tools/wasm-split/wasm-split.cpp +++ b/src/tools/wasm-split/wasm-split.cpp @@ -161,8 +161,8 @@ void writePlaceholderMap(const std::map<size_t, Name> placeholderMap, std::string filename) { Output output(filename, Flags::Text); auto& o = output.getStream(); - for (auto pair : placeholderMap) { - o << pair.first << ':' << pair.second << '\n'; + for (auto& [index, func] : placeholderMap) { + o << index << ':' << func << '\n'; } } diff --git a/src/wasm-debug.h b/src/wasm-debug.h index d5ab337d4..c76afb2a1 100644 --- a/src/wasm-debug.h +++ b/src/wasm-debug.h @@ -26,9 +26,7 @@ #include "pass.h" #include "wasm.h" -namespace wasm { - -namespace Debug { +namespace wasm::Debug { bool isDWARFSection(Name name); @@ -44,9 +42,7 @@ bool shouldPreserveDWARF(PassOptions& options, Module& wasm); // Update the DWARF sections. void writeDWARFSections(Module& wasm, const BinaryLocations& newLocations); -} // namespace Debug - -} // namespace wasm +} // namespace wasm::Debug #undef DEBUG_TYPE diff --git a/src/wasm/wasm-binary.cpp b/src/wasm/wasm-binary.cpp index 74036d748..11346056a 100644 --- a/src/wasm/wasm-binary.cpp +++ b/src/wasm/wasm-binary.cpp @@ -165,17 +165,17 @@ void WasmBinaryWriter::finishSection(int32_t start) { // we are at the right absolute address. // We are relative to the section start. auto totalAdjustment = adjustmentForLEBShrinking + body; - for (auto& pair : binaryLocations.expressions) { - pair.second.start -= totalAdjustment; - pair.second.end -= totalAdjustment; + for (auto& [_, locations] : binaryLocations.expressions) { + locations.start -= totalAdjustment; + locations.end -= totalAdjustment; } - for (auto& pair : binaryLocations.functions) { - pair.second.start -= totalAdjustment; - pair.second.declarations -= totalAdjustment; - pair.second.end -= totalAdjustment; + for (auto& [_, locations] : binaryLocations.functions) { + locations.start -= totalAdjustment; + locations.declarations -= totalAdjustment; + locations.end -= totalAdjustment; } - for (auto& pair : binaryLocations.delimiters) { - for (auto& item : pair.second) { + for (auto& [_, locations] : binaryLocations.delimiters) { + for (auto& item : locations) { item -= totalAdjustment; } } @@ -734,9 +734,7 @@ void WasmBinaryWriter::writeNames() { startSubsection(BinaryConsts::UserSections::Subsection::NameLocal); o << U32LEB(functionsWithLocalNames.size()); Index emitted = 0; - for (auto& kv : functionsWithLocalNames) { - auto index = kv.first; - auto* func = kv.second; + for (auto& [index, func] : functionsWithLocalNames) { // Pairs of (local index in IR, name). std::vector<std::pair<Index, Name>> localsWithNames; auto numLocals = func->getNumLocals(); @@ -748,9 +746,7 @@ void WasmBinaryWriter::writeNames() { assert(localsWithNames.size()); o << U32LEB(index); o << U32LEB(localsWithNames.size()); - for (auto& indexedLocal : localsWithNames) { - auto indexInFunc = indexedLocal.first; - auto name = indexedLocal.second; + for (auto& [indexInFunc, name] : localsWithNames) { // TODO: handle multivalue auto indexInBinary = funcMappedLocals.at(func->name)[{indexInFunc, 0}]; @@ -767,8 +763,7 @@ void WasmBinaryWriter::writeNames() { // type names { std::vector<HeapType> namedTypes; - for (auto& kv : typeIndices) { - auto type = kv.first; + for (auto& [type, _] : typeIndices) { if (wasm->typeNames.count(type) && wasm->typeNames[type].name.is()) { namedTypes.push_back(type); } @@ -804,9 +799,9 @@ void WasmBinaryWriter::writeNames() { startSubsection(BinaryConsts::UserSections::Subsection::NameTable); o << U32LEB(tablesWithNames.size()); - for (auto& indexedTable : tablesWithNames) { - o << U32LEB(indexedTable.first); - writeEscapedName(indexedTable.second->name.str); + for (auto& [index, table] : tablesWithNames) { + o << U32LEB(index); + writeEscapedName(table->name.str); } finishSubsection(substart); @@ -839,9 +834,9 @@ void WasmBinaryWriter::writeNames() { auto substart = startSubsection(BinaryConsts::UserSections::Subsection::NameGlobal); o << U32LEB(globalsWithNames.size()); - for (auto& indexedGlobal : globalsWithNames) { - o << U32LEB(indexedGlobal.first); - writeEscapedName(indexedGlobal.second->name.str); + for (auto& [index, global] : globalsWithNames) { + o << U32LEB(index); + writeEscapedName(global->name.str); } finishSubsection(substart); } @@ -864,9 +859,9 @@ void WasmBinaryWriter::writeNames() { startSubsection(BinaryConsts::UserSections::Subsection::NameElem); o << U32LEB(elemsWithNames.size()); - for (auto& indexedElem : elemsWithNames) { - o << U32LEB(indexedElem.first); - writeEscapedName(indexedElem.second->name.str); + for (auto& [index, elem] : elemsWithNames) { + o << U32LEB(index); + writeEscapedName(elem->name.str); } finishSubsection(substart); @@ -919,9 +914,9 @@ void WasmBinaryWriter::writeNames() { std::unordered_map<Index, Name>& fieldNames = wasm->typeNames.at(type).fieldNames; o << U32LEB(fieldNames.size()); - for (auto& kv : fieldNames) { - o << U32LEB(kv.first); - writeEscapedName(kv.second.str); + for (auto& [index, name] : fieldNames) { + o << U32LEB(index); + writeEscapedName(name.str); } } finishSubsection(substart); @@ -987,18 +982,16 @@ void WasmBinaryWriter::writeSourceMapEpilog() { // write source map entries size_t lastOffset = 0; Function::DebugLocation lastLoc = {0, /* lineNumber = */ 1, 0}; - for (const auto& offsetAndlocPair : sourceMapLocations) { + for (const auto& [offset, loc] : sourceMapLocations) { if (lastOffset > 0) { *sourceMap << ","; } - size_t offset = offsetAndlocPair.first; - const Function::DebugLocation& loc = *offsetAndlocPair.second; writeBase64VLQ(*sourceMap, int32_t(offset - lastOffset)); - writeBase64VLQ(*sourceMap, int32_t(loc.fileIndex - lastLoc.fileIndex)); - writeBase64VLQ(*sourceMap, int32_t(loc.lineNumber - lastLoc.lineNumber)); + writeBase64VLQ(*sourceMap, int32_t(loc->fileIndex - lastLoc.fileIndex)); + writeBase64VLQ(*sourceMap, int32_t(loc->lineNumber - lastLoc.lineNumber)); writeBase64VLQ(*sourceMap, - int32_t(loc.columnNumber - lastLoc.columnNumber)); - lastLoc = loc; + int32_t(loc->columnNumber - lastLoc.columnNumber)); + lastLoc = *loc; lastOffset = offset; } *sourceMap << "\"}"; @@ -2308,10 +2301,9 @@ void WasmBinaryBuilder::readExports() { BYN_TRACE("read one\n"); auto curr = new Export; curr->name = getInlineString(); - if (names.count(curr->name) > 0) { + if (!names.emplace(curr->name).second) { throwError("duplicate export name"); } - names.insert(curr->name); curr->kind = (ExternalKind)getU32LEB(); auto index = getU32LEB(); exportIndices[curr] = index; @@ -2771,9 +2763,7 @@ void WasmBinaryBuilder::processNames() { wasm.addExport(curr); } - for (auto& iter : functionRefs) { - size_t index = iter.first; - auto& refs = iter.second; + for (auto& [index, refs] : functionRefs) { for (auto* ref : refs) { if (auto* call = ref->dynCast<Call>()) { call->target = getFunctionName(index); @@ -2785,9 +2775,7 @@ void WasmBinaryBuilder::processNames() { } } - for (auto& iter : tableRefs) { - size_t index = iter.first; - auto& refs = iter.second; + for (auto& [index, refs] : tableRefs) { for (auto* ref : refs) { if (auto* callIndirect = ref->dynCast<CallIndirect>()) { callIndirect->table = getTableName(index); @@ -2805,9 +2793,7 @@ void WasmBinaryBuilder::processNames() { } } - for (auto& iter : globalRefs) { - size_t index = iter.first; - auto& refs = iter.second; + for (auto& [index, refs] : globalRefs) { for (auto* ref : refs) { if (auto* get = ref->dynCast<GlobalGet>()) { get->name = getGlobalName(index); diff --git a/src/wasm/wasm-debug.cpp b/src/wasm/wasm-debug.cpp index 60e97a27e..23c2dc938 100644 --- a/src/wasm/wasm-debug.cpp +++ b/src/wasm/wasm-debug.cpp @@ -29,9 +29,7 @@ std::error_code dwarf2yaml(llvm::DWARFContext& DCtx, llvm::DWARFYAML::Data& Y); #include "wasm-debug.h" #include "wasm.h" -namespace wasm { - -namespace Debug { +namespace wasm::Debug { bool isDWARFSection(Name name) { return name.startsWith(".debug_"); } @@ -372,11 +370,11 @@ struct AddrExprMap { // Construct the map from the binaryLocations loaded from the wasm. AddrExprMap(const Module& wasm) { for (auto& func : wasm.functions) { - for (auto pair : func->expressionLocations) { - add(pair.first, pair.second); + for (auto& [expr, span] : func->expressionLocations) { + add(expr, span); } - for (auto pair : func->delimiterLocations) { - add(pair.first, pair.second); + for (auto& [expr, delim] : func->delimiterLocations) { + add(expr, delim); } } } @@ -1105,6 +1103,4 @@ bool shouldPreserveDWARF(PassOptions& options, Module& wasm) { return false; } #endif // BUILD_LLVM_DWARF -} // namespace Debug - -} // namespace wasm +} // namespace wasm::Debug diff --git a/src/wasm/wasm-emscripten.cpp b/src/wasm/wasm-emscripten.cpp index 7e56ef849..262787ac1 100644 --- a/src/wasm/wasm-emscripten.cpp +++ b/src/wasm/wasm-emscripten.cpp @@ -387,9 +387,7 @@ std::string EmscriptenGlueGenerator::generateEmscriptenMetadata() { if (!emJsWalker.codeByName.empty()) { meta << " \"emJsFuncs\": {"; commaFirst = true; - for (auto& pair : emJsWalker.codeByName) { - auto& name = pair.first; - auto& code = pair.second; + for (auto& [name, code] : emJsWalker.codeByName) { meta << nextElement(); meta << '"' << name << "\": \"" << escape(code) << '"'; } diff --git a/src/wasm/wasm-s-parser.cpp b/src/wasm/wasm-s-parser.cpp index d9c35d97c..9a537586e 100644 --- a/src/wasm/wasm-s-parser.cpp +++ b/src/wasm/wasm-s-parser.cpp @@ -908,9 +908,7 @@ void SExpressionWasmBuilder::preParseHeapTypes(Element& module) { types = builder.build(); - for (auto& pair : typeIndices) { - auto name = pair.first; - auto index = pair.second; + for (auto& [name, index] : typeIndices) { auto type = types[index]; // A type may appear in the type section more than once, but we canonicalize // types internally, so there will be a single name chosen for that type. Do diff --git a/src/wasm/wasm-stack.cpp b/src/wasm/wasm-stack.cpp index adb9341b0..616e0370b 100644 --- a/src/wasm/wasm-stack.cpp +++ b/src/wasm/wasm-stack.cpp @@ -2308,8 +2308,8 @@ void BinaryInstWriter::countScratchLocals() { scratchLocals[extract->type] = 0; } } - for (auto t : scratchLocals) { - noteLocalType(t.first); + for (auto& [type, _] : scratchLocals) { + noteLocalType(type); } } diff --git a/src/wasm/wasm-type.cpp b/src/wasm/wasm-type.cpp index 7dc336d87..f04ae5bc0 100644 --- a/src/wasm/wasm-type.cpp +++ b/src/wasm/wasm-type.cpp @@ -2975,9 +2975,7 @@ globallyCanonicalize(std::vector<std::unique_ptr<HeapTypeInfo>>& infos) { canonicalHeapTypes[original] = canonical; } } - for (auto& pair : canonicalHeapTypes) { - HeapType original = pair.first; - HeapType canonical = pair.second; + for (auto& [original, canonical] : canonicalHeapTypes) { for (HeapType* use : locations.heapTypes.at(original)) { *use = canonical; } diff --git a/src/wasm/wasm-validator.cpp b/src/wasm/wasm-validator.cpp index 8cf456409..e7e1d7fd5 100644 --- a/src/wasm/wasm-validator.cpp +++ b/src/wasm/wasm-validator.cpp @@ -493,8 +493,7 @@ void FunctionValidator::noteLabelName(Name name) { if (!name.is()) { return; } - bool inserted; - std::tie(std::ignore, inserted) = labelNames.insert(name); + auto [_, inserted] = labelNames.insert(name); shouldBeTrue( inserted, name, @@ -2870,9 +2869,7 @@ static void validateBinaryenIR(Module& wasm, ValidationInfo& info) { } // check if a node is a duplicate - expressions must not be seen more than // once - bool inserted; - std::tie(std::ignore, inserted) = seen.insert(curr); - if (!inserted) { + if (!seen.insert(curr).second) { std::ostringstream ss; ss << "expression seen more than once in the tree in " << scope << " on " << curr << '\n'; diff --git a/src/wasm2js.h b/src/wasm2js.h index 206f945b4..ba5798285 100644 --- a/src/wasm2js.h +++ b/src/wasm2js.h @@ -1232,9 +1232,7 @@ Ref Wasm2JSBuilder::processFunctionBody(Module* m, // Emit any remaining groups by just emitting branches to their code, // which will appear outside the switch. - for (auto& pair : targetIndexes) { - auto target = pair.first; - auto& indexes = pair.second; + for (auto& [target, indexes] : targetIndexes) { if (emittedTargets.count(target)) { continue; } |