Skip to content

Truly independent web browser

78.8 KB
Raw Blame
/*
 * Copyright (c) 2024, Matthew Olsson <[email protected]>
 * Copyright (c) 2025, Idan Horowitz <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "LibJSGCPluginAction.h"
#include <array>
#include <clang/AST/IgnoreExpr.h>
#include <clang/ASTMatchers/ASTMatchFinder.h>
#include <clang/ASTMatchers/ASTMatchers.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/FrontendPluginRegistry.h>
#include <clang/Lex/MacroArgs.h>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>

template<typename T>
class SimpleCollectMatchesCallback : public clang::ast_matchers::MatchFinder::MatchCallback {
public:
    explicit SimpleCollectMatchesCallback(std::string name)
        : m_name(std::move(name))
    {
    }

    void run(clang::ast_matchers::MatchFinder::MatchResult const& result) override
    {
        if (auto const* node = result.Nodes.getNodeAs<T>(m_name))
            m_matches.push_back(node);
    }

    auto const& matches() const { return m_matches; }

private:
    std::string m_name;
    std::vector<T const*> m_matches;
};

// GC::ForeignCell's subclasses name cells that a foreign implementation, such as the Rust LibJS runtime, lays out,
// creates and visits. C++ code holds and visits them like GC::Cell's subclasses, so the checks of how cells are held
// apply to both kinds, while the checks of how a C++ cell class is written apply only to GC::Cell's subclasses.
enum class CellBaseOfRecord {
    NotACell,
    Cell,
    ForeignCell,
};

static CellBaseOfRecord cell_base_named_by_record(clang::CXXRecordDecl const& record)
{
    auto qualified_name = record.getQualifiedNameAsString();
    if (qualified_name == "GC::Cell")
        return CellBaseOfRecord::Cell;
    if (qualified_name == "GC::ForeignCell")
        return CellBaseOfRecord::ForeignCell;
    return CellBaseOfRecord::NotACell;
}

static CellBaseOfRecord cell_base_of_record(clang::CXXRecordDecl const& record)
{
    if (!record.isCompleteDefinition())
        return CellBaseOfRecord::NotACell;

    auto cell_base = cell_base_named_by_record(record);
    if (cell_base != CellBaseOfRecord::NotACell)
        return cell_base;
    record.forallBases([&](clang::CXXRecordDecl const* base) -> bool {
        cell_base = cell_base_named_by_record(*base);
        return cell_base == CellBaseOfRecord::NotACell;
    });
    return cell_base;
}

static bool record_inherits_from_cell(clang::CXXRecordDecl const& record)
{
    return cell_base_of_record(record) != CellBaseOfRecord::NotACell;
}

// Check if a type has a visit_edges method that takes GC::Cell::Visitor&
static bool type_has_visit_edges_method(clang::CXXRecordDecl const* record)
{
    if (!record || !record->isCompleteDefinition())
        return false;

    for (auto const* method : record->methods()) {
        if (method->getNameAsString() != "visit_edges")
            continue;
        if (method->getNumParams() != 1)
            continue;
        // Check that the parameter is a reference to Visitor (GC::Cell::Visitor)
        auto param_type = method->getParamDecl(0)->getType();
        if (!param_type->isReferenceType())
            continue;
        return true;
    }
    return false;
}

enum class ContainsGCPtrResult {
    No,
    Yes,
    YesRequiresVisitEdges, // Contains GC pointers and the type needs its own visit_edges
};

static std::map<clang::CXXRecordDecl const*, ContainsGCPtrResult> s_contains_gc_ptr_cache;

// Forward declaration
static ContainsGCPtrResult type_contains_gc_ptr(clang::QualType const& type, std::set<clang::CXXRecordDecl const*>& visited);

static ContainsGCPtrResult record_contains_gc_ptr(clang::CXXRecordDecl const* record, std::set<clang::CXXRecordDecl const*>& visited)
{
    if (!record || !record->isCompleteDefinition())
        return ContainsGCPtrResult::No;

    // Avoid infinite recursion
    if (visited.contains(record))
        return ContainsGCPtrResult::No;
    visited.insert(record);

    // Check cache
    auto cache_it = s_contains_gc_ptr_cache.find(record);
    if (cache_it != s_contains_gc_ptr_cache.end())
        return cache_it->second;

    // Cell types are visited directly via GC::Ptr/GC::Ref, not through substruct visiting
    if (record_inherits_from_cell(*record)) {
        s_contains_gc_ptr_cache[record] = ContainsGCPtrResult::No;
        return ContainsGCPtrResult::No;
    }

    // Skip GC infrastructure types that handle their own visiting
    auto qualified_name = record->getQualifiedNameAsString();
    static std::set<std::string> gc_infrastructure_types {
        "GC::Root",
        "GC::RootImpl",
        "GC::HeapBlock",
        "GC::CellAllocator",
        "GC::TypeIsolatingCellAllocator",
        "GC::RootVector",
        "GC::RootHashTable",
        "GC::RootHashTableBase",
        "GC::Heap",
        "GC::MarkedVector",
        "GC::RootHashMap",
        "GC::RootHashMapBase",
    };
    if (gc_infrastructure_types.contains(qualified_name)) {
        s_contains_gc_ptr_cache[record] = ContainsGCPtrResult::No;
        return ContainsGCPtrResult::No;
    }

    // Skip AK types - they're library types that don't need visit_edges
    if (qualified_name.starts_with("AK::") || qualified_name.starts_with("Optional<")) {
        s_contains_gc_ptr_cache[record] = ContainsGCPtrResult::No;
        return ContainsGCPtrResult::No;
    }

    ContainsGCPtrResult result = ContainsGCPtrResult::No;

    for (auto const* field : record->fields()) {
        auto field_result = type_contains_gc_ptr(field->getType(), visited);
        if (field_result == ContainsGCPtrResult::YesRequiresVisitEdges) {
            result = ContainsGCPtrResult::YesRequiresVisitEdges;
            break;
        }
        if (field_result == ContainsGCPtrResult::Yes) {
            result = ContainsGCPtrResult::YesRequiresVisitEdges;
        }
    }

    s_contains_gc_ptr_cache[record] = result;
    return result;
}

static ContainsGCPtrResult type_contains_gc_ptr(clang::QualType const& type, std::set<clang::CXXRecordDecl const*>& visited)
{
    // Check for JS::Value directly
    if (auto const* record = type->getAsCXXRecordDecl()) {
        if (record->getQualifiedNameAsString() == "JS::Value")
            return ContainsGCPtrResult::Yes;
    }

    // Check for raw pointers to Cell types (these should use GC::Ptr instead)
    if (auto const* pointer_type = type->getAs<clang::PointerType>()) {
        if (auto const* pointee = pointer_type->getPointeeCXXRecordDecl()) {
            if (pointee->hasDefinition() && record_inherits_from_cell(*pointee))
                return ContainsGCPtrResult::Yes;
        }
    }

    // Check for raw references to Cell types (these should use GC::Ref instead)
    if (auto const* reference_type = type->getAs<clang::ReferenceType>()) {
        if (auto const* pointee = reference_type->getPointeeCXXRecordDecl()) {
            if (pointee->hasDefinition() && record_inherits_from_cell(*pointee))
                return ContainsGCPtrResult::Yes;
        }
    }

    // Check for template specializations (GC::Ptr, GC::Ref, Vector, HashMap, etc.)
    if (auto const* specialization = type->getAs<clang::TemplateSpecializationType>()) {
        auto template_name = specialization->getTemplateName().getAsTemplateDecl()->getQualifiedNameAsString();

        // Direct GC pointer types
        if (template_name == "GC::Ptr" || template_name == "GC::Ref")
            return ContainsGCPtrResult::Yes;

        // Raw pointers don't need visiting
        if (template_name == "GC::RawPtr" || template_name == "GC::RawRef")
            return ContainsGCPtrResult::No;

        // Root types handle their own visiting
        if (template_name == "GC::Root" || template_name == "GC::RootVector" || template_name == "GC::RootHashMap" || template_name == "GC::RootHashTable")
            return ContainsGCPtrResult::No;

        // Check template arguments recursively for containers
        for (auto const& arg : specialization->template_arguments()) {
            if (arg.getKind() == clang::TemplateArgument::Type) {
                auto arg_result = type_contains_gc_ptr(arg.getAsType(), visited);
                if (arg_result != ContainsGCPtrResult::No)
                    return arg_result;
            }
        }
    }

    // Check for record types (structs/classes) that might contain GC pointers
    if (auto const* record = type->getAsCXXRecordDecl()) {
        return record_contains_gc_ptr(record, visited);
    }

    return ContainsGCPtrResult::No;
}

static ContainsGCPtrResult type_contains_gc_ptr(clang::QualType const& type)
{
    std::set<clang::CXXRecordDecl const*> visited;
    return type_contains_gc_ptr(type, visited);
}

static std::vector<clang::QualType> get_all_qualified_types(clang::QualType const& type)
{
    std::vector<clang::QualType> qualified_types;

    if (auto const* template_specialization = type->getAs<clang::TemplateSpecializationType>()) {
        auto specialization_name = template_specialization->getTemplateName().getAsTemplateDecl()->getQualifiedNameAsString();
        // Do not unwrap GCPtr/NonnullGCPtr/RootVector
        static std::unordered_set<std::string> gc_relevant_type_names {
            "GC::Ptr",
            "GC::Ref",
            "GC::RawPtr",
            "GC::RawRef",
            "GC::RootVector",
            "GC::RootHashMap",
            "GC::RootHashTable",
            "GC::Root",
        };

        if (gc_relevant_type_names.contains(specialization_name)) {
            qualified_types.push_back(type);
        } else {
            auto const template_arguments = template_specialization->template_arguments();
            for (size_t i = 0; i < template_arguments.size(); i++) {
                auto const& template_arg = template_arguments[i];
                if (template_arg.getKind() == clang::TemplateArgument::Type) {
                    auto template_qualified_types = get_all_qualified_types(template_arg.getAsType());
                    std::move(template_qualified_types.begin(), template_qualified_types.end(), std::back_inserter(qualified_types));
                }
            }
        }
    } else {
        qualified_types.push_back(type);
    }

    return qualified_types;
}
enum class OuterType {
    GCPtr,
    RawPtr,
    Root,
    Ptr,
    Ref,
    Value,
};

struct QualTypeGCInfo {
    std::optional<OuterType> outer_type { {} };
    bool base_type_inherits_from_cell { false };
};

static std::optional<QualTypeGCInfo> validate_qualified_type(clang::QualType const& type)
{
    if (auto const* pointer_decl = type->getAs<clang::PointerType>()) {
        if (auto const* pointee = pointer_decl->getPointeeCXXRecordDecl())
            return QualTypeGCInfo { OuterType::Ptr, record_inherits_from_cell(*pointee) };
    } else if (auto const* reference_decl = type->getAs<clang::ReferenceType>()) {
        if (auto const* pointee = reference_decl->getPointeeCXXRecordDecl())
            return QualTypeGCInfo { OuterType::Ref, record_inherits_from_cell(*pointee) };
    } else if (auto const* specialization = type->getAs<clang::TemplateSpecializationType>()) {
        auto template_type_name = specialization->getTemplateName().getAsTemplateDecl()->getQualifiedNameAsString();

        OuterType outer_type;
        if (template_type_name == "GC::Ptr" || template_type_name == "GC::Ref") {
            outer_type = OuterType::GCPtr;
        } else if (template_type_name == "GC::RawPtr" || template_type_name == "GC::RawRef") {
            outer_type = OuterType::RawPtr;
        } else if (template_type_name == "GC::Root") {
            outer_type = OuterType::Root;
        } else {
            return {};
        }

        auto template_args = specialization->template_arguments();
        if (template_args.size() != 1)
            return {}; // Not really valid, but will produce a compilation error anyway

        auto const& type_arg = template_args[0];
        auto const* record_type = type_arg.getAsType()->getAs<clang::RecordType>();
        if (!record_type)
            return {};

        auto const* record_decl = record_type->getAsCXXRecordDecl();
        if (!record_decl->hasDefinition()) {
            // If we don't have a definition (this is a forward declaration), assume that the type inherits from
            // GC::Cell instead of not checking it at all. If it does inherit from GC:Cell, this will make sure it's
            // visited. If it does not, any attempt to visit it will fail compilation on the visit call itself,
            // ensuring it's no longer wrapped in a GC::Ptr.
            return QualTypeGCInfo { outer_type, true };
        }

        return QualTypeGCInfo { outer_type, record_inherits_from_cell(*record_decl) };
    } else if (auto const* record = type->getAsCXXRecordDecl()) {
        if (record->getQualifiedNameAsString() == "JS::Value")
            return QualTypeGCInfo { OuterType::Value, true };
    }

    return {};
}

static std::optional<QualTypeGCInfo> validate_field_qualified_type(clang::FieldDecl const* field_decl)
{
    for (auto const& qualified_type : get_all_qualified_types(field_decl->getType())) {
        if (auto error = validate_qualified_type(qualified_type))
            return error;
    }

    return {};
}

static bool decl_has_annotation(clang::Decl const* decl, std::string name)
{
    for (auto const* attr : decl->attrs()) {
        if (auto const* annotate_attr = llvm::dyn_cast<clang::AnnotateAttr>(attr)) {
            if (annotate_attr->getAnnotation() == name)
                return true;
        }
    }
    return false;
}

bool LibJSGCVisitor::VisitCXXRecordDecl(clang::CXXRecordDecl* record)
{
    using namespace clang::ast_matchers;

    if (!record || !record->isCompleteDefinition() || (!record->isClass() && !record->isStruct()))
        return true;

    // Cell triggers a bunch of warnings for its empty visit_edges implementation, but
    // it doesn't have any members anyways so it's fine to just ignore.
    auto qualified_name = record->getQualifiedNameAsString();
    if (qualified_name == "GC::Cell")
        return true;

    validate_engine_subclass_is_in_libjs(*record);

    remember_polymorphic_subclass(*record);
    remember_claim_of_no_cell_edges(*record);

    auto& diag_engine = m_context.getDiagnostics();
    std::vector<clang::FieldDecl const*> fields_that_need_visiting;
    std::vector<clang::FieldDecl const*> substruct_fields_that_need_visiting;
    auto record_cell_base = cell_base_of_record(*record);
    auto record_is_cell = record_cell_base != CellBaseOfRecord::NotACell;

    for (clang::FieldDecl const* field : record->fields()) {
        // Skip anonymous structs/unions - their members are accessed indirectly
        // and may be handled specially (e.g., tagged unions with type checks)
        if (field->isAnonymousStructOrUnion())
            continue;

        auto const* field_record = m_context.getBaseElementType(field->getType())->getAsCXXRecordDecl();
        auto field_cell_base = field_record ? cell_base_of_record(*field_record) : CellBaseOfRecord::NotACell;
        if (field_cell_base != CellBaseOfRecord::NotACell) {
            auto diag_id = field_cell_base == CellBaseOfRecord::ForeignCell
                ? diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "GC::ForeignCell type %0 is allocated by its foreign implementation, not stored by value")
                : diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "GC::Cell type %0 must be allocated with GC::Heap::allocate(), not stored by value");
            auto builder = diag_engine.Report(field->getLocation(), diag_id);
            builder << field_record->getName();
            continue;
        }

        auto validation_results = validate_field_qualified_type(field);

        if (validation_results) {
            auto [outer_type, base_type_inherits_from_cell] = *validation_results;

            if (outer_type == OuterType::Ptr || outer_type == OuterType::Ref) {
                if (base_type_inherits_from_cell) {
                    auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "%0 to GC::Cell type should be wrapped in %1");
                    auto builder = diag_engine.Report(field->getLocation(), diag_id);
                    if (outer_type == OuterType::Ref) {
                        builder << "reference"
                                << "GC::Ref";
                    } else {
                        builder << "pointer"
                                << "GC::Ptr";
                    }
                }
            } else if (outer_type == OuterType::GCPtr || outer_type == OuterType::RawPtr || outer_type == OuterType::Value) {
                if (!base_type_inherits_from_cell) {
                    auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "Specialization type must inherit from GC::Cell");
                    diag_engine.Report(field->getLocation(), diag_id);
                } else if (outer_type != OuterType::RawPtr) {
                    fields_that_need_visiting.push_back(field);
                }
            } else if (outer_type == OuterType::Root) {
                if (record_is_cell && m_detect_invalid_function_members) {
                    // FIXME: Change this to an Error when all of the use cases get addressed and remove the plugin argument
                    auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Warning, "Types inheriting from GC::Cell should not have %0 fields");
                    auto builder = diag_engine.Report(field->getLocation(), diag_id);
                    builder << "GC::Root";
                }
            }
            // Field is a direct GC type, don't also check for substruct
            continue;
        }

        // Check if this field is a substruct (non-Cell type) containing GC pointers
        auto contains_result = type_contains_gc_ptr(field->getType());
        if (contains_result == ContainsGCPtrResult::YesRequiresVisitEdges) {
            substruct_fields_that_need_visiting.push_back(field);
        }
    }

    // Non-Cell types don't need visit_edges just for existing - they only need it
    // when used as a member of a Cell (checked below for Cell types).
    // However, if they DO have visit_edges, verify it visits all GC members.
    if (!record_is_cell) {
        validate_gc_members_of_polymorphic_record(*record);

        // Check if this non-Cell type has a visit_edges method
        clang::DeclarationName name = &m_context.Idents.get("visit_edges");
        auto const* visit_edges_method = record->lookup(name).find_first<clang::CXXMethodDecl>();
        // A struct that a foreign implementation lays out, such as an execution context of the Rust LibJS runtime, can
        // hand its visit to that implementation, which visits every member.
        if (visit_edges_method && visit_edges_method->getBody() && !decl_has_annotation(visit_edges_method, "ladybird::visits_through_foreign_implementation")) {
            // Verify that all GC pointer fields are visited
            if (!fields_that_need_visiting.empty() || !substruct_fields_that_need_visiting.empty()) {
                MatchFinder field_access_finder;
                SimpleCollectMatchesCallback<clang::MemberExpr> field_access_callback("member-expr");

                auto field_access_matcher = memberExpr(
                    hasAncestor(cxxMethodDecl(hasName("visit_edges"))),
                    hasObjectExpression(hasType(pointsTo(cxxRecordDecl(hasName(record->getName()))))))
                                                .bind("member-expr");

                field_access_finder.addMatcher(field_access_matcher, &field_access_callback);
                field_access_finder.matchAST(visit_edges_method->getASTContext());

                std::unordered_set<std::string> fields_that_are_visited;
                for (auto const* member_expr : field_access_callback.matches())
                    fields_that_are_visited.insert(member_expr->getMemberNameInfo().getAsString());

                auto gc_member_diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error,
                    "GC-allocated member is not visited in %0::visit_edges");

                for (auto const* field : fields_that_need_visiting) {
                    if (!fields_that_are_visited.contains(field->getNameAsString())) {
                        auto builder = diag_engine.Report(field->getBeginLoc(), gc_member_diag_id);
                        builder << record->getName();
                    }
                }

                auto substruct_diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error,
                    "Member %0 contains GC pointers but is not visited in %1::visit_edges");

                for (auto const* field : substruct_fields_that_need_visiting) {
                    if (!fields_that_are_visited.contains(field->getNameAsString())) {
                        auto builder = diag_engine.Report(field->getBeginLoc(), substruct_diag_id);
                        builder << field->getName() << record->getName();
                    }
                }
            }
        }
        return true;
    }

    // The checks below are about how a C++ cell class is written. A foreign cell has no vtable for the GC_CELL macros
    // to override, and its foreign implementation visits its edges and destroys it.
    if (record_cell_base == CellBaseOfRecord::ForeignCell)
        return true;

    // The macros are written in the class template, not in an explicit instantiation of it.
    if (!record->getTemplateInstantiationPattern())
        validate_record_macros(*record);

    // Check that Cell subclasses (and all their base classes) don't have non-trivial destructors.
    // They should override Cell::finalize() instead.
    auto check_no_nontrivial_destructor = [&](clang::CXXRecordDecl const* check_record) {
        if (!check_record || !check_record->isCompleteDefinition())
            return;
        if (check_record->getQualifiedNameAsString() == "GC::Cell")
            return;
        auto const* destructor = check_record->getDestructor();
        if (!destructor || !destructor->isUserProvided())
            return;
        // Only flag destructors whose body we can see, that aren't defaulted,
        // and that have a non-empty body. This way, out-of-line `= default` destructors
        // and empty-body destructors `~Foo() {}` are fine.
        if (!destructor->getBody() || destructor->isDefaulted())
            return;
        if (auto const* body = llvm::dyn_cast<clang::CompoundStmt>(destructor->getBody())) {
            if (body->body_empty())
                return;
        }
        if (decl_has_annotation(destructor, "ladybird::allow_cell_destructor"))
            return;
        auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error,
            "GC::Cell-inheriting class %0 has a non-trivial destructor; override Cell::finalize() instead");
        auto builder = diag_engine.Report(destructor->getBeginLoc(), diag_id);
        builder << check_record->getName();
    };

    check_no_nontrivial_destructor(record);
    record->forallBases([&](clang::CXXRecordDecl const* base) -> bool {
        if (base->getQualifiedNameAsString() == "GC::Cell")
            return false;
        // Only check bases that are themselves part of the Cell hierarchy.
        // Non-Cell mixins (e.g. Weakable) are not our concern here.
        if (!record_inherits_from_cell(*base))
            return true;
        check_no_nontrivial_destructor(base);
        return true;
    });

    clang::DeclarationName name = &m_context.Idents.get("visit_edges");
    auto const* visit_edges_method = record->lookup(name).find_first<clang::CXXMethodDecl>();
    if (!visit_edges_method && !fields_that_need_visiting.empty()) {
        auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "GC::Cell-inheriting class %0 contains a GC-allocated member %1 but has no visit_edges method");
        auto builder = diag_engine.Report(record->getLocation(), diag_id);
        builder << record->getName()
                << fields_that_need_visiting[0];
    }
    if (!visit_edges_method && !substruct_fields_that_need_visiting.empty()) {
        auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "GC::Cell-inheriting class %0 contains a member %1 that has GC pointers but has no visit_edges method");
        auto builder = diag_engine.Report(record->getLocation(), diag_id);
        builder << record->getName()
                << substruct_fields_that_need_visiting[0];
    }
    if (!visit_edges_method || !visit_edges_method->getBody())
        return true;

    // NOTE: The check for calling Base::visit_edges() is now handled by the general
    // must_upcall attribute check in VisitCXXMethodDecl, since Cell::visit_edges()
    // is annotated with MUST_UPCALL.

    // Search for uses of all fields that need visiting. We don't ensure they are _actually_ visited
    // with a call to visitor.visit(...), as that is too complex. Instead, we just assume that if the
    // field is accessed at all, then it is visited.

    if (fields_that_need_visiting.empty() && substruct_fields_that_need_visiting.empty())
        return true;

    MatchFinder field_access_finder;
    SimpleCollectMatchesCallback<clang::MemberExpr> field_access_callback("member-expr");

    auto field_access_matcher = memberExpr(
        hasAncestor(cxxMethodDecl(hasName("visit_edges"))),
        hasObjectExpression(hasType(pointsTo(cxxRecordDecl(hasName(record->getName()))))))
                                    .bind("member-expr");

    field_access_finder.addMatcher(field_access_matcher, &field_access_callback);
    field_access_finder.matchAST(visit_edges_method->getASTContext());

    std::unordered_set<std::string> fields_that_are_visited;
    for (auto const* member_expr : field_access_callback.matches())
        fields_that_are_visited.insert(member_expr->getMemberNameInfo().getAsString());

    auto gc_member_diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "GC-allocated member is not visited in %0::visit_edges");

    for (auto const* field : fields_that_need_visiting) {
        if (!fields_that_are_visited.contains(field->getNameAsString())) {
            auto builder = diag_engine.Report(field->getBeginLoc(), gc_member_diag_id);
            builder << record->getName();
        }
    }

    auto substruct_not_visited_diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error,
        "Member %0 contains GC pointers but is not visited in %1::visit_edges");
    auto substruct_needs_visit_edges_diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error,
        "Member %0 contains GC pointers but its type has no visit_edges method");

    for (auto const* field : substruct_fields_that_need_visiting) {
        if (!fields_that_are_visited.contains(field->getNameAsString())) {
            // Check if the substruct type has a visit_edges method
            auto field_type = field->getType();

            // For smart pointer types (OwnPtr, RefPtr, etc.), check the pointed-to type
            clang::CXXRecordDecl const* type_to_check = nullptr;
            if (auto const* specialization = field_type->getAs<clang::TemplateSpecializationType>()) {
                auto template_name = specialization->getTemplateName().getAsTemplateDecl()->getQualifiedNameAsString();
                static std::set<std::string> smart_pointer_types {
                    "OwnPtr", "NonnullOwnPtr", "RefPtr", "NonnullRefPtr",
                    "ValueComparingRefPtr", "ValueComparingNonnullRefPtr",
                    "AK::OwnPtr", "AK::NonnullOwnPtr", "AK::RefPtr", "AK::NonnullRefPtr",
                    "AK::ValueComparingRefPtr", "AK::ValueComparingNonnullRefPtr"
                };
                if (smart_pointer_types.contains(template_name)) {
                    auto const& args = specialization->template_arguments();
                    if (args.size() >= 1 && args[0].getKind() == clang::TemplateArgument::Type) {
                        type_to_check = args[0].getAsType()->getAsCXXRecordDecl();
                    }
                }
            }
            if (!type_to_check)
                type_to_check = field_type->getAsCXXRecordDecl();

            if (type_to_check && !type_has_visit_edges_method(type_to_check)) {
                auto builder = diag_engine.Report(field->getBeginLoc(), substruct_needs_visit_edges_diag_id);
                builder << field->getName();
            } else {
                auto builder = diag_engine.Report(field->getBeginLoc(), substruct_not_visited_diag_id);
                builder << field->getName() << record->getName();
            }
        }
    }

    return true;
}

// Check if a method (or any method it overrides) has the must_upcall annotation
static bool method_requires_upcall(clang::CXXMethodDecl const* method)
{
    if (!method)
        return false;

    if (decl_has_annotation(method, "must_upcall"))
        return true;

    // Check overridden methods recursively
    for (auto const* overridden : method->overridden_methods()) {
        if (method_requires_upcall(overridden))
            return true;
    }

    return false;
}

// Get the immediate parent class's method that this method overrides
static clang::CXXMethodDecl const* get_immediate_base_method(clang::CXXMethodDecl const* method)
{
    if (!method->isVirtual() || method->overridden_methods().empty())
        return nullptr;

    // The overridden_methods() returns the immediate parent(s) that this method overrides
    // For single inheritance, there's just one
    for (auto const* overridden : method->overridden_methods())
        return overridden;

    return nullptr;
}

bool LibJSGCVisitor::VisitCXXMethodDecl(clang::CXXMethodDecl* method)
{
    if (!method || !method->isVirtual() || !method->doesThisDeclarationHaveABody())
        return true;

    // Skip if this method is not an override
    if (!method->size_overridden_methods())
        return true;

    // Check if any method in the override chain has must_upcall annotation
    if (!method_requires_upcall(method))
        return true;

    auto const* base_method = get_immediate_base_method(method);
    if (!base_method)
        return true;

    auto const* parent_class = base_method->getParent();
    if (!parent_class)
        return true;

    auto method_name = method->getNameAsString();

    // Search for a call to Base::method_name or ParentClass::method_name
    using namespace clang::ast_matchers;

    MatchFinder upcall_finder;
    SimpleCollectMatchesCallback<clang::MemberExpr> upcall_callback("member-call");

    auto upcall_matcher = cxxMethodDecl(
        equalsNode(method),
        hasDescendant(memberExpr(member(hasName(method_name))).bind("member-call")));

    upcall_finder.addMatcher(upcall_matcher, &upcall_callback);
    upcall_finder.matchAST(m_context);

    bool upcall_found = false;

    for (auto const* member_expr : upcall_callback.matches()) {
        // Check if this is a qualified call (e.g., Base::method or ParentClass::method)
        if (!member_expr->hasQualifier())
            continue;

        // Get the record decl that the qualifier refers to
        auto const* qualifier_record = member_expr->getQualifier().getAsRecordDecl();
        if (!qualifier_record)
            continue;

        // Check if the qualifier refers to a base class of the current class
        auto const* current_class = method->getParent();
        if (!current_class)
            continue;

        // The qualifier should be the same as or a base of the parent class
        if (qualifier_record == parent_class || current_class->isDerivedFrom(qualifier_record)) {
            upcall_found = true;
            break;
        }
    }

    if (!upcall_found) {
        auto& diag_engine = m_context.getDiagnostics();
        auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error,
            "Missing call to Base::%0 (required by must_upcall attribute)");
        auto builder = diag_engine.Report(method->getBeginLoc(), diag_id);
        builder << method_name;
    }

    return true;
}

bool LibJSGCVisitor::VisitCXXConstructExpr(clang::CXXConstructExpr* construct_expression)
{
    if (construct_expression->getConstructionKind() != clang::CXXConstructionKind::Complete)
        return true;

    auto const* record = construct_expression->getConstructor()->getParent();
    if (!record_inherits_from_cell(*record))
        return true;

    auto& diag_engine = m_context.getDiagnostics();
    auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "GC::Cell type %0 must be allocated with GC::Heap::allocate()");
    auto builder = diag_engine.Report(construct_expression->getBeginLoc(), diag_id);
    builder << record->getName();
    return true;
}

struct CellTypeWithOrigin {
    clang::CXXRecordDecl const& base_origin;
    LibJSCellMacro::Type type;
};

static std::optional<CellTypeWithOrigin> find_cell_type_with_origin(clang::CXXRecordDecl const& record)
{
    for (auto const& base : record.bases()) {
        if (auto const* base_record = base.getType()->getAsCXXRecordDecl()) {
            auto base_name = base_record->getQualifiedNameAsString();

            if (base_name == "GC::Cell")
                return CellTypeWithOrigin { *base_record, LibJSCellMacro::Type::GCCell };

            if (base_name == "JS::Object")
                return CellTypeWithOrigin { *base_record, LibJSCellMacro::Type::JSObject };

            if (base_name == "JS::Environment")
                return CellTypeWithOrigin { *base_record, LibJSCellMacro::Type::JSEnvironment };

            if (base_name == "JS::PrototypeObject")
                return CellTypeWithOrigin { *base_record, LibJSCellMacro::Type::JSPrototypeObject };

            if (base_name == "Web::Bindings::Wrappable")
                return CellTypeWithOrigin { *base_record, LibJSCellMacro::Type::WebWrappable };

            if (auto origin = find_cell_type_with_origin(*base_record))
                return CellTypeWithOrigin { *base_record, origin->type };
        }
    }

    return {};
}

LibJSGCVisitor::CellMacroExpectation LibJSGCVisitor::get_record_cell_macro_expectation(clang::CXXRecordDecl const& record)
{
    auto origin = find_cell_type_with_origin(record);
    assert(origin.has_value());

    // Need to iterate the bases again to turn the record into the exact text that the user used as
    // the class base, since it doesn't have to be qualified (but might be).
    for (auto const& base : record.bases()) {
        if (auto const* base_record = base.getType()->getAsCXXRecordDecl()) {
            if (base_record == &origin->base_origin) {
                auto& source_manager = m_context.getSourceManager();
                auto char_range = source_manager.getExpansionRange({ base.getBaseTypeLoc(), base.getEndLoc() });
                auto exact_text = clang::Lexer::getSourceText(char_range, source_manager, m_context.getLangOpts());
                return { origin->type, exact_text.str() };
            }
        }
    }

    assert(false);
    __builtin_unreachable();
}

void LibJSGCVisitor::validate_record_macros(clang::CXXRecordDecl const& record)
{
    auto& source_manager = m_context.getSourceManager();
    auto record_range = record.getSourceRange();

    // FIXME: The current macro detection doesn't recursively search through macro expansion,
    //        so if the record itself is defined in a macro, the GC_CELL/etc won't be found
    if (source_manager.isMacroBodyExpansion(record_range.getBegin()))
        return;

    auto [expected_cell_macro_type, expected_base_name] = get_record_cell_macro_expectation(record);
    auto file_id = m_context.getSourceManager().getFileID(record.getLocation());
    auto it = m_macro_map.find(file_id.getHashValue());
    auto& diag_engine = m_context.getDiagnostics();

    auto report_missing_macro = [&] {
        auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "Expected record to have a %0 macro invocation");
        auto builder = diag_engine.Report(record.getLocation(), diag_id);
        builder << LibJSCellMacro::type_name(expected_cell_macro_type);
    };

    if (it == m_macro_map.end()) {
        report_missing_macro();
        return;
    }

    std::vector<clang::SourceRange> sub_ranges;
    for (auto const& sub_decl : record.decls()) {
        if (auto const* sub_record = llvm::dyn_cast<clang::CXXRecordDecl>(sub_decl))
            sub_ranges.push_back(sub_record->getSourceRange());
    }

    bool found_macro = false;

    auto record_name = record.getDeclName().getAsString();
    if (record.getQualifier()) {
        // FIXME: There has to be a better way to get this info. getQualifiedNameAsString() gets too much info
        //        (outer namespaces that aren't part of the class identifier), and getNameAsString() doesn't get
        //        enough info (doesn't include parts before the namespace specifier).
        auto loc = record.getQualifierLoc();
        auto& sm = m_context.getSourceManager();
        auto begin_offset = sm.getFileOffset(loc.getBeginLoc());
        auto end_offset = sm.getFileOffset(loc.getEndLoc());
        auto const* file_buf = sm.getCharacterData(loc.getBeginLoc());
        auto prefix = std::string { file_buf, end_offset - begin_offset };
        record_name = prefix + "::" + record_name;
    }

    for (auto const& macro : it->second) {
        if (record_range.fullyContains(macro.range)) {
            bool macro_is_in_sub_decl = false;
            for (auto const& sub_range : sub_ranges) {
                if (sub_range.fullyContains(macro.range)) {
                    macro_is_in_sub_decl = true;
                    break;
                }
            }
            if (macro_is_in_sub_decl)
                continue;

            if (found_macro) {
                auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "Record has multiple GC_CELL-like macro invocations");
                diag_engine.Report(record_range.getBegin(), diag_id);
            }

            found_macro = true;
            if (macro.type != expected_cell_macro_type) {
                auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "Invalid GC-CELL-like macro invocation; expected %0");
                auto builder = diag_engine.Report(macro.range.getBegin(), diag_id);
                builder << LibJSCellMacro::type_name(expected_cell_macro_type);
            }

            // This is a compile error, no diagnostic needed
            if (macro.args.size() < 2)
                return;

            // NOTE: DOMURL is a special case since the C++ class is named differently than the IDL.
            if (macro.args[0].text != record_name && record_name != "DOMURL") {
                auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "Expected first argument of %0 macro invocation to be %1");
                auto builder = diag_engine.Report(macro.args[0].location, diag_id);
                builder << LibJSCellMacro::type_name(expected_cell_macro_type) << record_name;
            }

            if (expected_cell_macro_type == LibJSCellMacro::Type::JSPrototypeObject) {
                // FIXME: Validate the args for this macro
            } else if (macro.args[1].text != expected_base_name) {
                auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "Expected second argument of %0 macro invocation to be %1");
                auto builder = diag_engine.Report(macro.args[1].location, diag_id);
                builder << LibJSCellMacro::type_name(expected_cell_macro_type) << expected_base_name;
            }
        }
    }

    if (!found_macro)
        report_missing_macro();
}

// A dependent base such as JS::TypedArray<T> has no record of its own, so it stands for the class template it names: if
// that template is an engine object type, so is every instantiation. A base that is a template parameter stays unknown
// until the template is instantiated.
static clang::CXXRecordDecl const* record_named_by_base_type(clang::QualType base_type)
{
    if (auto const* record = base_type->getAsCXXRecordDecl())
        return record->getDefinition();

    auto const* specialization_type = base_type->getAs<clang::TemplateSpecializationType>();
    if (!specialization_type)
        return nullptr;
    if (specialization_type->isTypeAlias())
        return record_named_by_base_type(specialization_type->getAliasedType());
    auto const* class_template = llvm::dyn_cast_or_null<clang::ClassTemplateDecl>(specialization_type->getTemplateName().getAsTemplateDecl());
    if (!class_template)
        return nullptr;
    return class_template->getTemplatedDecl()->getDefinition();
}

// Every other engine object type, such as JS::NativeFunction, JS::Array, JS::Error, JS::CyclicModule or
// JS::PrototypeObject, derives from one of these.
static bool is_engine_object_type(clang::CXXRecordDecl const& record, std::unordered_set<clang::CXXRecordDecl const*>& records_seen)
{
    static std::unordered_set<std::string> const engine_object_root_types {
        "JS::Environment",
        "JS::Module",
        "JS::Object",
    };

    if (engine_object_root_types.contains(record.getQualifiedNameAsString()))
        return true;
    if (!records_seen.insert(&record).second)
        return false;

    for (auto const& base : record.bases()) {
        auto const* base_record = record_named_by_base_type(base.getType());
        if (base_record && is_engine_object_type(*base_record, records_seen))
            return true;
    }
    return false;
}

static bool is_engine_object_type(clang::CXXRecordDecl const& record)
{
    std::unordered_set<clang::CXXRecordDecl const*> records_seen;
    return is_engine_object_type(record, records_seen);
}

static clang::CXXRecordDecl const& class_definition_written_in_source(clang::CXXRecordDecl const& record)
{
    if (auto const* template_pattern = record.getTemplateInstantiationPattern())
        return *template_pattern;
    return record;
}

static std::string file_path_of_declaration(clang::SourceManager const& source_manager, clang::Decl const& declaration)
{
    auto path = source_manager.getFilename(source_manager.getFileLoc(declaration.getLocation())).str();
    if (!path.starts_with('/'))
        path.insert(0, "/");
    return path;
}

static bool is_libjs_path(std::string const& path)
{
    return path.find("/Libraries/LibJS/") != std::string::npos;
}

// These files still define their global objects and test objects as C++ subclasses of engine objects. They move to
// host objects together with the rest of the code that embeds the engine, and each entry goes away with its port.
static bool is_path_allowed_to_subclass_engine_objects(std::string const& path)
{
    static constexpr std::array legacy_engine_subclass_paths {
        "/Utilities/js.cpp",
    };
    for (auto const* legacy_path : legacy_engine_subclass_paths) {
        if (path.ends_with(legacy_path))
            return true;
    }
    return false;
}

static bool may_subclass_engine_objects(clang::SourceManager const& source_manager, clang::CXXRecordDecl const& record)
{
    auto path = file_path_of_declaration(source_manager, class_definition_written_in_source(record));
    return is_libjs_path(path) || is_path_allowed_to_subclass_engine_objects(path);
}

// The visitor checks every class written in the source and every instantiation of a class template written in the
// source, but not the classes and class templates that an instantiation declares as its members.
static bool is_checked_for_engine_subclassing(clang::CXXRecordDecl const& record)
{
    if (auto const* specialization = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(&record))
        return !specialization->getSpecializedTemplate()->getInstantiatedFromMemberTemplate();
    return !record.getInstantiatedFromMemberClass();
}

static clang::CXXRecordDecl const& engine_object_type_that_may_be_subclassed(clang::SourceManager const& source_manager, clang::CXXRecordDecl const& engine_object_type)
{
    if (may_subclass_engine_objects(source_manager, engine_object_type))
        return engine_object_type;
    for (auto const& base : engine_object_type.bases()) {
        auto const* base_record = record_named_by_base_type(base.getType());
        if (base_record && is_engine_object_type(*base_record))
            return engine_object_type_that_may_be_subclassed(source_manager, *base_record);
    }
    return engine_object_type;
}

static std::string name_for_diagnostic(clang::ASTContext const& context, clang::NamedDecl const& declaration)
{
    std::string name;
    llvm::raw_string_ostream stream(name);
    declaration.getNameForDiagnostic(stream, context.getPrintingPolicy(), false);
    return name;
}

void LibJSGCVisitor::validate_engine_subclass_is_in_libjs(clang::CXXRecordDecl const& record)
{
    auto& source_manager = m_context.getSourceManager();
    if (may_subclass_engine_objects(source_manager, record))
        return;

    // A class template that is an engine object type whatever its arguments are gets the diagnostic in place of its
    // instantiations.
    auto const& class_definition = class_definition_written_in_source(record);
    if (&class_definition != &record && is_engine_object_type(class_definition))
        return;

    for (auto const& base : record.bases()) {
        auto const* base_record = record_named_by_base_type(base.getType());
        if (!base_record || !is_engine_object_type(*base_record))
            continue;

        // A checked base outside LibJS gets the diagnostic in place of the classes derived from it.
        if (!may_subclass_engine_objects(source_manager, *base_record) && is_checked_for_engine_subclassing(*base_record))
            continue;

        auto& diag_engine = m_context.getDiagnostics();
        auto record_name = name_for_diagnostic(m_context, record);
        auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "%0 derives from the engine type %1, which only LibJS may subclass; use a host class instead");
        auto const& engine_object_type = engine_object_type_that_may_be_subclassed(source_manager, *base_record);
        diag_engine.Report(record.getLocation(), diag_id) << record_name << engine_object_type.getQualifiedNameAsString();

        auto const* specialization = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(&record);
        if (specialization && specialization->getSpecializationKind() == clang::TSK_ImplicitInstantiation) {
            auto note_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Note, "%0 is instantiated here");
            diag_engine.Report(specialization->getPointOfInstantiation(), note_id) << record_name;
        }
    }
}

// The visitor sees only the classes written in the source. An instantiation of a class template can still be an engine
// object type when the template derives from one of its arguments, so the implicit instantiations are checked here.
bool LibJSGCVisitor::VisitClassTemplateDecl(clang::ClassTemplateDecl* class_template)
{
    if (!class_template->isThisDeclarationADefinition())
        return true;

    for (auto const* specialization : class_template->specializations()) {
        if (specialization->getSpecializationKind() != clang::TSK_ImplicitInstantiation || !specialization->isCompleteDefinition())
            continue;
        validate_engine_subclass_is_in_libjs(*specialization);
        remember_polymorphic_subclass(*specialization);
        if (!record_inherits_from_cell(*specialization))
            validate_gc_members_of_polymorphic_record(*specialization);
    }
    return true;
}

struct TemplateInstance {
    std::string name;
    std::vector<clang::QualType> type_arguments;
};

static void append_type_arguments(llvm::ArrayRef<clang::TemplateArgument> arguments, std::vector<clang::QualType>& type_arguments)
{
    for (auto const& argument : arguments) {
        if (argument.getKind() == clang::TemplateArgument::Type)
            type_arguments.push_back(argument.getAsType());
        else if (argument.getKind() == clang::TemplateArgument::Pack)
            append_type_arguments(argument.pack_elements(), type_arguments);
    }
}

// These hold their values outside the object they are stored in, or are visible to the GC already.
static bool is_type_that_does_not_store_gc_pointers_by_value(std::string const& template_name)
{
    static std::unordered_set<std::string> const template_names {
        "AK::NonnullOwnPtr",
        "AK::NonnullRefPtr",
        "AK::OwnPtr",
        "AK::RefPtr",
        "AK::Span",
        "AK::WeakPtr",
        "GC::RawPtr",
        "GC::RawRef",
        "GC::Root",
        "GC::RootHashMap",
        "GC::RootHashTable",
        "GC::RootVector",
        "GC::Weak",
        "GC::WeakHashMap",
        "GC::WeakHashSet",
    };
    return template_names.contains(template_name);
}

// The template arguments as written keep alias templates such as GC::RawPtr, which the canonical arguments of a
// specialization resolve to the template they alias. A dependent type such as Vector<GC::Ref<T>> only has those.
static std::optional<TemplateInstance> template_instance_of_type(clang::QualType type)
{
    if (auto const* specialization_type = type->getAs<clang::TemplateSpecializationType>()) {
        auto const* template_decl = specialization_type->getTemplateName().getAsTemplateDecl();
        if (!template_decl)
            return {};
        auto template_name = template_decl->getQualifiedNameAsString();
        if (specialization_type->isTypeAlias() && !is_type_that_does_not_store_gc_pointers_by_value(template_name))
            return template_instance_of_type(specialization_type->getAliasedType());

        TemplateInstance instance { std::move(template_name), {} };
        append_type_arguments(specialization_type->template_arguments(), instance.type_arguments);
        return instance;
    }

    if (auto const* specialization = llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>(type->getAsCXXRecordDecl())) {
        TemplateInstance instance { specialization->getSpecializedTemplate()->getQualifiedNameAsString(), {} };
        append_type_arguments(specialization->getTemplateArgs().asArray(), instance.type_arguments);
        return instance;
    }
    return {};
}

static bool record_is_nan_boxed_value(clang::CXXRecordDecl const& record)
{
    if (record.getQualifiedNameAsString() == "GC::NanBoxedValue")
        return true;
    return !record.forallBases([](clang::CXXRecordDecl const* base) {
        return base->getQualifiedNameAsString() != "GC::NanBoxedValue";
    });
}

static bool record_is_in_ak_or_gc(clang::CXXRecordDecl const& record)
{
    auto qualified_name = record.getQualifiedNameAsString();
    return qualified_name.starts_with("AK::") || qualified_name.starts_with("GC::");
}

// Whether a value of this type holds a pointer that a GC root container could keep alive, or a struct that holds one.
static bool type_holds_gc_pointer(clang::QualType type, std::set<clang::CXXRecordDecl const*>& visited)
{
    if (auto const* array = type->getAsArrayTypeUnsafe())
        return type_holds_gc_pointer(array->getElementType(), visited);

    if (type->isPointerType() || type->isReferenceType()) {
        auto const* pointee = type->getPointeeCXXRecordDecl();
        auto const* definition = pointee ? pointee->getDefinition() : nullptr;
        return definition && record_inherits_from_cell(*definition);
    }

    if (auto instance = template_instance_of_type(type)) {
        if (instance->name == "GC::Ptr" || instance->name == "GC::Ref")
            return true;
        if (is_type_that_does_not_store_gc_pointers_by_value(instance->name))
            return false;
        for (auto const& type_argument : instance->type_arguments) {
            if (type_holds_gc_pointer(type_argument, visited))
                return true;
        }
    }

    auto const* record = type->getAsCXXRecordDecl();
    if (!record || !record->isCompleteDefinition() || !visited.insert(record).second)
        return false;
    if (record_is_nan_boxed_value(*record))
        return true;
    if (record_is_in_ak_or_gc(*record) || record_inherits_from_cell(*record))
        return false;
    for (auto const& base : record->bases()) {
        if (type_holds_gc_pointer(base.getType(), visited))
            return true;
    }
    for (auto const* field : record->fields()) {
        if (type_holds_gc_pointer(field->getType(), visited))
            return true;
    }
    return false;
}

// Whether a type declares with GC_HOLDS_NO_CELL_EDGES, or inherits from one that declares, that it holds no cell edges.
static bool record_declares_no_cell_edges(clang::CXXRecordDecl const& record)
{
    auto declares = [](clang::CXXRecordDecl const* candidate) {
        for (auto const* declaration : candidate->decls()) {
            if (auto const* alias = llvm::dyn_cast<clang::TypedefNameDecl>(declaration); alias && alias->getName() == "HoldsNoCellEdges")
                return true;
        }
        return false;
    };
    if (declares(&record))
        return true;
    // NB: forallBases() gives up on a dependent base, so the bases are walked here, skipping those not known yet.
    for (auto const& base : record.bases()) {
        auto const* base_record = base.getType()->getAsCXXRecordDecl();
        base_record = base_record ? base_record->getDefinition() : nullptr;
        if (base_record && record_declares_no_cell_edges(*base_record))
            return true;
    }
    return false;
}

enum class ClaimViolation {
    GCPointer,
    OpaqueFunction,
};

static bool is_owning_pointer(std::string const& template_name)
{
    return template_name == "AK::NonnullOwnPtr" || template_name == "AK::NonnullRefPtr" || template_name == "AK::OwnPtr" || template_name == "AK::RefPtr";
}

// Whether a value of this type holds what a type declared to hold no cell edges must not: a GC pointer, which nothing
// would trace, or an AK::Function, whose captures no check can see. Roots and weak pointers need no tracing. A GC pointer
// is looked for in what the value owns too, unless the pointee declares the claim itself and is checked on its own.
// NB: An owned object's callbacks are its own API, such as those of libraries below LibGC, which can't keep a
//     GC::Function. As with every AK::Function, what they capture must be rooted or weak.
static bool record_violates_claim_of_no_cell_edges(clang::CXXRecordDecl const&, ClaimViolation, std::set<clang::CXXRecordDecl const*>& visited, PolymorphicSubclasses const&);

static bool type_violates_claim_of_no_cell_edges(clang::QualType type, ClaimViolation violation, std::set<clang::CXXRecordDecl const*>& visited, PolymorphicSubclasses const& polymorphic_subclasses)
{
    if (auto const* array = type->getAsArrayTypeUnsafe())
        return type_violates_claim_of_no_cell_edges(array->getElementType(), violation, visited, polymorphic_subclasses);

    // NB: A raw pointer to a cell, or to something with cell edges such as the mixin of a cell, is an edge that nothing
    //     traces. Whether a pointee that is only declared is one can't be seen.
    if (type->isPointerType() || type->isReferenceType()) {
        if (violation != ClaimViolation::GCPointer)
            return false;
        auto const* pointee = type->getPointeeCXXRecordDecl();
        auto const* definition = pointee ? pointee->getDefinition() : nullptr;
        return definition && (record_inherits_from_cell(*definition) || (!record_is_in_ak_or_gc(*definition) && type_has_visit_edges_method(definition)));
    }

    if (auto instance = template_instance_of_type(type)) {
        if (instance->name == "AK::Function")
            return violation == ClaimViolation::OpaqueFunction;
        if (instance->name == "GC::Ptr" || instance->name == "GC::Ref" || instance->name == "GC::RawPtr" || instance->name == "GC::RawRef" || instance->name == "GC::Member" || instance->name == "GC::NonnullMember")
            return violation == ClaimViolation::GCPointer;
        if (is_owning_pointer(instance->name)) {
            if (violation != ClaimViolation::GCPointer || instance->type_arguments.empty())
                return false;
            auto const* pointee = instance->type_arguments.front()->getAsCXXRecordDecl();
            pointee = pointee ? pointee->getDefinition() : nullptr;
            if (pointee && record_declares_no_cell_edges(*pointee))
                return false;
            if (type_violates_claim_of_no_cell_edges(instance->type_arguments.front(), violation, visited, polymorphic_subclasses))
                return true;
            // NB: The pointer may own a subclass of its pointee.
            if (!pointee)
                return false;
            auto subclasses = polymorphic_subclasses.find(pointee->getCanonicalDecl());
            if (subclasses == polymorphic_subclasses.end())
                return false;
            for (auto const* subclass : subclasses->second) {
                if (record_declares_no_cell_edges(*subclass))
                    continue;
                if (record_violates_claim_of_no_cell_edges(*subclass, violation, visited, polymorphic_subclasses))
                    return true;
            }
            return false;
        }
        if (is_type_that_does_not_store_gc_pointers_by_value(instance->name))
            return false;
        for (auto const& type_argument : instance->type_arguments) {
            if (type_violates_claim_of_no_cell_edges(type_argument, violation, visited, polymorphic_subclasses))
                return true;
        }
    }

    auto const* record = type->getAsCXXRecordDecl();
    return record && record_violates_claim_of_no_cell_edges(*record, violation, visited, polymorphic_subclasses);
}

static bool record_violates_claim_of_no_cell_edges(clang::CXXRecordDecl const& record, ClaimViolation violation, std::set<clang::CXXRecordDecl const*>& visited, PolymorphicSubclasses const& polymorphic_subclasses)
{
    if (!record.isCompleteDefinition() || !visited.insert(&record).second)
        return false;
    if (record_is_nan_boxed_value(record))
        return violation == ClaimViolation::GCPointer;
    if (record_is_in_ak_or_gc(record) || record_inherits_from_cell(record))
        return false;
    for (auto const& base : record.bases()) {
        if (type_violates_claim_of_no_cell_edges(base.getType(), violation, visited, polymorphic_subclasses))
            return true;
    }
    for (auto const* field : record.fields()) {
        if (type_violates_claim_of_no_cell_edges(field->getType(), violation, visited, polymorphic_subclasses))
            return true;
    }
    return false;
}

// A GC::Function captures a type that declares that it holds no cell edges without tracing it, so the type must not hold
// a GC pointer, which nothing would keep alive. Roots and weak pointers are fine, as they need no tracing. Nor may it hold
// an AK::Function, whose captures could hold anything.
// NB: Claims are checked once the translation unit is complete, when every instantiation of a class template that makes
//     the claim, and every subclass of what a claimed type owns, is known.
void LibJSGCVisitor::remember_claim_of_no_cell_edges(clang::CXXRecordDecl const& record)
{
    clang::CXXRecordDecl const* claimed_record = nullptr;
    bool callbacks_hold_roots = false;
    bool claim_covers_subclasses = false;
    if (auto const* specialization = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(&record)) {
        if (specialization->getSpecializationKind() != clang::TSK_ExplicitSpecialization || specialization->getSpecializedTemplate()->getQualifiedNameAsString() != "GC::IsUntracedCapture")
            return;
        // NB: GC_UNTRACED_CAPTURE_WITH_ROOTED_CALLBACKS() declares that the type's callbacks hold roots, which no check
        //     can see, so only its other members are checked.
        for (auto const* declaration : specialization->decls()) {
            if (auto const* variable = llvm::dyn_cast<clang::VarDecl>(declaration); variable && variable->getName() == "callbacks_hold_roots")
                callbacks_hold_roots = true;
        }
        // NB: A partial specialization declares the claim for whatever its arguments hold, which is checked where they
        //     make claims of their own.
        auto const& arguments = specialization->getTemplateArgs();
        if (llvm::isa<clang::ClassTemplatePartialSpecializationDecl>(specialization) || arguments.size() != 1 || arguments[0].getKind() != clang::TemplateArgument::Type || arguments[0].getAsType()->isDependentType())
            return;
        claimed_record = arguments[0].getAsType()->getAsCXXRecordDecl();
        // NB: Unlike a claim made in the class, which its subclasses inherit and make themselves, this one covers a
        //     counted or owned pointer to the class, which may point to a subclass.
        claim_covers_subclasses = true;
    } else if (record_declares_no_cell_edges(record)) {
        claimed_record = &record;
    }
    if (claimed_record)
        m_claims_of_no_cell_edges.push_back({ claimed_record, callbacks_hold_roots, claim_covers_subclasses });
}

void LibJSGCVisitor::validate_claims_of_no_cell_edges()
{
    std::set<clang::CXXRecordDecl const*> validated;
    auto validate = [&](clang::CXXRecordDecl const* record, bool callbacks_hold_roots, clang::CXXRecordDecl const* claiming_base = nullptr) {
        if (record && record->isCompleteDefinition() && !record->isDependentContext() && validated.insert(record).second)
            validate_claim_of_no_cell_edges(*record, callbacks_hold_roots, claiming_base);
    };
    for (auto const& claim : m_claims_of_no_cell_edges) {
        if (auto const* class_template = claim.record->getDescribedClassTemplate()) {
            for (auto const* specialization : class_template->specializations())
                validate(specialization, claim.callbacks_hold_roots);
            continue;
        }
        auto const* definition = claim.record->getDefinition();
        validate(definition, claim.callbacks_hold_roots);
        if (!claim.covers_subclasses || !definition)
            continue;
        // NB: A subclass that makes the claim itself is checked on its own.
        auto subclasses = m_polymorphic_subclasses.find(definition->getCanonicalDecl());
        if (subclasses == m_polymorphic_subclasses.end())
            continue;
        for (auto const* subclass : subclasses->second) {
            if (!record_declares_no_cell_edges(*subclass))
                validate(subclass, claim.callbacks_hold_roots, definition);
        }
    }
}

// NB: A subclass of a class whose counted or owned pointers are declared to hold no cell edges is checked with the claiming
//     base, which is checked on its own.
void LibJSGCVisitor::validate_claim_of_no_cell_edges(clang::CXXRecordDecl const& record, bool callbacks_hold_roots, clang::CXXRecordDecl const* claiming_base)
{
    auto const* claimed_record = &record;
    auto& diag_engine = m_context.getDiagnostics();
    auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "%0 is declared to hold no cell edges, but its member %1 holds a GC pointer");
    auto record_name = name_for_diagnostic(m_context, *claimed_record);
    if (claiming_base)
        record_name += " (through its base " + name_for_diagnostic(m_context, *claiming_base) + ")";
    auto function_diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "%0 is declared to hold no cell edges, but its member %1 holds an AK::Function, whose captures can't be checked");
    auto violates = [&](clang::QualType type, ClaimViolation violation) {
        if (violation == ClaimViolation::OpaqueFunction && callbacks_hold_roots)
            return false;
        // NB: The claimed type is checked here already, wherever its members lead back to it, such as through the
        //     template arguments of RefCounted<T>.
        std::set<clang::CXXRecordDecl const*> visited { claimed_record };
        if (claiming_base)
            visited.insert(claiming_base);
        return type_violates_claim_of_no_cell_edges(type, violation, visited, m_polymorphic_subclasses);
    };
    for (auto const* field : claimed_record->fields()) {
        if (violates(field->getType(), ClaimViolation::GCPointer))
            diag_engine.Report(field->getLocation(), diag_id) << record_name << field->getName();
        if (violates(field->getType(), ClaimViolation::OpaqueFunction))
            diag_engine.Report(field->getLocation(), function_diag_id) << record_name << field->getName();
    }

    // NB: A base that declares the claim itself is checked on its own.
    auto base_diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "%0 is declared to hold no cell edges, but its base %1 holds a GC pointer");
    auto base_function_diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "%0 is declared to hold no cell edges, but its base %1 holds an AK::Function, whose captures can't be checked");
    for (auto const& base : claimed_record->bases()) {
        auto const* base_record = base.getType()->getAsCXXRecordDecl();
        if (base_record && record_declares_no_cell_edges(*base_record))
            continue;
        if (violates(base.getType(), ClaimViolation::GCPointer))
            diag_engine.Report(base.getBeginLoc(), base_diag_id) << record_name << base.getType();
        if (violates(base.getType(), ClaimViolation::OpaqueFunction))
            diag_engine.Report(base.getBeginLoc(), base_function_diag_id) << record_name << base.getType();
    }
}

void LibJSGCVisitor::validate_gc_members_of_polymorphic_record(clang::CXXRecordDecl const& record)
{
    if (record.isDependentContext() || !record.isPolymorphic() || type_has_visit_edges_method(&record))
        return;

    bool has_polymorphic_base = false;
    record.forallBases([&](clang::CXXRecordDecl const* base) {
        has_polymorphic_base |= base->isPolymorphic();
        return !has_polymorphic_base;
    });
    if (!has_polymorphic_base)
        return;

    auto& diag_engine = m_context.getDiagnostics();
    auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "Member %0 of polymorphic class %1 contains GC pointers but %1 has no visit_edges method");
    auto record_name = name_for_diagnostic(m_context, record);
    for (auto const* field : record.fields()) {
        std::set<clang::CXXRecordDecl const*> visited;
        if (type_holds_gc_pointer(field->getType(), visited))
            diag_engine.Report(field->getLocation(), diag_id) << field->getName() << record_name;
    }
}

void LibJSGCVisitor::remember_polymorphic_subclass(clang::CXXRecordDecl const& record)
{
    if (record.isDependentContext() || !record.isPolymorphic())
        return;
    record.forallBases([&](clang::CXXRecordDecl const* base) {
        if (base->isPolymorphic())
            m_polymorphic_subclasses[base->getCanonicalDecl()].push_back(&record);
        return true;
    });
}

static bool is_container_with_heap_storage(std::string const& template_name)
{
    static std::unordered_set<std::string> const template_names {
        "AK::DoublyLinkedList",
        "AK::FixedArray",
        "AK::HashMap",
        "AK::HashTable",
        "AK::Queue",
        "AK::SinglyLinkedList",
        "AK::Vector",
    };
    return template_names.contains(template_name);
}

// The GC sees the values these store, but not the heap storage of a container stored in one of them.
static bool is_container_scanned_by_gc(std::string const& template_name)
{
    static std::unordered_set<std::string> const template_names {
        "GC::RootHashMap",
        "GC::RootHashTable",
        "GC::RootVector",
    };
    return template_names.contains(template_name);
}

static bool is_root_container(std::string const& template_name)
{
    return template_name == "GC::RootHashMap" || template_name == "GC::RootHashTable" || template_name == "GC::RootVector";
}

static bool is_value_wrapper(std::string const& template_name)
{
    static std::unordered_set<std::string> const template_names {
        "AK::Array",
        "AK::ErrorOr",
        "AK::Optional",
        "AK::Tuple",
        "AK::Variant",
    };
    return template_names.contains(template_name);
}

static std::optional<clang::QualType> find_container_with_unscanned_gc_pointers(clang::QualType, std::set<clang::CXXRecordDecl const*>& visited, PolymorphicSubclasses const* subclasses_of_owned_types = nullptr);

static clang::FieldDecl const* find_owned_member_with_gc_pointers(clang::QualType owned_type, std::set<clang::CXXRecordDecl const*>& visited, PolymorphicSubclasses const& subclasses_of_owned_types)
{
    auto const* record = owned_type->getAsCXXRecordDecl();
    if (!record || !record->getDefinition())
        return nullptr;
    record = record->getDefinition();
    if (record_is_in_ak_or_gc(*record) || record_inherits_from_cell(*record) || !visited.insert(record).second)
        return nullptr;

    std::vector<clang::CXXRecordDecl const*> records { record };
    record->forallBases([&](clang::CXXRecordDecl const* base) {
        records.push_back(base);
        return true;
    });
    if (auto subclasses = subclasses_of_owned_types.find(record->getCanonicalDecl()); subclasses != subclasses_of_owned_types.end())
        records.insert(records.end(), subclasses->second.begin(), subclasses->second.end());

    for (auto const* candidate : records) {
        for (auto const* field : candidate->fields()) {
            std::set<clang::CXXRecordDecl const*> visited_by_field;
            if (type_holds_gc_pointer(field->getType(), visited_by_field) || find_container_with_unscanned_gc_pointers(field->getType(), visited, &subclasses_of_owned_types))
                return field;
        }
    }
    return nullptr;
}

// Conservative stack scanning sees the values stored in a stack object, but not the heap storage of a container in it.
static std::optional<clang::QualType> find_container_with_unscanned_gc_pointers(clang::QualType type, std::set<clang::CXXRecordDecl const*>& visited, PolymorphicSubclasses const* subclasses_of_owned_types)
{
    if (auto const* array = type->getAsArrayTypeUnsafe())
        return find_container_with_unscanned_gc_pointers(array->getElementType(), visited, subclasses_of_owned_types);

    if (type->isPointerType() || type->isReferenceType())
        return {};

    if (auto instance = template_instance_of_type(type)) {
        if (is_container_with_heap_storage(instance->name)) {
            for (auto const& type_argument : instance->type_arguments) {
                std::set<clang::CXXRecordDecl const*> visited_by_element;
                if (type_holds_gc_pointer(type_argument, visited_by_element))
                    return type;
                if (subclasses_of_owned_types && find_container_with_unscanned_gc_pointers(type_argument, visited, subclasses_of_owned_types))
                    return type;
            }
            return {};
        }
        if (subclasses_of_owned_types && is_owning_pointer(instance->name)) {
            for (auto const& type_argument : instance->type_arguments) {
                std::set<clang::CXXRecordDecl const*> visited_by_object;
                if (type_holds_gc_pointer(type_argument, visited_by_object) || find_owned_member_with_gc_pointers(type_argument, visited, *subclasses_of_owned_types))
                    return type;
                if (find_container_with_unscanned_gc_pointers(type_argument, visited, subclasses_of_owned_types))
                    return type;
            }
            return {};
        }
        if (is_value_wrapper(instance->name) || is_container_scanned_by_gc(instance->name)) {
            for (auto const& type_argument : instance->type_arguments) {
                // NB: A root container traces a value with a visit_edges(), which visits what the value keeps on the heap.
                if (is_root_container(instance->name) && type_has_visit_edges_method(type_argument->getAsCXXRecordDecl()))
                    continue;
                if (auto container = find_container_with_unscanned_gc_pointers(type_argument, visited, subclasses_of_owned_types))
                    return container;
            }
            return {};
        }
        if (is_type_that_does_not_store_gc_pointers_by_value(instance->name))
            return {};
    }

    auto const* record = type->getAsCXXRecordDecl();
    if (!record || !record->isCompleteDefinition() || !visited.insert(record).second)
        return {};
    if (record_is_in_ak_or_gc(*record) || record_inherits_from_cell(*record))
        return {};
    for (auto const& base : record->bases()) {
        if (auto container = find_container_with_unscanned_gc_pointers(base.getType(), visited, subclasses_of_owned_types))
            return container;
    }
    for (auto const* field : record->fields()) {
        if (auto container = find_container_with_unscanned_gc_pointers(field->getType(), visited, subclasses_of_owned_types))
            return container;
    }
    return {};
}

static clang::QualType type_of_object_on_stack(clang::VarDecl const& variable)
{
    if (!variable.getType()->isReferenceType())
        return variable.getType();

    // A reference that extends the lifetime of a temporary keeps that temporary on the stack.
    auto const* initializer = variable.getInit();
    if (auto const* expression_with_cleanups = llvm::dyn_cast_or_null<clang::ExprWithCleanups>(initializer))
        initializer = expression_with_cleanups->getSubExpr();
    auto const* temporary = llvm::dyn_cast_or_null<clang::MaterializeTemporaryExpr>(initializer);
    if (!temporary || temporary->getExtendingDecl() != &variable)
        return {};
    return temporary->getType();
}

void LibJSGCVisitor::validate_object_on_stack(clang::VarDecl const& variable, clang::SourceLocation location)
{
    auto type = type_of_object_on_stack(variable);
    if (type.isNull())
        return;

    validate_type_on_stack(type, location);
}

void LibJSGCVisitor::validate_type_on_stack(clang::QualType type, clang::SourceLocation location)
{
    std::set<clang::CXXRecordDecl const*> visited;
    auto container = find_container_with_unscanned_gc_pointers(type, visited);
    if (!container)
        return;

    auto& diag_engine = m_context.getDiagnostics();
    auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "%0 keeps GC pointers in heap memory that is not scanned for roots; use GC::RootVector, GC::RootHashMap or GC::RootHashTable instead");
    diag_engine.Report(location, diag_id) << *container;
}

bool LibJSGCVisitor::VisitVarDecl(clang::VarDecl* variable)
{
    if (!variable->hasLocalStorage() || variable->isImplicit())
        return true;

    // A parameter passed by value is an object on the stack of the definition, like a local. A container that is moved
    // into a field is taken by rvalue reference instead, so that the caller keeps it until then.
    if (llvm::isa<clang::ParmVarDecl>(variable)) {
        auto const* function = llvm::dyn_cast<clang::FunctionDecl>(variable->getDeclContext());
        if (!function || !function->doesThisDeclarationHaveABody() || function->isImplicit())
            return true;
    }

    validate_object_on_stack(*variable, variable->getLocation());
    return true;
}

// The hidden range variable of a range-based for loop keeps a temporary range alive for the whole loop.
bool LibJSGCVisitor::VisitCXXForRangeStmt(clang::CXXForRangeStmt* for_range)
{
    auto const* range_statement = for_range->getRangeStmt();
    if (!range_statement || !range_statement->isSingleDecl())
        return true;
    if (auto const* range_variable = llvm::dyn_cast<clang::VarDecl>(range_statement->getSingleDecl()))
        validate_object_on_stack(*range_variable, for_range->getRangeInit()->getBeginLoc());
    return true;
}

// A container returned by value becomes a temporary or a local of the caller.
bool LibJSGCVisitor::VisitFunctionDecl(clang::FunctionDecl* function)
{
    if (function->doesThisDeclarationHaveABody() && !function->isImplicit() && !function->getReturnType()->isReferenceType())
        validate_type_on_stack(function->getReturnType(), function->getLocation());
    return true;
}

// The call operator of a lambda is only visited through its body.
bool LibJSGCVisitor::VisitLambdaExpr(clang::LambdaExpr* lambda)
{
    auto return_type = lambda->getCallOperator()->getReturnType();
    if (!return_type->isReferenceType())
        validate_type_on_stack(return_type, lambda->getBeginLoc());
    return true;
}

LibJSGCASTConsumer::LibJSGCASTConsumer(clang::CompilerInstance& compiler, bool detect_invalid_function_members)
    : m_compiler(compiler)
    , m_detect_invalid_function_members(detect_invalid_function_members)
{
    auto& preprocessor = compiler.getPreprocessor();
    preprocessor.addPPCallbacks(std::make_unique<LibJSPPCallbacks>(preprocessor, m_macro_map));
}

void LibJSGCASTConsumer::HandleTranslationUnit(clang::ASTContext& context)
{
    LibJSGCVisitor visitor { context, m_macro_map, m_detect_invalid_function_members };
    visitor.TraverseDecl(context.getTranslationUnitDecl());
    visitor.validate_claims_of_no_cell_edges();
}

char const* LibJSCellMacro::type_name(Type type)
{
    switch (type) {
    case Type::GCCell:
        return "GC_CELL";
    case Type::JSObject:
        return "JS_OBJECT";
    case Type::JSEnvironment:
        return "JS_ENVIRONMENT";
    case Type::JSPrototypeObject:
        return "JS_PROTOTYPE_OBJECT";
    case Type::WebWrappable:
        return "WEB_WRAPPABLE";
    default:
        __builtin_unreachable();
    }
}

void LibJSPPCallbacks::LexedFileChanged(clang::FileID curr_fid, LexedFileChangeReason reason, clang::SrcMgr::CharacteristicKind, clang::FileID, clang::SourceLocation)
{
    if (reason == LexedFileChangeReason::EnterFile) {
        m_curr_fid_hash_stack.push_back(curr_fid.getHashValue());
    } else {
        assert(!m_curr_fid_hash_stack.empty());
        m_curr_fid_hash_stack.pop_back();
    }
}

void LibJSPPCallbacks::MacroExpands(clang::Token const& name_token, clang::MacroDefinition const&, clang::SourceRange range, clang::MacroArgs const* args)
{
    if (auto* ident_info = name_token.getIdentifierInfo()) {
        static llvm::StringMap<LibJSCellMacro::Type> libjs_macro_types {
            { "GC_CELL", LibJSCellMacro::Type::GCCell },
            { "GC_CELL_WITH_CUSTOM_CLASS_NAME", LibJSCellMacro::Type::GCCell },
            { "JS_OBJECT", LibJSCellMacro::Type::JSObject },
            { "JS_OBJECT_WITH_CUSTOM_CLASS_NAME", LibJSCellMacro::Type::JSObject },
            { "JS_ENVIRONMENT", LibJSCellMacro::Type::JSEnvironment },
            { "JS_PROTOTYPE_OBJECT", LibJSCellMacro::Type::JSPrototypeObject },
            { "WEB_WRAPPABLE", LibJSCellMacro::Type::WebWrappable },
            { "WEB_NON_IDL_WRAPPABLE", LibJSCellMacro::Type::WebWrappable },
        };

        auto name = ident_info->getName();
        if (auto it = libjs_macro_types.find(name); it != libjs_macro_types.end()) {
            LibJSCellMacro macro { range, it->second, {} };

            for (size_t arg_index = 0; arg_index < args->getNumMacroArguments(); arg_index++) {
                auto const* first_token = args->getUnexpArgument(arg_index);
                auto stringified_token = clang::MacroArgs::StringifyArgument(first_token, m_preprocessor, false, range.getBegin(), range.getEnd());
                // The token includes leading and trailing quotes
                auto len = strlen(stringified_token.getLiteralData());
                std::string arg_text { stringified_token.getLiteralData() + 1, len - 2 };
                macro.args.push_back({ arg_text, first_token->getLocation() });
            }

            assert(!m_curr_fid_hash_stack.empty());
            auto curr_fid_hash = m_curr_fid_hash_stack.back();
            if (m_macro_map.find(curr_fid_hash) == m_macro_map.end())
                m_macro_map[curr_fid_hash] = {};
            m_macro_map[curr_fid_hash].push_back(macro);
        }
    }
}

static clang::FrontendPluginRegistry::Add<LibJSGCPluginAction> X("libjs_gc_scanner", "analyze LibJS GC usage");