1 //===- ASTStructuralEquivalence.cpp ---------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implement StructuralEquivalenceContext class and helper functions
10 // for layout matching.
12 // The structural equivalence check could have been implemented as a parallel
13 // BFS on a pair of graphs. That must have been the original approach at the
15 // Let's consider this simple BFS algorithm from the `s` source:
17 // void bfs(Graph G, int s)
19 // Queue<Integer> queue = new Queue<Integer>();
20 // marked[s] = true; // Mark the source
21 // queue.enqueue(s); // and put it on the queue.
22 // while (!q.isEmpty()) {
23 // int v = queue.dequeue(); // Remove next vertex from the queue.
24 // for (int w : G.adj(v))
25 // if (!marked[w]) // For every unmarked adjacent vertex,
33 // Indeed, it has it's queue, which holds pairs of nodes, one from each graph,
34 // this is the `DeclsToCheck` member. `VisitedDecls` plays the role of the
35 // marking (`marked`) functionality above, we use it to check whether we've
36 // already seen a pair of nodes.
38 // We put in the elements into the queue only in the toplevel decl check
41 // static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
42 // Decl *D1, Decl *D2);
44 // The `while` loop where we iterate over the children is implemented in
45 // `Finish()`. And `Finish` is called only from the two **member** functions
46 // which check the equivalency of two Decls or two Types. ASTImporter (and
47 // other clients) call only these functions.
49 // The `static` implementation functions are called from `Finish`, these push
50 // the children nodes to the queue via `static bool
51 // IsStructurallyEquivalent(StructuralEquivalenceContext &Context, Decl *D1,
52 // Decl *D2)`. So far so good, this is almost like the BFS. However, if we
53 // let a static implementation function to call `Finish` via another **member**
54 // function that means we end up with two nested while loops each of them
55 // working on the same queue. This is wrong and nobody can reason about it's
56 // doing. Thus, static implementation functions must not call the **member**
59 //===----------------------------------------------------------------------===//
61 #include "clang/AST/ASTStructuralEquivalence.h"
62 #include "clang/AST/ASTContext.h"
63 #include "clang/AST/ASTDiagnostic.h"
64 #include "clang/AST/Decl.h"
65 #include "clang/AST/DeclBase.h"
66 #include "clang/AST/DeclCXX.h"
67 #include "clang/AST/DeclFriend.h"
68 #include "clang/AST/DeclObjC.h"
69 #include "clang/AST/DeclOpenMP.h"
70 #include "clang/AST/DeclTemplate.h"
71 #include "clang/AST/ExprCXX.h"
72 #include "clang/AST/ExprConcepts.h"
73 #include "clang/AST/ExprObjC.h"
74 #include "clang/AST/ExprOpenMP.h"
75 #include "clang/AST/NestedNameSpecifier.h"
76 #include "clang/AST/StmtObjC.h"
77 #include "clang/AST/StmtOpenMP.h"
78 #include "clang/AST/TemplateBase.h"
79 #include "clang/AST/TemplateName.h"
80 #include "clang/AST/Type.h"
81 #include "clang/Basic/ExceptionSpecificationType.h"
82 #include "clang/Basic/IdentifierTable.h"
83 #include "clang/Basic/LLVM.h"
84 #include "clang/Basic/SourceLocation.h"
85 #include "llvm/ADT/APInt.h"
86 #include "llvm/ADT/APSInt.h"
87 #include "llvm/ADT/StringExtras.h"
88 #include "llvm/Support/Casting.h"
89 #include "llvm/Support/Compiler.h"
90 #include "llvm/Support/ErrorHandling.h"
95 using namespace clang;
97 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
98 QualType T1, QualType T2);
99 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
101 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
102 const TemplateArgument &Arg1,
103 const TemplateArgument &Arg2);
104 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
105 const TemplateArgumentLoc &Arg1,
106 const TemplateArgumentLoc &Arg2);
107 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
108 NestedNameSpecifier *NNS1,
109 NestedNameSpecifier *NNS2);
110 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
111 const IdentifierInfo *Name2);
113 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
114 const DeclarationName Name1,
115 const DeclarationName Name2) {
116 if (Name1.getNameKind() != Name2.getNameKind())
119 switch (Name1.getNameKind()) {
121 case DeclarationName::Identifier:
122 return IsStructurallyEquivalent(Name1.getAsIdentifierInfo(),
123 Name2.getAsIdentifierInfo());
125 case DeclarationName::CXXConstructorName:
126 case DeclarationName::CXXDestructorName:
127 case DeclarationName::CXXConversionFunctionName:
128 return IsStructurallyEquivalent(Context, Name1.getCXXNameType(),
129 Name2.getCXXNameType());
131 case DeclarationName::CXXDeductionGuideName: {
132 if (!IsStructurallyEquivalent(
133 Context, Name1.getCXXDeductionGuideTemplate()->getDeclName(),
134 Name2.getCXXDeductionGuideTemplate()->getDeclName()))
136 return IsStructurallyEquivalent(Context,
137 Name1.getCXXDeductionGuideTemplate(),
138 Name2.getCXXDeductionGuideTemplate());
141 case DeclarationName::CXXOperatorName:
142 return Name1.getCXXOverloadedOperator() == Name2.getCXXOverloadedOperator();
144 case DeclarationName::CXXLiteralOperatorName:
145 return IsStructurallyEquivalent(Name1.getCXXLiteralIdentifier(),
146 Name2.getCXXLiteralIdentifier());
148 case DeclarationName::CXXUsingDirective:
149 return true; // FIXME When do we consider two using directives equal?
151 case DeclarationName::ObjCZeroArgSelector:
152 case DeclarationName::ObjCOneArgSelector:
153 case DeclarationName::ObjCMultiArgSelector:
154 return true; // FIXME
157 llvm_unreachable("Unhandled kind of DeclarationName");
162 /// Encapsulates Stmt comparison logic.
164 StructuralEquivalenceContext &Context;
166 // IsStmtEquivalent overloads. Each overload compares a specific statement
167 // and only has to compare the data that is specific to the specific statement
168 // class. Should only be called from TraverseStmt.
170 bool IsStmtEquivalent(const AddrLabelExpr *E1, const AddrLabelExpr *E2) {
171 return IsStructurallyEquivalent(Context, E1->getLabel(), E2->getLabel());
174 bool IsStmtEquivalent(const AtomicExpr *E1, const AtomicExpr *E2) {
175 return E1->getOp() == E2->getOp();
178 bool IsStmtEquivalent(const BinaryOperator *E1, const BinaryOperator *E2) {
179 return E1->getOpcode() == E2->getOpcode();
182 bool IsStmtEquivalent(const CallExpr *E1, const CallExpr *E2) {
183 // FIXME: IsStructurallyEquivalent requires non-const Decls.
184 Decl *Callee1 = const_cast<Decl *>(E1->getCalleeDecl());
185 Decl *Callee2 = const_cast<Decl *>(E2->getCalleeDecl());
187 // Compare whether both calls know their callee.
188 if (static_cast<bool>(Callee1) != static_cast<bool>(Callee2))
191 // Both calls have no callee, so nothing to do.
192 if (!static_cast<bool>(Callee1))
196 return IsStructurallyEquivalent(Context, Callee1, Callee2);
199 bool IsStmtEquivalent(const CharacterLiteral *E1,
200 const CharacterLiteral *E2) {
201 return E1->getValue() == E2->getValue() && E1->getKind() == E2->getKind();
204 bool IsStmtEquivalent(const ChooseExpr *E1, const ChooseExpr *E2) {
205 return true; // Semantics only depend on children.
208 bool IsStmtEquivalent(const CompoundStmt *E1, const CompoundStmt *E2) {
209 // Number of children is actually checked by the generic children comparison
210 // code, but a CompoundStmt is one of the few statements where the number of
211 // children frequently differs and the number of statements is also always
212 // precomputed. Directly comparing the number of children here is thus
213 // just an optimization.
214 return E1->size() == E2->size();
217 bool IsStmtEquivalent(const DependentScopeDeclRefExpr *DE1,
218 const DependentScopeDeclRefExpr *DE2) {
219 if (!IsStructurallyEquivalent(Context, DE1->getDeclName(),
222 return IsStructurallyEquivalent(Context, DE1->getQualifier(),
223 DE2->getQualifier());
226 bool IsStmtEquivalent(const Expr *E1, const Expr *E2) {
227 return IsStructurallyEquivalent(Context, E1->getType(), E2->getType());
230 bool IsStmtEquivalent(const ExpressionTraitExpr *E1,
231 const ExpressionTraitExpr *E2) {
232 return E1->getTrait() == E2->getTrait() && E1->getValue() == E2->getValue();
235 bool IsStmtEquivalent(const FloatingLiteral *E1, const FloatingLiteral *E2) {
236 return E1->isExact() == E2->isExact() && E1->getValue() == E2->getValue();
239 bool IsStmtEquivalent(const GenericSelectionExpr *E1,
240 const GenericSelectionExpr *E2) {
241 for (auto Pair : zip_longest(E1->getAssocTypeSourceInfos(),
242 E2->getAssocTypeSourceInfos())) {
243 std::optional<TypeSourceInfo *> Child1 = std::get<0>(Pair);
244 std::optional<TypeSourceInfo *> Child2 = std::get<1>(Pair);
245 // Skip this case if there are a different number of associated types.
246 if (!Child1 || !Child2)
249 if (!IsStructurallyEquivalent(Context, (*Child1)->getType(),
250 (*Child2)->getType()))
257 bool IsStmtEquivalent(const ImplicitCastExpr *CastE1,
258 const ImplicitCastExpr *CastE2) {
259 return IsStructurallyEquivalent(Context, CastE1->getType(),
263 bool IsStmtEquivalent(const IntegerLiteral *E1, const IntegerLiteral *E2) {
264 return E1->getValue() == E2->getValue();
267 bool IsStmtEquivalent(const MemberExpr *E1, const MemberExpr *E2) {
268 return IsStructurallyEquivalent(Context, E1->getFoundDecl(),
272 bool IsStmtEquivalent(const ObjCStringLiteral *E1,
273 const ObjCStringLiteral *E2) {
274 // Just wraps a StringLiteral child.
278 bool IsStmtEquivalent(const Stmt *S1, const Stmt *S2) { return true; }
280 bool IsStmtEquivalent(const SourceLocExpr *E1, const SourceLocExpr *E2) {
281 return E1->getIdentKind() == E2->getIdentKind();
284 bool IsStmtEquivalent(const StmtExpr *E1, const StmtExpr *E2) {
285 return E1->getTemplateDepth() == E2->getTemplateDepth();
288 bool IsStmtEquivalent(const StringLiteral *E1, const StringLiteral *E2) {
289 return E1->getBytes() == E2->getBytes();
292 bool IsStmtEquivalent(const SubstNonTypeTemplateParmExpr *E1,
293 const SubstNonTypeTemplateParmExpr *E2) {
294 if (!IsStructurallyEquivalent(Context, E1->getAssociatedDecl(),
295 E2->getAssociatedDecl()))
297 if (E1->getIndex() != E2->getIndex())
299 if (E1->getPackIndex() != E2->getPackIndex())
304 bool IsStmtEquivalent(const SubstNonTypeTemplateParmPackExpr *E1,
305 const SubstNonTypeTemplateParmPackExpr *E2) {
306 return IsStructurallyEquivalent(Context, E1->getArgumentPack(),
307 E2->getArgumentPack());
310 bool IsStmtEquivalent(const TypeTraitExpr *E1, const TypeTraitExpr *E2) {
311 if (E1->getTrait() != E2->getTrait())
314 for (auto Pair : zip_longest(E1->getArgs(), E2->getArgs())) {
315 std::optional<TypeSourceInfo *> Child1 = std::get<0>(Pair);
316 std::optional<TypeSourceInfo *> Child2 = std::get<1>(Pair);
317 // Different number of args.
318 if (!Child1 || !Child2)
321 if (!IsStructurallyEquivalent(Context, (*Child1)->getType(),
322 (*Child2)->getType()))
328 bool IsStmtEquivalent(const UnaryExprOrTypeTraitExpr *E1,
329 const UnaryExprOrTypeTraitExpr *E2) {
330 if (E1->getKind() != E2->getKind())
332 return IsStructurallyEquivalent(Context, E1->getTypeOfArgument(),
333 E2->getTypeOfArgument());
336 bool IsStmtEquivalent(const UnaryOperator *E1, const UnaryOperator *E2) {
337 return E1->getOpcode() == E2->getOpcode();
340 bool IsStmtEquivalent(const VAArgExpr *E1, const VAArgExpr *E2) {
341 // Semantics only depend on children.
345 bool IsStmtEquivalent(const OverloadExpr *E1, const OverloadExpr *E2) {
346 if (!IsStructurallyEquivalent(Context, E1->getName(), E2->getName()))
349 if (static_cast<bool>(E1->getQualifier()) !=
350 static_cast<bool>(E2->getQualifier()))
352 if (E1->getQualifier() &&
353 !IsStructurallyEquivalent(Context, E1->getQualifier(),
357 if (E1->getNumTemplateArgs() != E2->getNumTemplateArgs())
359 const TemplateArgumentLoc *Args1 = E1->getTemplateArgs();
360 const TemplateArgumentLoc *Args2 = E2->getTemplateArgs();
361 for (unsigned int ArgI = 0, ArgN = E1->getNumTemplateArgs(); ArgI < ArgN;
363 if (!IsStructurallyEquivalent(Context, Args1[ArgI], Args2[ArgI]))
369 /// End point of the traversal chain.
370 bool TraverseStmt(const Stmt *S1, const Stmt *S2) { return true; }
372 // Create traversal methods that traverse the class hierarchy and return
373 // the accumulated result of the comparison. Each TraverseStmt overload
374 // calls the TraverseStmt overload of the parent class. For example,
375 // the TraverseStmt overload for 'BinaryOperator' calls the TraverseStmt
376 // overload of 'Expr' which then calls the overload for 'Stmt'.
377 #define STMT(CLASS, PARENT) \
378 bool TraverseStmt(const CLASS *S1, const CLASS *S2) { \
379 if (!TraverseStmt(static_cast<const PARENT *>(S1), \
380 static_cast<const PARENT *>(S2))) \
382 return IsStmtEquivalent(S1, S2); \
384 #include "clang/AST/StmtNodes.inc"
387 StmtComparer(StructuralEquivalenceContext &C) : Context(C) {}
389 /// Determine whether two statements are equivalent. The statements have to
390 /// be of the same kind. The children of the statements and their properties
391 /// are not compared by this function.
392 bool IsEquivalent(const Stmt *S1, const Stmt *S2) {
393 if (S1->getStmtClass() != S2->getStmtClass())
396 // Each TraverseStmt walks the class hierarchy from the leaf class to
397 // the root class 'Stmt' (e.g. 'BinaryOperator' -> 'Expr' -> 'Stmt'). Cast
398 // the Stmt we have here to its specific subclass so that we call the
399 // overload that walks the whole class hierarchy from leaf to root (e.g.,
400 // cast to 'BinaryOperator' so that 'Expr' and 'Stmt' is traversed).
401 switch (S1->getStmtClass()) {
402 case Stmt::NoStmtClass:
403 llvm_unreachable("Can't traverse NoStmtClass");
404 #define STMT(CLASS, PARENT) \
405 case Stmt::StmtClass::CLASS##Class: \
406 return TraverseStmt(static_cast<const CLASS *>(S1), \
407 static_cast<const CLASS *>(S2));
408 #define ABSTRACT_STMT(S)
409 #include "clang/AST/StmtNodes.inc"
411 llvm_unreachable("Invalid statement kind");
416 /// Determine structural equivalence of two statements.
417 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
418 const Stmt *S1, const Stmt *S2) {
422 // Compare the statements itself.
423 StmtComparer Comparer(Context);
424 if (!Comparer.IsEquivalent(S1, S2))
427 // Iterate over the children of both statements and also compare them.
428 for (auto Pair : zip_longest(S1->children(), S2->children())) {
429 std::optional<const Stmt *> Child1 = std::get<0>(Pair);
430 std::optional<const Stmt *> Child2 = std::get<1>(Pair);
431 // One of the statements has a different amount of children than the other,
432 // so the statements can't be equivalent.
433 if (!Child1 || !Child2)
435 if (!IsStructurallyEquivalent(Context, *Child1, *Child2))
441 /// Determine whether two identifiers are equivalent.
442 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
443 const IdentifierInfo *Name2) {
444 if (!Name1 || !Name2)
445 return Name1 == Name2;
447 return Name1->getName() == Name2->getName();
450 /// Determine whether two nested-name-specifiers are equivalent.
451 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
452 NestedNameSpecifier *NNS1,
453 NestedNameSpecifier *NNS2) {
454 if (NNS1->getKind() != NNS2->getKind())
457 NestedNameSpecifier *Prefix1 = NNS1->getPrefix(),
458 *Prefix2 = NNS2->getPrefix();
459 if ((bool)Prefix1 != (bool)Prefix2)
463 if (!IsStructurallyEquivalent(Context, Prefix1, Prefix2))
466 switch (NNS1->getKind()) {
467 case NestedNameSpecifier::Identifier:
468 return IsStructurallyEquivalent(NNS1->getAsIdentifier(),
469 NNS2->getAsIdentifier());
470 case NestedNameSpecifier::Namespace:
471 return IsStructurallyEquivalent(Context, NNS1->getAsNamespace(),
472 NNS2->getAsNamespace());
473 case NestedNameSpecifier::NamespaceAlias:
474 return IsStructurallyEquivalent(Context, NNS1->getAsNamespaceAlias(),
475 NNS2->getAsNamespaceAlias());
476 case NestedNameSpecifier::TypeSpec:
477 case NestedNameSpecifier::TypeSpecWithTemplate:
478 return IsStructurallyEquivalent(Context, QualType(NNS1->getAsType(), 0),
479 QualType(NNS2->getAsType(), 0));
480 case NestedNameSpecifier::Global:
482 case NestedNameSpecifier::Super:
483 return IsStructurallyEquivalent(Context, NNS1->getAsRecordDecl(),
484 NNS2->getAsRecordDecl());
489 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
490 const TemplateName &N1,
491 const TemplateName &N2) {
492 TemplateDecl *TemplateDeclN1 = N1.getAsTemplateDecl();
493 TemplateDecl *TemplateDeclN2 = N2.getAsTemplateDecl();
494 if (TemplateDeclN1 && TemplateDeclN2) {
495 if (!IsStructurallyEquivalent(Context, TemplateDeclN1, TemplateDeclN2))
497 // If the kind is different we compare only the template decl.
498 if (N1.getKind() != N2.getKind())
500 } else if (TemplateDeclN1 || TemplateDeclN2)
502 else if (N1.getKind() != N2.getKind())
505 // Check for special case incompatibilities.
506 switch (N1.getKind()) {
508 case TemplateName::OverloadedTemplate: {
509 OverloadedTemplateStorage *OS1 = N1.getAsOverloadedTemplate(),
510 *OS2 = N2.getAsOverloadedTemplate();
511 OverloadedTemplateStorage::iterator I1 = OS1->begin(), I2 = OS2->begin(),
512 E1 = OS1->end(), E2 = OS2->end();
513 for (; I1 != E1 && I2 != E2; ++I1, ++I2)
514 if (!IsStructurallyEquivalent(Context, *I1, *I2))
516 return I1 == E1 && I2 == E2;
519 case TemplateName::AssumedTemplate: {
520 AssumedTemplateStorage *TN1 = N1.getAsAssumedTemplateName(),
521 *TN2 = N1.getAsAssumedTemplateName();
522 return TN1->getDeclName() == TN2->getDeclName();
525 case TemplateName::DependentTemplate: {
526 DependentTemplateName *DN1 = N1.getAsDependentTemplateName(),
527 *DN2 = N2.getAsDependentTemplateName();
528 if (!IsStructurallyEquivalent(Context, DN1->getQualifier(),
529 DN2->getQualifier()))
531 if (DN1->isIdentifier() && DN2->isIdentifier())
532 return IsStructurallyEquivalent(DN1->getIdentifier(),
533 DN2->getIdentifier());
534 else if (DN1->isOverloadedOperator() && DN2->isOverloadedOperator())
535 return DN1->getOperator() == DN2->getOperator();
539 case TemplateName::SubstTemplateTemplateParmPack: {
540 SubstTemplateTemplateParmPackStorage
541 *P1 = N1.getAsSubstTemplateTemplateParmPack(),
542 *P2 = N2.getAsSubstTemplateTemplateParmPack();
543 return IsStructurallyEquivalent(Context, P1->getArgumentPack(),
544 P2->getArgumentPack()) &&
545 IsStructurallyEquivalent(Context, P1->getAssociatedDecl(),
546 P2->getAssociatedDecl()) &&
547 P1->getIndex() == P2->getIndex();
550 case TemplateName::Template:
551 case TemplateName::QualifiedTemplate:
552 case TemplateName::SubstTemplateTemplateParm:
553 case TemplateName::UsingTemplate:
554 // It is sufficient to check value of getAsTemplateDecl.
562 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
563 ArrayRef<TemplateArgument> Args1,
564 ArrayRef<TemplateArgument> Args2);
566 /// Determine whether two template arguments are equivalent.
567 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
568 const TemplateArgument &Arg1,
569 const TemplateArgument &Arg2) {
570 if (Arg1.getKind() != Arg2.getKind())
573 switch (Arg1.getKind()) {
574 case TemplateArgument::Null:
577 case TemplateArgument::Type:
578 return IsStructurallyEquivalent(Context, Arg1.getAsType(), Arg2.getAsType());
580 case TemplateArgument::Integral:
581 if (!IsStructurallyEquivalent(Context, Arg1.getIntegralType(),
582 Arg2.getIntegralType()))
585 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
586 Arg2.getAsIntegral());
588 case TemplateArgument::Declaration:
589 return IsStructurallyEquivalent(Context, Arg1.getAsDecl(), Arg2.getAsDecl());
591 case TemplateArgument::NullPtr:
592 return true; // FIXME: Is this correct?
594 case TemplateArgument::Template:
595 return IsStructurallyEquivalent(Context, Arg1.getAsTemplate(),
596 Arg2.getAsTemplate());
598 case TemplateArgument::TemplateExpansion:
599 return IsStructurallyEquivalent(Context,
600 Arg1.getAsTemplateOrTemplatePattern(),
601 Arg2.getAsTemplateOrTemplatePattern());
603 case TemplateArgument::Expression:
604 return IsStructurallyEquivalent(Context, Arg1.getAsExpr(),
607 case TemplateArgument::Pack:
608 return IsStructurallyEquivalent(Context, Arg1.pack_elements(),
609 Arg2.pack_elements());
612 llvm_unreachable("Invalid template argument kind");
615 /// Determine structural equivalence of two template argument lists.
616 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
617 ArrayRef<TemplateArgument> Args1,
618 ArrayRef<TemplateArgument> Args2) {
619 if (Args1.size() != Args2.size())
621 for (unsigned I = 0, N = Args1.size(); I != N; ++I) {
622 if (!IsStructurallyEquivalent(Context, Args1[I], Args2[I]))
628 /// Determine whether two template argument locations are equivalent.
629 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
630 const TemplateArgumentLoc &Arg1,
631 const TemplateArgumentLoc &Arg2) {
632 return IsStructurallyEquivalent(Context, Arg1.getArgument(),
636 /// Determine structural equivalence for the common part of array
638 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
639 const ArrayType *Array1,
640 const ArrayType *Array2) {
641 if (!IsStructurallyEquivalent(Context, Array1->getElementType(),
642 Array2->getElementType()))
644 if (Array1->getSizeModifier() != Array2->getSizeModifier())
646 if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
652 /// Determine structural equivalence based on the ExtInfo of functions. This
653 /// is inspired by ASTContext::mergeFunctionTypes(), we compare calling
654 /// conventions bits but must not compare some other bits.
655 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
656 FunctionType::ExtInfo EI1,
657 FunctionType::ExtInfo EI2) {
658 // Compatible functions must have compatible calling conventions.
659 if (EI1.getCC() != EI2.getCC())
662 // Regparm is part of the calling convention.
663 if (EI1.getHasRegParm() != EI2.getHasRegParm())
665 if (EI1.getRegParm() != EI2.getRegParm())
668 if (EI1.getProducesResult() != EI2.getProducesResult())
670 if (EI1.getNoCallerSavedRegs() != EI2.getNoCallerSavedRegs())
672 if (EI1.getNoCfCheck() != EI2.getNoCfCheck())
678 /// Check the equivalence of exception specifications.
679 static bool IsEquivalentExceptionSpec(StructuralEquivalenceContext &Context,
680 const FunctionProtoType *Proto1,
681 const FunctionProtoType *Proto2) {
683 auto Spec1 = Proto1->getExceptionSpecType();
684 auto Spec2 = Proto2->getExceptionSpecType();
686 if (isUnresolvedExceptionSpec(Spec1) || isUnresolvedExceptionSpec(Spec2))
691 if (Spec1 == EST_Dynamic) {
692 if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
694 for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
695 if (!IsStructurallyEquivalent(Context, Proto1->getExceptionType(I),
696 Proto2->getExceptionType(I)))
699 } else if (isComputedNoexcept(Spec1)) {
700 if (!IsStructurallyEquivalent(Context, Proto1->getNoexceptExpr(),
701 Proto2->getNoexceptExpr()))
708 /// Determine structural equivalence of two types.
709 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
710 QualType T1, QualType T2) {
711 if (T1.isNull() || T2.isNull())
712 return T1.isNull() && T2.isNull();
714 QualType OrigT1 = T1;
715 QualType OrigT2 = T2;
717 if (!Context.StrictTypeSpelling) {
718 // We aren't being strict about token-to-token equivalence of types,
719 // so map down to the canonical type.
720 T1 = Context.FromCtx.getCanonicalType(T1);
721 T2 = Context.ToCtx.getCanonicalType(T2);
724 if (T1.getQualifiers() != T2.getQualifiers())
727 Type::TypeClass TC = T1->getTypeClass();
729 if (T1->getTypeClass() != T2->getTypeClass()) {
730 // Compare function types with prototypes vs. without prototypes as if
731 // both did not have prototypes.
732 if (T1->getTypeClass() == Type::FunctionProto &&
733 T2->getTypeClass() == Type::FunctionNoProto)
734 TC = Type::FunctionNoProto;
735 else if (T1->getTypeClass() == Type::FunctionNoProto &&
736 T2->getTypeClass() == Type::FunctionProto)
737 TC = Type::FunctionNoProto;
744 // FIXME: Deal with Char_S/Char_U.
745 if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
750 if (!IsStructurallyEquivalent(Context,
751 cast<ComplexType>(T1)->getElementType(),
752 cast<ComplexType>(T2)->getElementType()))
758 if (!IsStructurallyEquivalent(Context,
759 cast<AdjustedType>(T1)->getOriginalType(),
760 cast<AdjustedType>(T2)->getOriginalType()))
765 if (!IsStructurallyEquivalent(Context,
766 cast<PointerType>(T1)->getPointeeType(),
767 cast<PointerType>(T2)->getPointeeType()))
771 case Type::BlockPointer:
772 if (!IsStructurallyEquivalent(Context,
773 cast<BlockPointerType>(T1)->getPointeeType(),
774 cast<BlockPointerType>(T2)->getPointeeType()))
778 case Type::LValueReference:
779 case Type::RValueReference: {
780 const auto *Ref1 = cast<ReferenceType>(T1);
781 const auto *Ref2 = cast<ReferenceType>(T2);
782 if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
784 if (Ref1->isInnerRef() != Ref2->isInnerRef())
786 if (!IsStructurallyEquivalent(Context, Ref1->getPointeeTypeAsWritten(),
787 Ref2->getPointeeTypeAsWritten()))
792 case Type::MemberPointer: {
793 const auto *MemPtr1 = cast<MemberPointerType>(T1);
794 const auto *MemPtr2 = cast<MemberPointerType>(T2);
795 if (!IsStructurallyEquivalent(Context, MemPtr1->getPointeeType(),
796 MemPtr2->getPointeeType()))
798 if (!IsStructurallyEquivalent(Context, QualType(MemPtr1->getClass(), 0),
799 QualType(MemPtr2->getClass(), 0)))
804 case Type::ConstantArray: {
805 const auto *Array1 = cast<ConstantArrayType>(T1);
806 const auto *Array2 = cast<ConstantArrayType>(T2);
807 if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize()))
810 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
815 case Type::IncompleteArray:
816 if (!IsArrayStructurallyEquivalent(Context, cast<ArrayType>(T1),
817 cast<ArrayType>(T2)))
821 case Type::VariableArray: {
822 const auto *Array1 = cast<VariableArrayType>(T1);
823 const auto *Array2 = cast<VariableArrayType>(T2);
824 if (!IsStructurallyEquivalent(Context, Array1->getSizeExpr(),
825 Array2->getSizeExpr()))
828 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
834 case Type::DependentSizedArray: {
835 const auto *Array1 = cast<DependentSizedArrayType>(T1);
836 const auto *Array2 = cast<DependentSizedArrayType>(T2);
837 if (!IsStructurallyEquivalent(Context, Array1->getSizeExpr(),
838 Array2->getSizeExpr()))
841 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
847 case Type::DependentAddressSpace: {
848 const auto *DepAddressSpace1 = cast<DependentAddressSpaceType>(T1);
849 const auto *DepAddressSpace2 = cast<DependentAddressSpaceType>(T2);
850 if (!IsStructurallyEquivalent(Context, DepAddressSpace1->getAddrSpaceExpr(),
851 DepAddressSpace2->getAddrSpaceExpr()))
853 if (!IsStructurallyEquivalent(Context, DepAddressSpace1->getPointeeType(),
854 DepAddressSpace2->getPointeeType()))
860 case Type::DependentSizedExtVector: {
861 const auto *Vec1 = cast<DependentSizedExtVectorType>(T1);
862 const auto *Vec2 = cast<DependentSizedExtVectorType>(T2);
863 if (!IsStructurallyEquivalent(Context, Vec1->getSizeExpr(),
864 Vec2->getSizeExpr()))
866 if (!IsStructurallyEquivalent(Context, Vec1->getElementType(),
867 Vec2->getElementType()))
872 case Type::DependentVector: {
873 const auto *Vec1 = cast<DependentVectorType>(T1);
874 const auto *Vec2 = cast<DependentVectorType>(T2);
875 if (Vec1->getVectorKind() != Vec2->getVectorKind())
877 if (!IsStructurallyEquivalent(Context, Vec1->getSizeExpr(),
878 Vec2->getSizeExpr()))
880 if (!IsStructurallyEquivalent(Context, Vec1->getElementType(),
881 Vec2->getElementType()))
887 case Type::ExtVector: {
888 const auto *Vec1 = cast<VectorType>(T1);
889 const auto *Vec2 = cast<VectorType>(T2);
890 if (!IsStructurallyEquivalent(Context, Vec1->getElementType(),
891 Vec2->getElementType()))
893 if (Vec1->getNumElements() != Vec2->getNumElements())
895 if (Vec1->getVectorKind() != Vec2->getVectorKind())
900 case Type::DependentSizedMatrix: {
901 const DependentSizedMatrixType *Mat1 = cast<DependentSizedMatrixType>(T1);
902 const DependentSizedMatrixType *Mat2 = cast<DependentSizedMatrixType>(T2);
903 // The element types, row and column expressions must be structurally
905 if (!IsStructurallyEquivalent(Context, Mat1->getRowExpr(),
906 Mat2->getRowExpr()) ||
907 !IsStructurallyEquivalent(Context, Mat1->getColumnExpr(),
908 Mat2->getColumnExpr()) ||
909 !IsStructurallyEquivalent(Context, Mat1->getElementType(),
910 Mat2->getElementType()))
915 case Type::ConstantMatrix: {
916 const ConstantMatrixType *Mat1 = cast<ConstantMatrixType>(T1);
917 const ConstantMatrixType *Mat2 = cast<ConstantMatrixType>(T2);
918 // The element types must be structurally equivalent and the number of rows
919 // and columns must match.
920 if (!IsStructurallyEquivalent(Context, Mat1->getElementType(),
921 Mat2->getElementType()) ||
922 Mat1->getNumRows() != Mat2->getNumRows() ||
923 Mat1->getNumColumns() != Mat2->getNumColumns())
928 case Type::FunctionProto: {
929 const auto *Proto1 = cast<FunctionProtoType>(T1);
930 const auto *Proto2 = cast<FunctionProtoType>(T2);
932 if (Proto1->getNumParams() != Proto2->getNumParams())
934 for (unsigned I = 0, N = Proto1->getNumParams(); I != N; ++I) {
935 if (!IsStructurallyEquivalent(Context, Proto1->getParamType(I),
936 Proto2->getParamType(I)))
939 if (Proto1->isVariadic() != Proto2->isVariadic())
942 if (Proto1->getMethodQuals() != Proto2->getMethodQuals())
945 // Check exceptions, this information is lost in canonical type.
946 const auto *OrigProto1 =
947 cast<FunctionProtoType>(OrigT1.getDesugaredType(Context.FromCtx));
948 const auto *OrigProto2 =
949 cast<FunctionProtoType>(OrigT2.getDesugaredType(Context.ToCtx));
950 if (!IsEquivalentExceptionSpec(Context, OrigProto1, OrigProto2))
953 // Fall through to check the bits common with FunctionNoProtoType.
957 case Type::FunctionNoProto: {
958 const auto *Function1 = cast<FunctionType>(T1);
959 const auto *Function2 = cast<FunctionType>(T2);
960 if (!IsStructurallyEquivalent(Context, Function1->getReturnType(),
961 Function2->getReturnType()))
963 if (!IsStructurallyEquivalent(Context, Function1->getExtInfo(),
964 Function2->getExtInfo()))
969 case Type::UnresolvedUsing:
970 if (!IsStructurallyEquivalent(Context,
971 cast<UnresolvedUsingType>(T1)->getDecl(),
972 cast<UnresolvedUsingType>(T2)->getDecl()))
976 case Type::Attributed:
977 if (!IsStructurallyEquivalent(Context,
978 cast<AttributedType>(T1)->getModifiedType(),
979 cast<AttributedType>(T2)->getModifiedType()))
981 if (!IsStructurallyEquivalent(
982 Context, cast<AttributedType>(T1)->getEquivalentType(),
983 cast<AttributedType>(T2)->getEquivalentType()))
987 case Type::BTFTagAttributed:
988 if (!IsStructurallyEquivalent(
989 Context, cast<BTFTagAttributedType>(T1)->getWrappedType(),
990 cast<BTFTagAttributedType>(T2)->getWrappedType()))
995 if (!IsStructurallyEquivalent(Context, cast<ParenType>(T1)->getInnerType(),
996 cast<ParenType>(T2)->getInnerType()))
1000 case Type::MacroQualified:
1001 if (!IsStructurallyEquivalent(
1002 Context, cast<MacroQualifiedType>(T1)->getUnderlyingType(),
1003 cast<MacroQualifiedType>(T2)->getUnderlyingType()))
1008 if (!IsStructurallyEquivalent(Context, cast<UsingType>(T1)->getFoundDecl(),
1009 cast<UsingType>(T2)->getFoundDecl()))
1011 if (!IsStructurallyEquivalent(Context,
1012 cast<UsingType>(T1)->getUnderlyingType(),
1013 cast<UsingType>(T2)->getUnderlyingType()))
1018 if (!IsStructurallyEquivalent(Context, cast<TypedefType>(T1)->getDecl(),
1019 cast<TypedefType>(T2)->getDecl()) ||
1020 !IsStructurallyEquivalent(Context, cast<TypedefType>(T1)->desugar(),
1021 cast<TypedefType>(T2)->desugar()))
1025 case Type::TypeOfExpr:
1026 if (!IsStructurallyEquivalent(
1027 Context, cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
1028 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
1033 if (!IsStructurallyEquivalent(Context,
1034 cast<TypeOfType>(T1)->getUnmodifiedType(),
1035 cast<TypeOfType>(T2)->getUnmodifiedType()))
1039 case Type::UnaryTransform:
1040 if (!IsStructurallyEquivalent(
1041 Context, cast<UnaryTransformType>(T1)->getUnderlyingType(),
1042 cast<UnaryTransformType>(T2)->getUnderlyingType()))
1046 case Type::Decltype:
1047 if (!IsStructurallyEquivalent(Context,
1048 cast<DecltypeType>(T1)->getUnderlyingExpr(),
1049 cast<DecltypeType>(T2)->getUnderlyingExpr()))
1054 auto *Auto1 = cast<AutoType>(T1);
1055 auto *Auto2 = cast<AutoType>(T2);
1056 if (!IsStructurallyEquivalent(Context, Auto1->getDeducedType(),
1057 Auto2->getDeducedType()))
1059 if (Auto1->isConstrained() != Auto2->isConstrained())
1061 if (Auto1->isConstrained()) {
1062 if (Auto1->getTypeConstraintConcept() !=
1063 Auto2->getTypeConstraintConcept())
1065 if (!IsStructurallyEquivalent(Context,
1066 Auto1->getTypeConstraintArguments(),
1067 Auto2->getTypeConstraintArguments()))
1073 case Type::DeducedTemplateSpecialization: {
1074 const auto *DT1 = cast<DeducedTemplateSpecializationType>(T1);
1075 const auto *DT2 = cast<DeducedTemplateSpecializationType>(T2);
1076 if (!IsStructurallyEquivalent(Context, DT1->getTemplateName(),
1077 DT2->getTemplateName()))
1079 if (!IsStructurallyEquivalent(Context, DT1->getDeducedType(),
1080 DT2->getDeducedType()))
1087 if (!IsStructurallyEquivalent(Context, cast<TagType>(T1)->getDecl(),
1088 cast<TagType>(T2)->getDecl()))
1092 case Type::TemplateTypeParm: {
1093 const auto *Parm1 = cast<TemplateTypeParmType>(T1);
1094 const auto *Parm2 = cast<TemplateTypeParmType>(T2);
1095 if (Parm1->getDepth() != Parm2->getDepth())
1097 if (Parm1->getIndex() != Parm2->getIndex())
1099 if (Parm1->isParameterPack() != Parm2->isParameterPack())
1102 // Names of template type parameters are never significant.
1106 case Type::SubstTemplateTypeParm: {
1107 const auto *Subst1 = cast<SubstTemplateTypeParmType>(T1);
1108 const auto *Subst2 = cast<SubstTemplateTypeParmType>(T2);
1109 if (!IsStructurallyEquivalent(Context, Subst1->getReplacementType(),
1110 Subst2->getReplacementType()))
1112 if (!IsStructurallyEquivalent(Context, Subst1->getAssociatedDecl(),
1113 Subst2->getAssociatedDecl()))
1115 if (Subst1->getIndex() != Subst2->getIndex())
1117 if (Subst1->getPackIndex() != Subst2->getPackIndex())
1122 case Type::SubstTemplateTypeParmPack: {
1123 const auto *Subst1 = cast<SubstTemplateTypeParmPackType>(T1);
1124 const auto *Subst2 = cast<SubstTemplateTypeParmPackType>(T2);
1125 if (!IsStructurallyEquivalent(Context, Subst1->getAssociatedDecl(),
1126 Subst2->getAssociatedDecl()))
1128 if (Subst1->getIndex() != Subst2->getIndex())
1130 if (!IsStructurallyEquivalent(Context, Subst1->getArgumentPack(),
1131 Subst2->getArgumentPack()))
1136 case Type::TemplateSpecialization: {
1137 const auto *Spec1 = cast<TemplateSpecializationType>(T1);
1138 const auto *Spec2 = cast<TemplateSpecializationType>(T2);
1139 if (!IsStructurallyEquivalent(Context, Spec1->getTemplateName(),
1140 Spec2->getTemplateName()))
1142 if (!IsStructurallyEquivalent(Context, Spec1->template_arguments(),
1143 Spec2->template_arguments()))
1148 case Type::Elaborated: {
1149 const auto *Elab1 = cast<ElaboratedType>(T1);
1150 const auto *Elab2 = cast<ElaboratedType>(T2);
1151 // CHECKME: what if a keyword is ETK_None or ETK_typename ?
1152 if (Elab1->getKeyword() != Elab2->getKeyword())
1154 if (!IsStructurallyEquivalent(Context, Elab1->getQualifier(),
1155 Elab2->getQualifier()))
1157 if (!IsStructurallyEquivalent(Context, Elab1->getNamedType(),
1158 Elab2->getNamedType()))
1163 case Type::InjectedClassName: {
1164 const auto *Inj1 = cast<InjectedClassNameType>(T1);
1165 const auto *Inj2 = cast<InjectedClassNameType>(T2);
1166 if (!IsStructurallyEquivalent(Context,
1167 Inj1->getInjectedSpecializationType(),
1168 Inj2->getInjectedSpecializationType()))
1173 case Type::DependentName: {
1174 const auto *Typename1 = cast<DependentNameType>(T1);
1175 const auto *Typename2 = cast<DependentNameType>(T2);
1176 if (!IsStructurallyEquivalent(Context, Typename1->getQualifier(),
1177 Typename2->getQualifier()))
1179 if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
1180 Typename2->getIdentifier()))
1186 case Type::DependentTemplateSpecialization: {
1187 const auto *Spec1 = cast<DependentTemplateSpecializationType>(T1);
1188 const auto *Spec2 = cast<DependentTemplateSpecializationType>(T2);
1189 if (!IsStructurallyEquivalent(Context, Spec1->getQualifier(),
1190 Spec2->getQualifier()))
1192 if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
1193 Spec2->getIdentifier()))
1195 if (!IsStructurallyEquivalent(Context, Spec1->template_arguments(),
1196 Spec2->template_arguments()))
1201 case Type::PackExpansion:
1202 if (!IsStructurallyEquivalent(Context,
1203 cast<PackExpansionType>(T1)->getPattern(),
1204 cast<PackExpansionType>(T2)->getPattern()))
1208 case Type::ObjCInterface: {
1209 const auto *Iface1 = cast<ObjCInterfaceType>(T1);
1210 const auto *Iface2 = cast<ObjCInterfaceType>(T2);
1211 if (!IsStructurallyEquivalent(Context, Iface1->getDecl(),
1217 case Type::ObjCTypeParam: {
1218 const auto *Obj1 = cast<ObjCTypeParamType>(T1);
1219 const auto *Obj2 = cast<ObjCTypeParamType>(T2);
1220 if (!IsStructurallyEquivalent(Context, Obj1->getDecl(), Obj2->getDecl()))
1223 if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
1225 for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
1226 if (!IsStructurallyEquivalent(Context, Obj1->getProtocol(I),
1227 Obj2->getProtocol(I)))
1233 case Type::ObjCObject: {
1234 const auto *Obj1 = cast<ObjCObjectType>(T1);
1235 const auto *Obj2 = cast<ObjCObjectType>(T2);
1236 if (!IsStructurallyEquivalent(Context, Obj1->getBaseType(),
1237 Obj2->getBaseType()))
1239 if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
1241 for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
1242 if (!IsStructurallyEquivalent(Context, Obj1->getProtocol(I),
1243 Obj2->getProtocol(I)))
1249 case Type::ObjCObjectPointer: {
1250 const auto *Ptr1 = cast<ObjCObjectPointerType>(T1);
1251 const auto *Ptr2 = cast<ObjCObjectPointerType>(T2);
1252 if (!IsStructurallyEquivalent(Context, Ptr1->getPointeeType(),
1253 Ptr2->getPointeeType()))
1259 if (!IsStructurallyEquivalent(Context, cast<AtomicType>(T1)->getValueType(),
1260 cast<AtomicType>(T2)->getValueType()))
1265 if (!IsStructurallyEquivalent(Context, cast<PipeType>(T1)->getElementType(),
1266 cast<PipeType>(T2)->getElementType()))
1269 case Type::BitInt: {
1270 const auto *Int1 = cast<BitIntType>(T1);
1271 const auto *Int2 = cast<BitIntType>(T2);
1273 if (Int1->isUnsigned() != Int2->isUnsigned() ||
1274 Int1->getNumBits() != Int2->getNumBits())
1278 case Type::DependentBitInt: {
1279 const auto *Int1 = cast<DependentBitIntType>(T1);
1280 const auto *Int2 = cast<DependentBitIntType>(T2);
1282 if (Int1->isUnsigned() != Int2->isUnsigned() ||
1283 !IsStructurallyEquivalent(Context, Int1->getNumBitsExpr(),
1284 Int2->getNumBitsExpr()))
1293 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1294 FieldDecl *Field1, FieldDecl *Field2,
1295 QualType Owner2Type) {
1296 const auto *Owner2 = cast<Decl>(Field2->getDeclContext());
1298 // For anonymous structs/unions, match up the anonymous struct/union type
1299 // declarations directly, so that we don't go off searching for anonymous
1301 if (Field1->isAnonymousStructOrUnion() &&
1302 Field2->isAnonymousStructOrUnion()) {
1303 RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl();
1304 RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl();
1305 return IsStructurallyEquivalent(Context, D1, D2);
1308 // Check for equivalent field names.
1309 IdentifierInfo *Name1 = Field1->getIdentifier();
1310 IdentifierInfo *Name2 = Field2->getIdentifier();
1311 if (!::IsStructurallyEquivalent(Name1, Name2)) {
1312 if (Context.Complain) {
1314 Owner2->getLocation(),
1315 Context.getApplicableDiagnostic(diag::err_odr_tag_type_inconsistent))
1317 Context.Diag2(Field2->getLocation(), diag::note_odr_field_name)
1318 << Field2->getDeclName();
1319 Context.Diag1(Field1->getLocation(), diag::note_odr_field_name)
1320 << Field1->getDeclName();
1325 if (!IsStructurallyEquivalent(Context, Field1->getType(),
1326 Field2->getType())) {
1327 if (Context.Complain) {
1329 Owner2->getLocation(),
1330 Context.getApplicableDiagnostic(diag::err_odr_tag_type_inconsistent))
1332 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1333 << Field2->getDeclName() << Field2->getType();
1334 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1335 << Field1->getDeclName() << Field1->getType();
1340 if (Field1->isBitField())
1341 return IsStructurallyEquivalent(Context, Field1->getBitWidth(),
1342 Field2->getBitWidth());
1347 /// Determine structural equivalence of two fields.
1348 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1349 FieldDecl *Field1, FieldDecl *Field2) {
1350 const auto *Owner2 = cast<RecordDecl>(Field2->getDeclContext());
1351 return IsStructurallyEquivalent(Context, Field1, Field2,
1352 Context.ToCtx.getTypeDeclType(Owner2));
1355 /// Determine structural equivalence of two methods.
1356 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1357 CXXMethodDecl *Method1,
1358 CXXMethodDecl *Method2) {
1359 bool PropertiesEqual =
1360 Method1->getDeclKind() == Method2->getDeclKind() &&
1361 Method1->getRefQualifier() == Method2->getRefQualifier() &&
1362 Method1->getAccess() == Method2->getAccess() &&
1363 Method1->getOverloadedOperator() == Method2->getOverloadedOperator() &&
1364 Method1->isStatic() == Method2->isStatic() &&
1365 Method1->isConst() == Method2->isConst() &&
1366 Method1->isVolatile() == Method2->isVolatile() &&
1367 Method1->isVirtual() == Method2->isVirtual() &&
1368 Method1->isPure() == Method2->isPure() &&
1369 Method1->isDefaulted() == Method2->isDefaulted() &&
1370 Method1->isDeleted() == Method2->isDeleted();
1371 if (!PropertiesEqual)
1373 // FIXME: Check for 'final'.
1375 if (auto *Constructor1 = dyn_cast<CXXConstructorDecl>(Method1)) {
1376 auto *Constructor2 = cast<CXXConstructorDecl>(Method2);
1377 if (!Constructor1->getExplicitSpecifier().isEquivalent(
1378 Constructor2->getExplicitSpecifier()))
1382 if (auto *Conversion1 = dyn_cast<CXXConversionDecl>(Method1)) {
1383 auto *Conversion2 = cast<CXXConversionDecl>(Method2);
1384 if (!Conversion1->getExplicitSpecifier().isEquivalent(
1385 Conversion2->getExplicitSpecifier()))
1387 if (!IsStructurallyEquivalent(Context, Conversion1->getConversionType(),
1388 Conversion2->getConversionType()))
1392 const IdentifierInfo *Name1 = Method1->getIdentifier();
1393 const IdentifierInfo *Name2 = Method2->getIdentifier();
1394 if (!::IsStructurallyEquivalent(Name1, Name2)) {
1396 // TODO: Names do not match, add warning like at check for FieldDecl.
1399 // Check the prototypes.
1400 if (!::IsStructurallyEquivalent(Context,
1401 Method1->getType(), Method2->getType()))
1407 /// Determine structural equivalence of two lambda classes.
1409 IsStructurallyEquivalentLambdas(StructuralEquivalenceContext &Context,
1410 CXXRecordDecl *D1, CXXRecordDecl *D2) {
1411 assert(D1->isLambda() && D2->isLambda() &&
1412 "Must be called on lambda classes");
1413 if (!IsStructurallyEquivalent(Context, D1->getLambdaCallOperator(),
1414 D2->getLambdaCallOperator()))
1420 /// Determine if context of a class is equivalent.
1421 static bool IsRecordContextStructurallyEquivalent(RecordDecl *D1,
1423 // The context should be completely equal, including anonymous and inline
1425 // We compare objects as part of full translation units, not subtrees of
1426 // translation units.
1427 DeclContext *DC1 = D1->getDeclContext()->getNonTransparentContext();
1428 DeclContext *DC2 = D2->getDeclContext()->getNonTransparentContext();
1430 // Special case: We allow a struct defined in a function to be equivalent
1431 // with a similar struct defined outside of a function.
1432 if ((DC1->isFunctionOrMethod() && DC2->isTranslationUnit()) ||
1433 (DC2->isFunctionOrMethod() && DC1->isTranslationUnit()))
1436 if (DC1->getDeclKind() != DC2->getDeclKind())
1438 if (DC1->isTranslationUnit())
1440 if (DC1->isInlineNamespace() != DC2->isInlineNamespace())
1442 if (const auto *ND1 = dyn_cast<NamedDecl>(DC1)) {
1443 const auto *ND2 = cast<NamedDecl>(DC2);
1444 if (!DC1->isInlineNamespace() &&
1445 !IsStructurallyEquivalent(ND1->getIdentifier(), ND2->getIdentifier()))
1449 DC1 = DC1->getParent()->getNonTransparentContext();
1450 DC2 = DC2->getParent()->getNonTransparentContext();
1456 static bool NameIsStructurallyEquivalent(const TagDecl &D1, const TagDecl &D2) {
1457 auto GetName = [](const TagDecl &D) -> const IdentifierInfo * {
1458 if (const IdentifierInfo *Name = D.getIdentifier())
1460 if (const TypedefNameDecl *TypedefName = D.getTypedefNameForAnonDecl())
1461 return TypedefName->getIdentifier();
1464 return IsStructurallyEquivalent(GetName(D1), GetName(D2));
1467 /// Determine structural equivalence of two records.
1468 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1469 RecordDecl *D1, RecordDecl *D2) {
1470 if (!NameIsStructurallyEquivalent(*D1, *D2)) {
1474 if (D1->isUnion() != D2->isUnion()) {
1475 if (Context.Complain) {
1476 Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic(
1477 diag::err_odr_tag_type_inconsistent))
1478 << Context.ToCtx.getTypeDeclType(D2);
1479 Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
1480 << D1->getDeclName() << (unsigned)D1->getTagKind();
1485 if (!D1->getDeclName() && !D2->getDeclName()) {
1486 // If both anonymous structs/unions are in a record context, make sure
1487 // they occur in the same location in the context records.
1488 if (std::optional<unsigned> Index1 =
1489 StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(D1)) {
1490 if (std::optional<unsigned> Index2 =
1491 StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(
1493 if (*Index1 != *Index2)
1499 // If the records occur in different context (namespace), these should be
1500 // different. This is specially important if the definition of one or both
1501 // records is missing.
1502 if (!IsRecordContextStructurallyEquivalent(D1, D2))
1505 // If both declarations are class template specializations, we know
1506 // the ODR applies, so check the template and template arguments.
1507 const auto *Spec1 = dyn_cast<ClassTemplateSpecializationDecl>(D1);
1508 const auto *Spec2 = dyn_cast<ClassTemplateSpecializationDecl>(D2);
1509 if (Spec1 && Spec2) {
1510 // Check that the specialized templates are the same.
1511 if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
1512 Spec2->getSpecializedTemplate()))
1515 // Check that the template arguments are the same.
1516 if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
1519 for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
1520 if (!IsStructurallyEquivalent(Context, Spec1->getTemplateArgs().get(I),
1521 Spec2->getTemplateArgs().get(I)))
1524 // If one is a class template specialization and the other is not, these
1525 // structures are different.
1526 else if (Spec1 || Spec2)
1529 // Compare the definitions of these two records. If either or both are
1530 // incomplete (i.e. it is a forward decl), we assume that they are
1532 D1 = D1->getDefinition();
1533 D2 = D2->getDefinition();
1537 // If any of the records has external storage and we do a minimal check (or
1538 // AST import) we assume they are equivalent. (If we didn't have this
1539 // assumption then `RecordDecl::LoadFieldsFromExternalStorage` could trigger
1540 // another AST import which in turn would call the structural equivalency
1541 // check again and finally we'd have an improper result.)
1542 if (Context.EqKind == StructuralEquivalenceKind::Minimal)
1543 if (D1->hasExternalLexicalStorage() || D2->hasExternalLexicalStorage())
1546 // If one definition is currently being defined, we do not compare for
1547 // equality and we assume that the decls are equal.
1548 if (D1->isBeingDefined() || D2->isBeingDefined())
1551 if (auto *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
1552 if (auto *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
1553 if (D1CXX->hasExternalLexicalStorage() &&
1554 !D1CXX->isCompleteDefinition()) {
1555 D1CXX->getASTContext().getExternalSource()->CompleteType(D1CXX);
1558 if (D1CXX->isLambda() != D2CXX->isLambda())
1560 if (D1CXX->isLambda()) {
1561 if (!IsStructurallyEquivalentLambdas(Context, D1CXX, D2CXX))
1565 if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
1566 if (Context.Complain) {
1567 Context.Diag2(D2->getLocation(),
1568 Context.getApplicableDiagnostic(
1569 diag::err_odr_tag_type_inconsistent))
1570 << Context.ToCtx.getTypeDeclType(D2);
1571 Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
1572 << D2CXX->getNumBases();
1573 Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
1574 << D1CXX->getNumBases();
1579 // Check the base classes.
1580 for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(),
1581 BaseEnd1 = D1CXX->bases_end(),
1582 Base2 = D2CXX->bases_begin();
1583 Base1 != BaseEnd1; ++Base1, ++Base2) {
1584 if (!IsStructurallyEquivalent(Context, Base1->getType(),
1585 Base2->getType())) {
1586 if (Context.Complain) {
1587 Context.Diag2(D2->getLocation(),
1588 Context.getApplicableDiagnostic(
1589 diag::err_odr_tag_type_inconsistent))
1590 << Context.ToCtx.getTypeDeclType(D2);
1591 Context.Diag2(Base2->getBeginLoc(), diag::note_odr_base)
1592 << Base2->getType() << Base2->getSourceRange();
1593 Context.Diag1(Base1->getBeginLoc(), diag::note_odr_base)
1594 << Base1->getType() << Base1->getSourceRange();
1599 // Check virtual vs. non-virtual inheritance mismatch.
1600 if (Base1->isVirtual() != Base2->isVirtual()) {
1601 if (Context.Complain) {
1602 Context.Diag2(D2->getLocation(),
1603 Context.getApplicableDiagnostic(
1604 diag::err_odr_tag_type_inconsistent))
1605 << Context.ToCtx.getTypeDeclType(D2);
1606 Context.Diag2(Base2->getBeginLoc(), diag::note_odr_virtual_base)
1607 << Base2->isVirtual() << Base2->getSourceRange();
1608 Context.Diag1(Base1->getBeginLoc(), diag::note_odr_base)
1609 << Base1->isVirtual() << Base1->getSourceRange();
1615 // Check the friends for consistency.
1616 CXXRecordDecl::friend_iterator Friend2 = D2CXX->friend_begin(),
1617 Friend2End = D2CXX->friend_end();
1618 for (CXXRecordDecl::friend_iterator Friend1 = D1CXX->friend_begin(),
1619 Friend1End = D1CXX->friend_end();
1620 Friend1 != Friend1End; ++Friend1, ++Friend2) {
1621 if (Friend2 == Friend2End) {
1622 if (Context.Complain) {
1623 Context.Diag2(D2->getLocation(),
1624 Context.getApplicableDiagnostic(
1625 diag::err_odr_tag_type_inconsistent))
1626 << Context.ToCtx.getTypeDeclType(D2CXX);
1627 Context.Diag1((*Friend1)->getFriendLoc(), diag::note_odr_friend);
1628 Context.Diag2(D2->getLocation(), diag::note_odr_missing_friend);
1633 if (!IsStructurallyEquivalent(Context, *Friend1, *Friend2)) {
1634 if (Context.Complain) {
1635 Context.Diag2(D2->getLocation(),
1636 Context.getApplicableDiagnostic(
1637 diag::err_odr_tag_type_inconsistent))
1638 << Context.ToCtx.getTypeDeclType(D2CXX);
1639 Context.Diag1((*Friend1)->getFriendLoc(), diag::note_odr_friend);
1640 Context.Diag2((*Friend2)->getFriendLoc(), diag::note_odr_friend);
1646 if (Friend2 != Friend2End) {
1647 if (Context.Complain) {
1648 Context.Diag2(D2->getLocation(),
1649 Context.getApplicableDiagnostic(
1650 diag::err_odr_tag_type_inconsistent))
1651 << Context.ToCtx.getTypeDeclType(D2);
1652 Context.Diag2((*Friend2)->getFriendLoc(), diag::note_odr_friend);
1653 Context.Diag1(D1->getLocation(), diag::note_odr_missing_friend);
1657 } else if (D1CXX->getNumBases() > 0) {
1658 if (Context.Complain) {
1659 Context.Diag2(D2->getLocation(),
1660 Context.getApplicableDiagnostic(
1661 diag::err_odr_tag_type_inconsistent))
1662 << Context.ToCtx.getTypeDeclType(D2);
1663 const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
1664 Context.Diag1(Base1->getBeginLoc(), diag::note_odr_base)
1665 << Base1->getType() << Base1->getSourceRange();
1666 Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
1672 // Check the fields for consistency.
1673 QualType D2Type = Context.ToCtx.getTypeDeclType(D2);
1674 RecordDecl::field_iterator Field2 = D2->field_begin(),
1675 Field2End = D2->field_end();
1676 for (RecordDecl::field_iterator Field1 = D1->field_begin(),
1677 Field1End = D1->field_end();
1678 Field1 != Field1End; ++Field1, ++Field2) {
1679 if (Field2 == Field2End) {
1680 if (Context.Complain) {
1681 Context.Diag2(D2->getLocation(),
1682 Context.getApplicableDiagnostic(
1683 diag::err_odr_tag_type_inconsistent))
1684 << Context.ToCtx.getTypeDeclType(D2);
1685 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1686 << Field1->getDeclName() << Field1->getType();
1687 Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
1692 if (!IsStructurallyEquivalent(Context, *Field1, *Field2, D2Type))
1696 if (Field2 != Field2End) {
1697 if (Context.Complain) {
1698 Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic(
1699 diag::err_odr_tag_type_inconsistent))
1700 << Context.ToCtx.getTypeDeclType(D2);
1701 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1702 << Field2->getDeclName() << Field2->getType();
1703 Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
1711 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1712 EnumConstantDecl *D1,
1713 EnumConstantDecl *D2) {
1714 const llvm::APSInt &FromVal = D1->getInitVal();
1715 const llvm::APSInt &ToVal = D2->getInitVal();
1716 if (FromVal.isSigned() != ToVal.isSigned())
1718 if (FromVal.getBitWidth() != ToVal.getBitWidth())
1720 if (FromVal != ToVal)
1723 if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier()))
1726 // Init expressions are the most expensive check, so do them last.
1727 return IsStructurallyEquivalent(Context, D1->getInitExpr(),
1731 /// Determine structural equivalence of two enums.
1732 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1733 EnumDecl *D1, EnumDecl *D2) {
1734 if (!NameIsStructurallyEquivalent(*D1, *D2)) {
1738 // Compare the definitions of these two enums. If either or both are
1739 // incomplete (i.e. forward declared), we assume that they are equivalent.
1740 D1 = D1->getDefinition();
1741 D2 = D2->getDefinition();
1745 EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
1746 EC2End = D2->enumerator_end();
1747 for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
1748 EC1End = D1->enumerator_end();
1749 EC1 != EC1End; ++EC1, ++EC2) {
1750 if (EC2 == EC2End) {
1751 if (Context.Complain) {
1752 Context.Diag2(D2->getLocation(),
1753 Context.getApplicableDiagnostic(
1754 diag::err_odr_tag_type_inconsistent))
1755 << Context.ToCtx.getTypeDeclType(D2);
1756 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1757 << EC1->getDeclName() << toString(EC1->getInitVal(), 10);
1758 Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
1763 llvm::APSInt Val1 = EC1->getInitVal();
1764 llvm::APSInt Val2 = EC2->getInitVal();
1765 if (!llvm::APSInt::isSameValue(Val1, Val2) ||
1766 !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
1767 if (Context.Complain) {
1768 Context.Diag2(D2->getLocation(),
1769 Context.getApplicableDiagnostic(
1770 diag::err_odr_tag_type_inconsistent))
1771 << Context.ToCtx.getTypeDeclType(D2);
1772 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1773 << EC2->getDeclName() << toString(EC2->getInitVal(), 10);
1774 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1775 << EC1->getDeclName() << toString(EC1->getInitVal(), 10);
1781 if (EC2 != EC2End) {
1782 if (Context.Complain) {
1783 Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic(
1784 diag::err_odr_tag_type_inconsistent))
1785 << Context.ToCtx.getTypeDeclType(D2);
1786 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1787 << EC2->getDeclName() << toString(EC2->getInitVal(), 10);
1788 Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
1796 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1797 TemplateParameterList *Params1,
1798 TemplateParameterList *Params2) {
1799 if (Params1->size() != Params2->size()) {
1800 if (Context.Complain) {
1801 Context.Diag2(Params2->getTemplateLoc(),
1802 Context.getApplicableDiagnostic(
1803 diag::err_odr_different_num_template_parameters))
1804 << Params1->size() << Params2->size();
1805 Context.Diag1(Params1->getTemplateLoc(),
1806 diag::note_odr_template_parameter_list);
1811 for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
1812 if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
1813 if (Context.Complain) {
1814 Context.Diag2(Params2->getParam(I)->getLocation(),
1815 Context.getApplicableDiagnostic(
1816 diag::err_odr_different_template_parameter_kind));
1817 Context.Diag1(Params1->getParam(I)->getLocation(),
1818 diag::note_odr_template_parameter_here);
1823 if (!IsStructurallyEquivalent(Context, Params1->getParam(I),
1824 Params2->getParam(I)))
1831 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1832 TemplateTypeParmDecl *D1,
1833 TemplateTypeParmDecl *D2) {
1834 if (D1->isParameterPack() != D2->isParameterPack()) {
1835 if (Context.Complain) {
1836 Context.Diag2(D2->getLocation(),
1837 Context.getApplicableDiagnostic(
1838 diag::err_odr_parameter_pack_non_pack))
1839 << D2->isParameterPack();
1840 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1841 << D1->isParameterPack();
1849 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1850 NonTypeTemplateParmDecl *D1,
1851 NonTypeTemplateParmDecl *D2) {
1852 if (D1->isParameterPack() != D2->isParameterPack()) {
1853 if (Context.Complain) {
1854 Context.Diag2(D2->getLocation(),
1855 Context.getApplicableDiagnostic(
1856 diag::err_odr_parameter_pack_non_pack))
1857 << D2->isParameterPack();
1858 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1859 << D1->isParameterPack();
1865 if (!IsStructurallyEquivalent(Context, D1->getType(), D2->getType())) {
1866 if (Context.Complain) {
1867 Context.Diag2(D2->getLocation(),
1868 Context.getApplicableDiagnostic(
1869 diag::err_odr_non_type_parameter_type_inconsistent))
1870 << D2->getType() << D1->getType();
1871 Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
1880 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1881 TemplateTemplateParmDecl *D1,
1882 TemplateTemplateParmDecl *D2) {
1883 if (D1->isParameterPack() != D2->isParameterPack()) {
1884 if (Context.Complain) {
1885 Context.Diag2(D2->getLocation(),
1886 Context.getApplicableDiagnostic(
1887 diag::err_odr_parameter_pack_non_pack))
1888 << D2->isParameterPack();
1889 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1890 << D1->isParameterPack();
1895 // Check template parameter lists.
1896 return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1897 D2->getTemplateParameters());
1900 static bool IsTemplateDeclCommonStructurallyEquivalent(
1901 StructuralEquivalenceContext &Ctx, TemplateDecl *D1, TemplateDecl *D2) {
1902 if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier()))
1904 if (!D1->getIdentifier()) // Special name
1905 if (D1->getNameAsString() != D2->getNameAsString())
1907 return IsStructurallyEquivalent(Ctx, D1->getTemplateParameters(),
1908 D2->getTemplateParameters());
1911 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1912 ClassTemplateDecl *D1,
1913 ClassTemplateDecl *D2) {
1914 // Check template parameters.
1915 if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2))
1918 // Check the templated declaration.
1919 return IsStructurallyEquivalent(Context, D1->getTemplatedDecl(),
1920 D2->getTemplatedDecl());
1923 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1924 FunctionTemplateDecl *D1,
1925 FunctionTemplateDecl *D2) {
1926 // Check template parameters.
1927 if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2))
1930 // Check the templated declaration.
1931 return IsStructurallyEquivalent(Context, D1->getTemplatedDecl()->getType(),
1932 D2->getTemplatedDecl()->getType());
1935 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1938 // Check template parameters.
1939 if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2))
1942 // Check the constraint expression.
1943 return IsStructurallyEquivalent(Context, D1->getConstraintExpr(),
1944 D2->getConstraintExpr());
1947 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1948 FriendDecl *D1, FriendDecl *D2) {
1949 if ((D1->getFriendType() && D2->getFriendDecl()) ||
1950 (D1->getFriendDecl() && D2->getFriendType())) {
1953 if (D1->getFriendType() && D2->getFriendType())
1954 return IsStructurallyEquivalent(Context,
1955 D1->getFriendType()->getType(),
1956 D2->getFriendType()->getType());
1957 if (D1->getFriendDecl() && D2->getFriendDecl())
1958 return IsStructurallyEquivalent(Context, D1->getFriendDecl(),
1959 D2->getFriendDecl());
1963 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1964 TypedefNameDecl *D1, TypedefNameDecl *D2) {
1965 if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier()))
1968 return IsStructurallyEquivalent(Context, D1->getUnderlyingType(),
1969 D2->getUnderlyingType());
1972 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1973 FunctionDecl *D1, FunctionDecl *D2) {
1974 if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier()))
1977 if (D1->isOverloadedOperator()) {
1978 if (!D2->isOverloadedOperator())
1980 if (D1->getOverloadedOperator() != D2->getOverloadedOperator())
1984 // FIXME: Consider checking for function attributes as well.
1985 if (!IsStructurallyEquivalent(Context, D1->getType(), D2->getType()))
1991 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1992 ObjCIvarDecl *D1, ObjCIvarDecl *D2,
1993 QualType Owner2Type) {
1994 if (D1->getAccessControl() != D2->getAccessControl())
1997 return IsStructurallyEquivalent(Context, cast<FieldDecl>(D1),
1998 cast<FieldDecl>(D2), Owner2Type);
2001 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
2002 ObjCIvarDecl *D1, ObjCIvarDecl *D2) {
2003 QualType Owner2Type =
2004 Context.ToCtx.getObjCInterfaceType(D2->getContainingInterface());
2005 return IsStructurallyEquivalent(Context, D1, D2, Owner2Type);
2008 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
2009 ObjCMethodDecl *Method1,
2010 ObjCMethodDecl *Method2) {
2011 bool PropertiesEqual =
2012 Method1->isInstanceMethod() == Method2->isInstanceMethod() &&
2013 Method1->isVariadic() == Method2->isVariadic() &&
2014 Method1->isDirectMethod() == Method2->isDirectMethod();
2015 if (!PropertiesEqual)
2018 // Compare selector slot names.
2019 Selector Selector1 = Method1->getSelector(),
2020 Selector2 = Method2->getSelector();
2021 unsigned NumArgs = Selector1.getNumArgs();
2022 if (NumArgs != Selector2.getNumArgs())
2024 // Compare all selector slots. For selectors with arguments it means all arg
2025 // slots. And if there are no arguments, compare the first-and-only slot.
2026 unsigned SlotsToCheck = NumArgs > 0 ? NumArgs : 1;
2027 for (unsigned I = 0; I < SlotsToCheck; ++I) {
2028 if (!IsStructurallyEquivalent(Selector1.getIdentifierInfoForSlot(I),
2029 Selector2.getIdentifierInfoForSlot(I)))
2034 if (!IsStructurallyEquivalent(Context, Method1->getReturnType(),
2035 Method2->getReturnType()))
2038 Method1->param_size() == Method2->param_size() &&
2039 "Same number of arguments should be already enforced in Selector checks");
2040 for (ObjCMethodDecl::param_type_iterator
2041 ParamT1 = Method1->param_type_begin(),
2042 ParamT1End = Method1->param_type_end(),
2043 ParamT2 = Method2->param_type_begin(),
2044 ParamT2End = Method2->param_type_end();
2045 (ParamT1 != ParamT1End) && (ParamT2 != ParamT2End);
2046 ++ParamT1, ++ParamT2) {
2047 if (!IsStructurallyEquivalent(Context, *ParamT1, *ParamT2))
2054 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
2055 ObjCCategoryDecl *D1,
2056 ObjCCategoryDecl *D2) {
2057 if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier()))
2060 const ObjCInterfaceDecl *Intf1 = D1->getClassInterface(),
2061 *Intf2 = D2->getClassInterface();
2062 if ((!Intf1 || !Intf2) && (Intf1 != Intf2))
2066 !IsStructurallyEquivalent(Intf1->getIdentifier(), Intf2->getIdentifier()))
2069 // Compare protocols.
2070 ObjCCategoryDecl::protocol_iterator Protocol2 = D2->protocol_begin(),
2071 Protocol2End = D2->protocol_end();
2072 for (ObjCCategoryDecl::protocol_iterator Protocol1 = D1->protocol_begin(),
2073 Protocol1End = D1->protocol_end();
2074 Protocol1 != Protocol1End; ++Protocol1, ++Protocol2) {
2075 if (Protocol2 == Protocol2End)
2077 if (!IsStructurallyEquivalent((*Protocol1)->getIdentifier(),
2078 (*Protocol2)->getIdentifier()))
2081 if (Protocol2 != Protocol2End)
2086 Intf2 ? Context.ToCtx.getObjCInterfaceType(Intf2) : QualType();
2087 ObjCCategoryDecl::ivar_iterator Ivar2 = D2->ivar_begin(),
2088 Ivar2End = D2->ivar_end();
2089 for (ObjCCategoryDecl::ivar_iterator Ivar1 = D1->ivar_begin(),
2090 Ivar1End = D1->ivar_end();
2091 Ivar1 != Ivar1End; ++Ivar1, ++Ivar2) {
2092 if (Ivar2 == Ivar2End)
2094 if (!IsStructurallyEquivalent(Context, *Ivar1, *Ivar2, D2Type))
2097 if (Ivar2 != Ivar2End)
2101 ObjCCategoryDecl::method_iterator Method2 = D2->meth_begin(),
2102 Method2End = D2->meth_end();
2103 for (ObjCCategoryDecl::method_iterator Method1 = D1->meth_begin(),
2104 Method1End = D1->meth_end();
2105 Method1 != Method1End; ++Method1, ++Method2) {
2106 if (Method2 == Method2End)
2108 if (!IsStructurallyEquivalent(Context, *Method1, *Method2))
2111 if (Method2 != Method2End)
2117 /// Determine structural equivalence of two declarations.
2118 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
2119 Decl *D1, Decl *D2) {
2120 // FIXME: Check for known structural equivalences via a callback of some sort.
2122 D1 = D1->getCanonicalDecl();
2123 D2 = D2->getCanonicalDecl();
2124 std::pair<Decl *, Decl *> P{D1, D2};
2126 // Check whether we already know that these two declarations are not
2127 // structurally equivalent.
2128 if (Context.NonEquivalentDecls.count(P))
2131 // Check if a check for these declarations is already pending.
2132 // If yes D1 and D2 will be checked later (from DeclsToCheck),
2133 // or these are already checked (and equivalent).
2134 bool Inserted = Context.VisitedDecls.insert(P).second;
2138 Context.DeclsToCheck.push(P);
2143 DiagnosticBuilder StructuralEquivalenceContext::Diag1(SourceLocation Loc,
2145 assert(Complain && "Not allowed to complain");
2147 FromCtx.getDiagnostics().notePriorDiagnosticFrom(ToCtx.getDiagnostics());
2148 LastDiagFromC2 = false;
2149 return FromCtx.getDiagnostics().Report(Loc, DiagID);
2152 DiagnosticBuilder StructuralEquivalenceContext::Diag2(SourceLocation Loc,
2154 assert(Complain && "Not allowed to complain");
2155 if (!LastDiagFromC2)
2156 ToCtx.getDiagnostics().notePriorDiagnosticFrom(FromCtx.getDiagnostics());
2157 LastDiagFromC2 = true;
2158 return ToCtx.getDiagnostics().Report(Loc, DiagID);
2161 std::optional<unsigned>
2162 StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(RecordDecl *Anon) {
2163 ASTContext &Context = Anon->getASTContext();
2164 QualType AnonTy = Context.getRecordType(Anon);
2166 const auto *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext());
2168 return std::nullopt;
2171 for (const auto *D : Owner->noload_decls()) {
2172 const auto *F = dyn_cast<FieldDecl>(D);
2176 if (F->isAnonymousStructOrUnion()) {
2177 if (Context.hasSameType(F->getType(), AnonTy))
2183 // If the field looks like this:
2184 // struct { ... } A;
2185 QualType FieldType = F->getType();
2186 // In case of nested structs.
2187 while (const auto *ElabType = dyn_cast<ElaboratedType>(FieldType))
2188 FieldType = ElabType->getNamedType();
2190 if (const auto *RecType = dyn_cast<RecordType>(FieldType)) {
2191 const RecordDecl *RecDecl = RecType->getDecl();
2192 if (RecDecl->getDeclContext() == Owner && !RecDecl->getIdentifier()) {
2193 if (Context.hasSameType(FieldType, AnonTy))
2204 unsigned StructuralEquivalenceContext::getApplicableDiagnostic(
2205 unsigned ErrorDiagnostic) {
2206 if (ErrorOnTagTypeMismatch)
2207 return ErrorDiagnostic;
2209 switch (ErrorDiagnostic) {
2210 case diag::err_odr_variable_type_inconsistent:
2211 return diag::warn_odr_variable_type_inconsistent;
2212 case diag::err_odr_variable_multiple_def:
2213 return diag::warn_odr_variable_multiple_def;
2214 case diag::err_odr_function_type_inconsistent:
2215 return diag::warn_odr_function_type_inconsistent;
2216 case diag::err_odr_tag_type_inconsistent:
2217 return diag::warn_odr_tag_type_inconsistent;
2218 case diag::err_odr_field_type_inconsistent:
2219 return diag::warn_odr_field_type_inconsistent;
2220 case diag::err_odr_ivar_type_inconsistent:
2221 return diag::warn_odr_ivar_type_inconsistent;
2222 case diag::err_odr_objc_superclass_inconsistent:
2223 return diag::warn_odr_objc_superclass_inconsistent;
2224 case diag::err_odr_objc_method_result_type_inconsistent:
2225 return diag::warn_odr_objc_method_result_type_inconsistent;
2226 case diag::err_odr_objc_method_num_params_inconsistent:
2227 return diag::warn_odr_objc_method_num_params_inconsistent;
2228 case diag::err_odr_objc_method_param_type_inconsistent:
2229 return diag::warn_odr_objc_method_param_type_inconsistent;
2230 case diag::err_odr_objc_method_variadic_inconsistent:
2231 return diag::warn_odr_objc_method_variadic_inconsistent;
2232 case diag::err_odr_objc_property_type_inconsistent:
2233 return diag::warn_odr_objc_property_type_inconsistent;
2234 case diag::err_odr_objc_property_impl_kind_inconsistent:
2235 return diag::warn_odr_objc_property_impl_kind_inconsistent;
2236 case diag::err_odr_objc_synthesize_ivar_inconsistent:
2237 return diag::warn_odr_objc_synthesize_ivar_inconsistent;
2238 case diag::err_odr_different_num_template_parameters:
2239 return diag::warn_odr_different_num_template_parameters;
2240 case diag::err_odr_different_template_parameter_kind:
2241 return diag::warn_odr_different_template_parameter_kind;
2242 case diag::err_odr_parameter_pack_non_pack:
2243 return diag::warn_odr_parameter_pack_non_pack;
2244 case diag::err_odr_non_type_parameter_type_inconsistent:
2245 return diag::warn_odr_non_type_parameter_type_inconsistent;
2247 llvm_unreachable("Diagnostic kind not handled in preceding switch");
2250 bool StructuralEquivalenceContext::IsEquivalent(Decl *D1, Decl *D2) {
2252 // Ensure that the implementation functions (all static functions in this TU)
2253 // never call the public ASTStructuralEquivalence::IsEquivalent() functions,
2254 // because that will wreak havoc the internal state (DeclsToCheck and
2255 // VisitedDecls members) and can cause faulty behaviour.
2256 // In other words: Do not start a graph search from a new node with the
2257 // internal data of another search in progress.
2258 // FIXME: Better encapsulation and separation of internal and public
2260 assert(DeclsToCheck.empty());
2261 assert(VisitedDecls.empty());
2263 if (!::IsStructurallyEquivalent(*this, D1, D2))
2269 bool StructuralEquivalenceContext::IsEquivalent(QualType T1, QualType T2) {
2270 assert(DeclsToCheck.empty());
2271 assert(VisitedDecls.empty());
2272 if (!::IsStructurallyEquivalent(*this, T1, T2))
2278 bool StructuralEquivalenceContext::IsEquivalent(Stmt *S1, Stmt *S2) {
2279 assert(DeclsToCheck.empty());
2280 assert(VisitedDecls.empty());
2281 if (!::IsStructurallyEquivalent(*this, S1, S2))
2287 bool StructuralEquivalenceContext::CheckCommonEquivalence(Decl *D1, Decl *D2) {
2288 // Check for equivalent described template.
2289 TemplateDecl *Template1 = D1->getDescribedTemplate();
2290 TemplateDecl *Template2 = D2->getDescribedTemplate();
2291 if ((Template1 != nullptr) != (Template2 != nullptr))
2293 if (Template1 && !IsStructurallyEquivalent(*this, Template1, Template2))
2296 // FIXME: Move check for identifier names into this function.
2301 bool StructuralEquivalenceContext::CheckKindSpecificEquivalence(
2302 Decl *D1, Decl *D2) {
2305 if (D1->getKind() != D2->getKind())
2308 // Cast the Decls to their actual subclass so that the right overload of
2309 // IsStructurallyEquivalent is called.
2310 switch (D1->getKind()) {
2311 #define ABSTRACT_DECL(DECL)
2312 #define DECL(DERIVED, BASE) \
2313 case Decl::Kind::DERIVED: \
2314 return ::IsStructurallyEquivalent(*this, static_cast<DERIVED##Decl *>(D1), \
2315 static_cast<DERIVED##Decl *>(D2));
2316 #include "clang/AST/DeclNodes.inc"
2321 bool StructuralEquivalenceContext::Finish() {
2322 while (!DeclsToCheck.empty()) {
2323 // Check the next declaration.
2324 std::pair<Decl *, Decl *> P = DeclsToCheck.front();
2328 Decl *D2 = P.second;
2331 CheckCommonEquivalence(D1, D2) && CheckKindSpecificEquivalence(D1, D2);
2334 // Note that these two declarations are not equivalent (and we already
2336 NonEquivalentDecls.insert(P);