1 //===- ASTStructuralEquivalence.cpp ---------------------------------------===// 2 // 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 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implement StructuralEquivalenceContext class and helper functions 10 // for layout matching. 11 // 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 14 // beginning. 15 // Let's consider this simple BFS algorithm from the `s` source: 16 // ``` 17 // void bfs(Graph G, int s) 18 // { 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, 26 // { 27 // marked[w] = true; 28 // queue.enqueue(w); 29 // } 30 // } 31 // } 32 // ``` 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. 37 // 38 // We put in the elements into the queue only in the toplevel decl check 39 // function: 40 // ``` 41 // static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 42 // Decl *D1, Decl *D2); 43 // ``` 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. 48 // 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** 57 // functions. 58 // 59 //===----------------------------------------------------------------------===// 60 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/None.h" 88 #include "llvm/ADT/Optional.h" 89 #include "llvm/Support/Casting.h" 90 #include "llvm/Support/Compiler.h" 91 #include "llvm/Support/ErrorHandling.h" 92 #include <cassert> 93 #include <utility> 94 95 using namespace clang; 96 97 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 98 QualType T1, QualType T2); 99 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 100 Decl *D1, Decl *D2); 101 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 102 const TemplateArgument &Arg1, 103 const TemplateArgument &Arg2); 104 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 105 NestedNameSpecifier *NNS1, 106 NestedNameSpecifier *NNS2); 107 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1, 108 const IdentifierInfo *Name2); 109 110 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 111 const DeclarationName Name1, 112 const DeclarationName Name2) { 113 if (Name1.getNameKind() != Name2.getNameKind()) 114 return false; 115 116 switch (Name1.getNameKind()) { 117 118 case DeclarationName::Identifier: 119 return IsStructurallyEquivalent(Name1.getAsIdentifierInfo(), 120 Name2.getAsIdentifierInfo()); 121 122 case DeclarationName::CXXConstructorName: 123 case DeclarationName::CXXDestructorName: 124 case DeclarationName::CXXConversionFunctionName: 125 return IsStructurallyEquivalent(Context, Name1.getCXXNameType(), 126 Name2.getCXXNameType()); 127 128 case DeclarationName::CXXDeductionGuideName: { 129 if (!IsStructurallyEquivalent( 130 Context, Name1.getCXXDeductionGuideTemplate()->getDeclName(), 131 Name2.getCXXDeductionGuideTemplate()->getDeclName())) 132 return false; 133 return IsStructurallyEquivalent(Context, 134 Name1.getCXXDeductionGuideTemplate(), 135 Name2.getCXXDeductionGuideTemplate()); 136 } 137 138 case DeclarationName::CXXOperatorName: 139 return Name1.getCXXOverloadedOperator() == Name2.getCXXOverloadedOperator(); 140 141 case DeclarationName::CXXLiteralOperatorName: 142 return IsStructurallyEquivalent(Name1.getCXXLiteralIdentifier(), 143 Name2.getCXXLiteralIdentifier()); 144 145 case DeclarationName::CXXUsingDirective: 146 return true; // FIXME When do we consider two using directives equal? 147 148 case DeclarationName::ObjCZeroArgSelector: 149 case DeclarationName::ObjCOneArgSelector: 150 case DeclarationName::ObjCMultiArgSelector: 151 return true; // FIXME 152 } 153 154 llvm_unreachable("Unhandled kind of DeclarationName"); 155 return true; 156 } 157 158 namespace { 159 /// Encapsulates Stmt comparison logic. 160 class StmtComparer { 161 StructuralEquivalenceContext &Context; 162 163 // IsStmtEquivalent overloads. Each overload compares a specific statement 164 // and only has to compare the data that is specific to the specific statement 165 // class. Should only be called from TraverseStmt. 166 167 bool IsStmtEquivalent(const AddrLabelExpr *E1, const AddrLabelExpr *E2) { 168 return IsStructurallyEquivalent(Context, E1->getLabel(), E2->getLabel()); 169 } 170 171 bool IsStmtEquivalent(const AtomicExpr *E1, const AtomicExpr *E2) { 172 return E1->getOp() == E2->getOp(); 173 } 174 175 bool IsStmtEquivalent(const BinaryOperator *E1, const BinaryOperator *E2) { 176 return E1->getOpcode() == E2->getOpcode(); 177 } 178 179 bool IsStmtEquivalent(const CallExpr *E1, const CallExpr *E2) { 180 // FIXME: IsStructurallyEquivalent requires non-const Decls. 181 Decl *Callee1 = const_cast<Decl *>(E1->getCalleeDecl()); 182 Decl *Callee2 = const_cast<Decl *>(E2->getCalleeDecl()); 183 184 // Compare whether both calls know their callee. 185 if (static_cast<bool>(Callee1) != static_cast<bool>(Callee2)) 186 return false; 187 188 // Both calls have no callee, so nothing to do. 189 if (!static_cast<bool>(Callee1)) 190 return true; 191 192 assert(Callee2); 193 return IsStructurallyEquivalent(Context, Callee1, Callee2); 194 } 195 196 bool IsStmtEquivalent(const CharacterLiteral *E1, 197 const CharacterLiteral *E2) { 198 return E1->getValue() == E2->getValue() && E1->getKind() == E2->getKind(); 199 } 200 201 bool IsStmtEquivalent(const ChooseExpr *E1, const ChooseExpr *E2) { 202 return true; // Semantics only depend on children. 203 } 204 205 bool IsStmtEquivalent(const CompoundStmt *E1, const CompoundStmt *E2) { 206 // Number of children is actually checked by the generic children comparison 207 // code, but a CompoundStmt is one of the few statements where the number of 208 // children frequently differs and the number of statements is also always 209 // precomputed. Directly comparing the number of children here is thus 210 // just an optimization. 211 return E1->size() == E2->size(); 212 } 213 214 bool IsStmtEquivalent(const DependentScopeDeclRefExpr *DE1, 215 const DependentScopeDeclRefExpr *DE2) { 216 if (!IsStructurallyEquivalent(Context, DE1->getDeclName(), 217 DE2->getDeclName())) 218 return false; 219 return IsStructurallyEquivalent(Context, DE1->getQualifier(), 220 DE2->getQualifier()); 221 } 222 223 bool IsStmtEquivalent(const Expr *E1, const Expr *E2) { 224 return IsStructurallyEquivalent(Context, E1->getType(), E2->getType()); 225 } 226 227 bool IsStmtEquivalent(const ExpressionTraitExpr *E1, 228 const ExpressionTraitExpr *E2) { 229 return E1->getTrait() == E2->getTrait() && E1->getValue() == E2->getValue(); 230 } 231 232 bool IsStmtEquivalent(const FloatingLiteral *E1, const FloatingLiteral *E2) { 233 return E1->isExact() == E2->isExact() && E1->getValue() == E2->getValue(); 234 } 235 236 bool IsStmtEquivalent(const GenericSelectionExpr *E1, 237 const GenericSelectionExpr *E2) { 238 for (auto Pair : zip_longest(E1->getAssocTypeSourceInfos(), 239 E2->getAssocTypeSourceInfos())) { 240 Optional<TypeSourceInfo *> Child1 = std::get<0>(Pair); 241 Optional<TypeSourceInfo *> Child2 = std::get<1>(Pair); 242 // Skip this case if there are a different number of associated types. 243 if (!Child1 || !Child2) 244 return false; 245 246 if (!IsStructurallyEquivalent(Context, (*Child1)->getType(), 247 (*Child2)->getType())) 248 return false; 249 } 250 251 return true; 252 } 253 254 bool IsStmtEquivalent(const ImplicitCastExpr *CastE1, 255 const ImplicitCastExpr *CastE2) { 256 return IsStructurallyEquivalent(Context, CastE1->getType(), 257 CastE2->getType()); 258 } 259 260 bool IsStmtEquivalent(const IntegerLiteral *E1, const IntegerLiteral *E2) { 261 return E1->getValue() == E2->getValue(); 262 } 263 264 bool IsStmtEquivalent(const MemberExpr *E1, const MemberExpr *E2) { 265 return IsStructurallyEquivalent(Context, E1->getFoundDecl(), 266 E2->getFoundDecl()); 267 } 268 269 bool IsStmtEquivalent(const ObjCStringLiteral *E1, 270 const ObjCStringLiteral *E2) { 271 // Just wraps a StringLiteral child. 272 return true; 273 } 274 275 bool IsStmtEquivalent(const Stmt *S1, const Stmt *S2) { return true; } 276 277 bool IsStmtEquivalent(const SourceLocExpr *E1, const SourceLocExpr *E2) { 278 return E1->getIdentKind() == E2->getIdentKind(); 279 } 280 281 bool IsStmtEquivalent(const StmtExpr *E1, const StmtExpr *E2) { 282 return E1->getTemplateDepth() == E2->getTemplateDepth(); 283 } 284 285 bool IsStmtEquivalent(const StringLiteral *E1, const StringLiteral *E2) { 286 return E1->getBytes() == E2->getBytes(); 287 } 288 289 bool IsStmtEquivalent(const SubstNonTypeTemplateParmExpr *E1, 290 const SubstNonTypeTemplateParmExpr *E2) { 291 return IsStructurallyEquivalent(Context, E1->getParameter(), 292 E2->getParameter()); 293 } 294 295 bool IsStmtEquivalent(const SubstNonTypeTemplateParmPackExpr *E1, 296 const SubstNonTypeTemplateParmPackExpr *E2) { 297 return IsStructurallyEquivalent(Context, E1->getArgumentPack(), 298 E2->getArgumentPack()); 299 } 300 301 bool IsStmtEquivalent(const TypeTraitExpr *E1, const TypeTraitExpr *E2) { 302 if (E1->getTrait() != E2->getTrait()) 303 return false; 304 305 for (auto Pair : zip_longest(E1->getArgs(), E2->getArgs())) { 306 Optional<TypeSourceInfo *> Child1 = std::get<0>(Pair); 307 Optional<TypeSourceInfo *> Child2 = std::get<1>(Pair); 308 // Different number of args. 309 if (!Child1 || !Child2) 310 return false; 311 312 if (!IsStructurallyEquivalent(Context, (*Child1)->getType(), 313 (*Child2)->getType())) 314 return false; 315 } 316 return true; 317 } 318 319 bool IsStmtEquivalent(const UnaryExprOrTypeTraitExpr *E1, 320 const UnaryExprOrTypeTraitExpr *E2) { 321 if (E1->getKind() != E2->getKind()) 322 return false; 323 return IsStructurallyEquivalent(Context, E1->getTypeOfArgument(), 324 E2->getTypeOfArgument()); 325 } 326 327 bool IsStmtEquivalent(const UnaryOperator *E1, const UnaryOperator *E2) { 328 return E1->getOpcode() == E2->getOpcode(); 329 } 330 331 bool IsStmtEquivalent(const VAArgExpr *E1, const VAArgExpr *E2) { 332 // Semantics only depend on children. 333 return true; 334 } 335 336 /// End point of the traversal chain. 337 bool TraverseStmt(const Stmt *S1, const Stmt *S2) { return true; } 338 339 // Create traversal methods that traverse the class hierarchy and return 340 // the accumulated result of the comparison. Each TraverseStmt overload 341 // calls the TraverseStmt overload of the parent class. For example, 342 // the TraverseStmt overload for 'BinaryOperator' calls the TraverseStmt 343 // overload of 'Expr' which then calls the overload for 'Stmt'. 344 #define STMT(CLASS, PARENT) \ 345 bool TraverseStmt(const CLASS *S1, const CLASS *S2) { \ 346 if (!TraverseStmt(static_cast<const PARENT *>(S1), \ 347 static_cast<const PARENT *>(S2))) \ 348 return false; \ 349 return IsStmtEquivalent(S1, S2); \ 350 } 351 #include "clang/AST/StmtNodes.inc" 352 353 public: 354 StmtComparer(StructuralEquivalenceContext &C) : Context(C) {} 355 356 /// Determine whether two statements are equivalent. The statements have to 357 /// be of the same kind. The children of the statements and their properties 358 /// are not compared by this function. 359 bool IsEquivalent(const Stmt *S1, const Stmt *S2) { 360 if (S1->getStmtClass() != S2->getStmtClass()) 361 return false; 362 363 // Each TraverseStmt walks the class hierarchy from the leaf class to 364 // the root class 'Stmt' (e.g. 'BinaryOperator' -> 'Expr' -> 'Stmt'). Cast 365 // the Stmt we have here to its specific subclass so that we call the 366 // overload that walks the whole class hierarchy from leaf to root (e.g., 367 // cast to 'BinaryOperator' so that 'Expr' and 'Stmt' is traversed). 368 switch (S1->getStmtClass()) { 369 case Stmt::NoStmtClass: 370 llvm_unreachable("Can't traverse NoStmtClass"); 371 #define STMT(CLASS, PARENT) \ 372 case Stmt::StmtClass::CLASS##Class: \ 373 return TraverseStmt(static_cast<const CLASS *>(S1), \ 374 static_cast<const CLASS *>(S2)); 375 #define ABSTRACT_STMT(S) 376 #include "clang/AST/StmtNodes.inc" 377 } 378 llvm_unreachable("Invalid statement kind"); 379 } 380 }; 381 } // namespace 382 383 /// Determine structural equivalence of two statements. 384 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 385 const Stmt *S1, const Stmt *S2) { 386 if (!S1 || !S2) 387 return S1 == S2; 388 389 // Compare the statements itself. 390 StmtComparer Comparer(Context); 391 if (!Comparer.IsEquivalent(S1, S2)) 392 return false; 393 394 // Iterate over the children of both statements and also compare them. 395 for (auto Pair : zip_longest(S1->children(), S2->children())) { 396 Optional<const Stmt *> Child1 = std::get<0>(Pair); 397 Optional<const Stmt *> Child2 = std::get<1>(Pair); 398 // One of the statements has a different amount of children than the other, 399 // so the statements can't be equivalent. 400 if (!Child1 || !Child2) 401 return false; 402 if (!IsStructurallyEquivalent(Context, *Child1, *Child2)) 403 return false; 404 } 405 return true; 406 } 407 408 /// Determine whether two identifiers are equivalent. 409 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1, 410 const IdentifierInfo *Name2) { 411 if (!Name1 || !Name2) 412 return Name1 == Name2; 413 414 return Name1->getName() == Name2->getName(); 415 } 416 417 /// Determine whether two nested-name-specifiers are equivalent. 418 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 419 NestedNameSpecifier *NNS1, 420 NestedNameSpecifier *NNS2) { 421 if (NNS1->getKind() != NNS2->getKind()) 422 return false; 423 424 NestedNameSpecifier *Prefix1 = NNS1->getPrefix(), 425 *Prefix2 = NNS2->getPrefix(); 426 if ((bool)Prefix1 != (bool)Prefix2) 427 return false; 428 429 if (Prefix1) 430 if (!IsStructurallyEquivalent(Context, Prefix1, Prefix2)) 431 return false; 432 433 switch (NNS1->getKind()) { 434 case NestedNameSpecifier::Identifier: 435 return IsStructurallyEquivalent(NNS1->getAsIdentifier(), 436 NNS2->getAsIdentifier()); 437 case NestedNameSpecifier::Namespace: 438 return IsStructurallyEquivalent(Context, NNS1->getAsNamespace(), 439 NNS2->getAsNamespace()); 440 case NestedNameSpecifier::NamespaceAlias: 441 return IsStructurallyEquivalent(Context, NNS1->getAsNamespaceAlias(), 442 NNS2->getAsNamespaceAlias()); 443 case NestedNameSpecifier::TypeSpec: 444 case NestedNameSpecifier::TypeSpecWithTemplate: 445 return IsStructurallyEquivalent(Context, QualType(NNS1->getAsType(), 0), 446 QualType(NNS2->getAsType(), 0)); 447 case NestedNameSpecifier::Global: 448 return true; 449 case NestedNameSpecifier::Super: 450 return IsStructurallyEquivalent(Context, NNS1->getAsRecordDecl(), 451 NNS2->getAsRecordDecl()); 452 } 453 return false; 454 } 455 456 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 457 const TemplateName &N1, 458 const TemplateName &N2) { 459 TemplateDecl *TemplateDeclN1 = N1.getAsTemplateDecl(); 460 TemplateDecl *TemplateDeclN2 = N2.getAsTemplateDecl(); 461 if (TemplateDeclN1 && TemplateDeclN2) { 462 if (!IsStructurallyEquivalent(Context, TemplateDeclN1, TemplateDeclN2)) 463 return false; 464 // If the kind is different we compare only the template decl. 465 if (N1.getKind() != N2.getKind()) 466 return true; 467 } else if (TemplateDeclN1 || TemplateDeclN2) 468 return false; 469 else if (N1.getKind() != N2.getKind()) 470 return false; 471 472 // Check for special case incompatibilities. 473 switch (N1.getKind()) { 474 475 case TemplateName::OverloadedTemplate: { 476 OverloadedTemplateStorage *OS1 = N1.getAsOverloadedTemplate(), 477 *OS2 = N2.getAsOverloadedTemplate(); 478 OverloadedTemplateStorage::iterator I1 = OS1->begin(), I2 = OS2->begin(), 479 E1 = OS1->end(), E2 = OS2->end(); 480 for (; I1 != E1 && I2 != E2; ++I1, ++I2) 481 if (!IsStructurallyEquivalent(Context, *I1, *I2)) 482 return false; 483 return I1 == E1 && I2 == E2; 484 } 485 486 case TemplateName::AssumedTemplate: { 487 AssumedTemplateStorage *TN1 = N1.getAsAssumedTemplateName(), 488 *TN2 = N1.getAsAssumedTemplateName(); 489 return TN1->getDeclName() == TN2->getDeclName(); 490 } 491 492 case TemplateName::DependentTemplate: { 493 DependentTemplateName *DN1 = N1.getAsDependentTemplateName(), 494 *DN2 = N2.getAsDependentTemplateName(); 495 if (!IsStructurallyEquivalent(Context, DN1->getQualifier(), 496 DN2->getQualifier())) 497 return false; 498 if (DN1->isIdentifier() && DN2->isIdentifier()) 499 return IsStructurallyEquivalent(DN1->getIdentifier(), 500 DN2->getIdentifier()); 501 else if (DN1->isOverloadedOperator() && DN2->isOverloadedOperator()) 502 return DN1->getOperator() == DN2->getOperator(); 503 return false; 504 } 505 506 case TemplateName::SubstTemplateTemplateParmPack: { 507 SubstTemplateTemplateParmPackStorage 508 *P1 = N1.getAsSubstTemplateTemplateParmPack(), 509 *P2 = N2.getAsSubstTemplateTemplateParmPack(); 510 return IsStructurallyEquivalent(Context, P1->getArgumentPack(), 511 P2->getArgumentPack()) && 512 IsStructurallyEquivalent(Context, P1->getParameterPack(), 513 P2->getParameterPack()); 514 } 515 516 case TemplateName::Template: 517 case TemplateName::QualifiedTemplate: 518 case TemplateName::SubstTemplateTemplateParm: 519 // It is sufficient to check value of getAsTemplateDecl. 520 break; 521 522 } 523 524 return true; 525 } 526 527 /// Determine whether two template arguments are equivalent. 528 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 529 const TemplateArgument &Arg1, 530 const TemplateArgument &Arg2) { 531 if (Arg1.getKind() != Arg2.getKind()) 532 return false; 533 534 switch (Arg1.getKind()) { 535 case TemplateArgument::Null: 536 return true; 537 538 case TemplateArgument::Type: 539 return IsStructurallyEquivalent(Context, Arg1.getAsType(), Arg2.getAsType()); 540 541 case TemplateArgument::Integral: 542 if (!IsStructurallyEquivalent(Context, Arg1.getIntegralType(), 543 Arg2.getIntegralType())) 544 return false; 545 546 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(), 547 Arg2.getAsIntegral()); 548 549 case TemplateArgument::Declaration: 550 return IsStructurallyEquivalent(Context, Arg1.getAsDecl(), Arg2.getAsDecl()); 551 552 case TemplateArgument::NullPtr: 553 return true; // FIXME: Is this correct? 554 555 case TemplateArgument::Template: 556 return IsStructurallyEquivalent(Context, Arg1.getAsTemplate(), 557 Arg2.getAsTemplate()); 558 559 case TemplateArgument::TemplateExpansion: 560 return IsStructurallyEquivalent(Context, 561 Arg1.getAsTemplateOrTemplatePattern(), 562 Arg2.getAsTemplateOrTemplatePattern()); 563 564 case TemplateArgument::Expression: 565 return IsStructurallyEquivalent(Context, Arg1.getAsExpr(), 566 Arg2.getAsExpr()); 567 568 case TemplateArgument::UncommonValue: 569 // FIXME: Do we need to customize the comparison? 570 return Arg1.structurallyEquals(Arg2); 571 572 case TemplateArgument::Pack: 573 if (Arg1.pack_size() != Arg2.pack_size()) 574 return false; 575 576 for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I) 577 if (!IsStructurallyEquivalent(Context, Arg1.pack_begin()[I], 578 Arg2.pack_begin()[I])) 579 return false; 580 581 return true; 582 } 583 584 llvm_unreachable("Invalid template argument kind"); 585 } 586 587 /// Determine structural equivalence for the common part of array 588 /// types. 589 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context, 590 const ArrayType *Array1, 591 const ArrayType *Array2) { 592 if (!IsStructurallyEquivalent(Context, Array1->getElementType(), 593 Array2->getElementType())) 594 return false; 595 if (Array1->getSizeModifier() != Array2->getSizeModifier()) 596 return false; 597 if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers()) 598 return false; 599 600 return true; 601 } 602 603 /// Determine structural equivalence based on the ExtInfo of functions. This 604 /// is inspired by ASTContext::mergeFunctionTypes(), we compare calling 605 /// conventions bits but must not compare some other bits. 606 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 607 FunctionType::ExtInfo EI1, 608 FunctionType::ExtInfo EI2) { 609 // Compatible functions must have compatible calling conventions. 610 if (EI1.getCC() != EI2.getCC()) 611 return false; 612 613 // Regparm is part of the calling convention. 614 if (EI1.getHasRegParm() != EI2.getHasRegParm()) 615 return false; 616 if (EI1.getRegParm() != EI2.getRegParm()) 617 return false; 618 619 if (EI1.getProducesResult() != EI2.getProducesResult()) 620 return false; 621 if (EI1.getNoCallerSavedRegs() != EI2.getNoCallerSavedRegs()) 622 return false; 623 if (EI1.getNoCfCheck() != EI2.getNoCfCheck()) 624 return false; 625 626 return true; 627 } 628 629 /// Check the equivalence of exception specifications. 630 static bool IsEquivalentExceptionSpec(StructuralEquivalenceContext &Context, 631 const FunctionProtoType *Proto1, 632 const FunctionProtoType *Proto2) { 633 634 auto Spec1 = Proto1->getExceptionSpecType(); 635 auto Spec2 = Proto2->getExceptionSpecType(); 636 637 if (isUnresolvedExceptionSpec(Spec1) || isUnresolvedExceptionSpec(Spec2)) 638 return true; 639 640 if (Spec1 != Spec2) 641 return false; 642 if (Spec1 == EST_Dynamic) { 643 if (Proto1->getNumExceptions() != Proto2->getNumExceptions()) 644 return false; 645 for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) { 646 if (!IsStructurallyEquivalent(Context, Proto1->getExceptionType(I), 647 Proto2->getExceptionType(I))) 648 return false; 649 } 650 } else if (isComputedNoexcept(Spec1)) { 651 if (!IsStructurallyEquivalent(Context, Proto1->getNoexceptExpr(), 652 Proto2->getNoexceptExpr())) 653 return false; 654 } 655 656 return true; 657 } 658 659 /// Determine structural equivalence of two types. 660 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 661 QualType T1, QualType T2) { 662 if (T1.isNull() || T2.isNull()) 663 return T1.isNull() && T2.isNull(); 664 665 QualType OrigT1 = T1; 666 QualType OrigT2 = T2; 667 668 if (!Context.StrictTypeSpelling) { 669 // We aren't being strict about token-to-token equivalence of types, 670 // so map down to the canonical type. 671 T1 = Context.FromCtx.getCanonicalType(T1); 672 T2 = Context.ToCtx.getCanonicalType(T2); 673 } 674 675 if (T1.getQualifiers() != T2.getQualifiers()) 676 return false; 677 678 Type::TypeClass TC = T1->getTypeClass(); 679 680 if (T1->getTypeClass() != T2->getTypeClass()) { 681 // Compare function types with prototypes vs. without prototypes as if 682 // both did not have prototypes. 683 if (T1->getTypeClass() == Type::FunctionProto && 684 T2->getTypeClass() == Type::FunctionNoProto) 685 TC = Type::FunctionNoProto; 686 else if (T1->getTypeClass() == Type::FunctionNoProto && 687 T2->getTypeClass() == Type::FunctionProto) 688 TC = Type::FunctionNoProto; 689 else 690 return false; 691 } 692 693 switch (TC) { 694 case Type::Builtin: 695 // FIXME: Deal with Char_S/Char_U. 696 if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind()) 697 return false; 698 break; 699 700 case Type::Complex: 701 if (!IsStructurallyEquivalent(Context, 702 cast<ComplexType>(T1)->getElementType(), 703 cast<ComplexType>(T2)->getElementType())) 704 return false; 705 break; 706 707 case Type::Adjusted: 708 case Type::Decayed: 709 if (!IsStructurallyEquivalent(Context, 710 cast<AdjustedType>(T1)->getOriginalType(), 711 cast<AdjustedType>(T2)->getOriginalType())) 712 return false; 713 break; 714 715 case Type::Pointer: 716 if (!IsStructurallyEquivalent(Context, 717 cast<PointerType>(T1)->getPointeeType(), 718 cast<PointerType>(T2)->getPointeeType())) 719 return false; 720 break; 721 722 case Type::BlockPointer: 723 if (!IsStructurallyEquivalent(Context, 724 cast<BlockPointerType>(T1)->getPointeeType(), 725 cast<BlockPointerType>(T2)->getPointeeType())) 726 return false; 727 break; 728 729 case Type::LValueReference: 730 case Type::RValueReference: { 731 const auto *Ref1 = cast<ReferenceType>(T1); 732 const auto *Ref2 = cast<ReferenceType>(T2); 733 if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue()) 734 return false; 735 if (Ref1->isInnerRef() != Ref2->isInnerRef()) 736 return false; 737 if (!IsStructurallyEquivalent(Context, Ref1->getPointeeTypeAsWritten(), 738 Ref2->getPointeeTypeAsWritten())) 739 return false; 740 break; 741 } 742 743 case Type::MemberPointer: { 744 const auto *MemPtr1 = cast<MemberPointerType>(T1); 745 const auto *MemPtr2 = cast<MemberPointerType>(T2); 746 if (!IsStructurallyEquivalent(Context, MemPtr1->getPointeeType(), 747 MemPtr2->getPointeeType())) 748 return false; 749 if (!IsStructurallyEquivalent(Context, QualType(MemPtr1->getClass(), 0), 750 QualType(MemPtr2->getClass(), 0))) 751 return false; 752 break; 753 } 754 755 case Type::ConstantArray: { 756 const auto *Array1 = cast<ConstantArrayType>(T1); 757 const auto *Array2 = cast<ConstantArrayType>(T2); 758 if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize())) 759 return false; 760 761 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2)) 762 return false; 763 break; 764 } 765 766 case Type::IncompleteArray: 767 if (!IsArrayStructurallyEquivalent(Context, cast<ArrayType>(T1), 768 cast<ArrayType>(T2))) 769 return false; 770 break; 771 772 case Type::VariableArray: { 773 const auto *Array1 = cast<VariableArrayType>(T1); 774 const auto *Array2 = cast<VariableArrayType>(T2); 775 if (!IsStructurallyEquivalent(Context, Array1->getSizeExpr(), 776 Array2->getSizeExpr())) 777 return false; 778 779 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2)) 780 return false; 781 782 break; 783 } 784 785 case Type::DependentSizedArray: { 786 const auto *Array1 = cast<DependentSizedArrayType>(T1); 787 const auto *Array2 = cast<DependentSizedArrayType>(T2); 788 if (!IsStructurallyEquivalent(Context, Array1->getSizeExpr(), 789 Array2->getSizeExpr())) 790 return false; 791 792 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2)) 793 return false; 794 795 break; 796 } 797 798 case Type::DependentAddressSpace: { 799 const auto *DepAddressSpace1 = cast<DependentAddressSpaceType>(T1); 800 const auto *DepAddressSpace2 = cast<DependentAddressSpaceType>(T2); 801 if (!IsStructurallyEquivalent(Context, DepAddressSpace1->getAddrSpaceExpr(), 802 DepAddressSpace2->getAddrSpaceExpr())) 803 return false; 804 if (!IsStructurallyEquivalent(Context, DepAddressSpace1->getPointeeType(), 805 DepAddressSpace2->getPointeeType())) 806 return false; 807 808 break; 809 } 810 811 case Type::DependentSizedExtVector: { 812 const auto *Vec1 = cast<DependentSizedExtVectorType>(T1); 813 const auto *Vec2 = cast<DependentSizedExtVectorType>(T2); 814 if (!IsStructurallyEquivalent(Context, Vec1->getSizeExpr(), 815 Vec2->getSizeExpr())) 816 return false; 817 if (!IsStructurallyEquivalent(Context, Vec1->getElementType(), 818 Vec2->getElementType())) 819 return false; 820 break; 821 } 822 823 case Type::DependentVector: { 824 const auto *Vec1 = cast<DependentVectorType>(T1); 825 const auto *Vec2 = cast<DependentVectorType>(T2); 826 if (Vec1->getVectorKind() != Vec2->getVectorKind()) 827 return false; 828 if (!IsStructurallyEquivalent(Context, Vec1->getSizeExpr(), 829 Vec2->getSizeExpr())) 830 return false; 831 if (!IsStructurallyEquivalent(Context, Vec1->getElementType(), 832 Vec2->getElementType())) 833 return false; 834 break; 835 } 836 837 case Type::Vector: 838 case Type::ExtVector: { 839 const auto *Vec1 = cast<VectorType>(T1); 840 const auto *Vec2 = cast<VectorType>(T2); 841 if (!IsStructurallyEquivalent(Context, Vec1->getElementType(), 842 Vec2->getElementType())) 843 return false; 844 if (Vec1->getNumElements() != Vec2->getNumElements()) 845 return false; 846 if (Vec1->getVectorKind() != Vec2->getVectorKind()) 847 return false; 848 break; 849 } 850 851 case Type::DependentSizedMatrix: { 852 const DependentSizedMatrixType *Mat1 = cast<DependentSizedMatrixType>(T1); 853 const DependentSizedMatrixType *Mat2 = cast<DependentSizedMatrixType>(T2); 854 // The element types, row and column expressions must be structurally 855 // equivalent. 856 if (!IsStructurallyEquivalent(Context, Mat1->getRowExpr(), 857 Mat2->getRowExpr()) || 858 !IsStructurallyEquivalent(Context, Mat1->getColumnExpr(), 859 Mat2->getColumnExpr()) || 860 !IsStructurallyEquivalent(Context, Mat1->getElementType(), 861 Mat2->getElementType())) 862 return false; 863 break; 864 } 865 866 case Type::ConstantMatrix: { 867 const ConstantMatrixType *Mat1 = cast<ConstantMatrixType>(T1); 868 const ConstantMatrixType *Mat2 = cast<ConstantMatrixType>(T2); 869 // The element types must be structurally equivalent and the number of rows 870 // and columns must match. 871 if (!IsStructurallyEquivalent(Context, Mat1->getElementType(), 872 Mat2->getElementType()) || 873 Mat1->getNumRows() != Mat2->getNumRows() || 874 Mat1->getNumColumns() != Mat2->getNumColumns()) 875 return false; 876 break; 877 } 878 879 case Type::FunctionProto: { 880 const auto *Proto1 = cast<FunctionProtoType>(T1); 881 const auto *Proto2 = cast<FunctionProtoType>(T2); 882 883 if (Proto1->getNumParams() != Proto2->getNumParams()) 884 return false; 885 for (unsigned I = 0, N = Proto1->getNumParams(); I != N; ++I) { 886 if (!IsStructurallyEquivalent(Context, Proto1->getParamType(I), 887 Proto2->getParamType(I))) 888 return false; 889 } 890 if (Proto1->isVariadic() != Proto2->isVariadic()) 891 return false; 892 893 if (Proto1->getMethodQuals() != Proto2->getMethodQuals()) 894 return false; 895 896 // Check exceptions, this information is lost in canonical type. 897 const auto *OrigProto1 = 898 cast<FunctionProtoType>(OrigT1.getDesugaredType(Context.FromCtx)); 899 const auto *OrigProto2 = 900 cast<FunctionProtoType>(OrigT2.getDesugaredType(Context.ToCtx)); 901 if (!IsEquivalentExceptionSpec(Context, OrigProto1, OrigProto2)) 902 return false; 903 904 // Fall through to check the bits common with FunctionNoProtoType. 905 LLVM_FALLTHROUGH; 906 } 907 908 case Type::FunctionNoProto: { 909 const auto *Function1 = cast<FunctionType>(T1); 910 const auto *Function2 = cast<FunctionType>(T2); 911 if (!IsStructurallyEquivalent(Context, Function1->getReturnType(), 912 Function2->getReturnType())) 913 return false; 914 if (!IsStructurallyEquivalent(Context, Function1->getExtInfo(), 915 Function2->getExtInfo())) 916 return false; 917 break; 918 } 919 920 case Type::UnresolvedUsing: 921 if (!IsStructurallyEquivalent(Context, 922 cast<UnresolvedUsingType>(T1)->getDecl(), 923 cast<UnresolvedUsingType>(T2)->getDecl())) 924 return false; 925 break; 926 927 case Type::Attributed: 928 if (!IsStructurallyEquivalent(Context, 929 cast<AttributedType>(T1)->getModifiedType(), 930 cast<AttributedType>(T2)->getModifiedType())) 931 return false; 932 if (!IsStructurallyEquivalent( 933 Context, cast<AttributedType>(T1)->getEquivalentType(), 934 cast<AttributedType>(T2)->getEquivalentType())) 935 return false; 936 break; 937 938 case Type::Paren: 939 if (!IsStructurallyEquivalent(Context, cast<ParenType>(T1)->getInnerType(), 940 cast<ParenType>(T2)->getInnerType())) 941 return false; 942 break; 943 944 case Type::MacroQualified: 945 if (!IsStructurallyEquivalent( 946 Context, cast<MacroQualifiedType>(T1)->getUnderlyingType(), 947 cast<MacroQualifiedType>(T2)->getUnderlyingType())) 948 return false; 949 break; 950 951 case Type::Typedef: 952 if (!IsStructurallyEquivalent(Context, cast<TypedefType>(T1)->getDecl(), 953 cast<TypedefType>(T2)->getDecl())) 954 return false; 955 break; 956 957 case Type::TypeOfExpr: 958 if (!IsStructurallyEquivalent( 959 Context, cast<TypeOfExprType>(T1)->getUnderlyingExpr(), 960 cast<TypeOfExprType>(T2)->getUnderlyingExpr())) 961 return false; 962 break; 963 964 case Type::TypeOf: 965 if (!IsStructurallyEquivalent(Context, 966 cast<TypeOfType>(T1)->getUnderlyingType(), 967 cast<TypeOfType>(T2)->getUnderlyingType())) 968 return false; 969 break; 970 971 case Type::UnaryTransform: 972 if (!IsStructurallyEquivalent( 973 Context, cast<UnaryTransformType>(T1)->getUnderlyingType(), 974 cast<UnaryTransformType>(T2)->getUnderlyingType())) 975 return false; 976 break; 977 978 case Type::Decltype: 979 if (!IsStructurallyEquivalent(Context, 980 cast<DecltypeType>(T1)->getUnderlyingExpr(), 981 cast<DecltypeType>(T2)->getUnderlyingExpr())) 982 return false; 983 break; 984 985 case Type::Auto: { 986 auto *Auto1 = cast<AutoType>(T1); 987 auto *Auto2 = cast<AutoType>(T2); 988 if (!IsStructurallyEquivalent(Context, Auto1->getDeducedType(), 989 Auto2->getDeducedType())) 990 return false; 991 if (Auto1->isConstrained() != Auto2->isConstrained()) 992 return false; 993 if (Auto1->isConstrained()) { 994 if (Auto1->getTypeConstraintConcept() != 995 Auto2->getTypeConstraintConcept()) 996 return false; 997 ArrayRef<TemplateArgument> Auto1Args = 998 Auto1->getTypeConstraintArguments(); 999 ArrayRef<TemplateArgument> Auto2Args = 1000 Auto2->getTypeConstraintArguments(); 1001 if (Auto1Args.size() != Auto2Args.size()) 1002 return false; 1003 for (unsigned I = 0, N = Auto1Args.size(); I != N; ++I) { 1004 if (!IsStructurallyEquivalent(Context, Auto1Args[I], Auto2Args[I])) 1005 return false; 1006 } 1007 } 1008 break; 1009 } 1010 1011 case Type::DeducedTemplateSpecialization: { 1012 const auto *DT1 = cast<DeducedTemplateSpecializationType>(T1); 1013 const auto *DT2 = cast<DeducedTemplateSpecializationType>(T2); 1014 if (!IsStructurallyEquivalent(Context, DT1->getTemplateName(), 1015 DT2->getTemplateName())) 1016 return false; 1017 if (!IsStructurallyEquivalent(Context, DT1->getDeducedType(), 1018 DT2->getDeducedType())) 1019 return false; 1020 break; 1021 } 1022 1023 case Type::Record: 1024 case Type::Enum: 1025 if (!IsStructurallyEquivalent(Context, cast<TagType>(T1)->getDecl(), 1026 cast<TagType>(T2)->getDecl())) 1027 return false; 1028 break; 1029 1030 case Type::TemplateTypeParm: { 1031 const auto *Parm1 = cast<TemplateTypeParmType>(T1); 1032 const auto *Parm2 = cast<TemplateTypeParmType>(T2); 1033 if (Parm1->getDepth() != Parm2->getDepth()) 1034 return false; 1035 if (Parm1->getIndex() != Parm2->getIndex()) 1036 return false; 1037 if (Parm1->isParameterPack() != Parm2->isParameterPack()) 1038 return false; 1039 1040 // Names of template type parameters are never significant. 1041 break; 1042 } 1043 1044 case Type::SubstTemplateTypeParm: { 1045 const auto *Subst1 = cast<SubstTemplateTypeParmType>(T1); 1046 const auto *Subst2 = cast<SubstTemplateTypeParmType>(T2); 1047 if (!IsStructurallyEquivalent(Context, 1048 QualType(Subst1->getReplacedParameter(), 0), 1049 QualType(Subst2->getReplacedParameter(), 0))) 1050 return false; 1051 if (!IsStructurallyEquivalent(Context, Subst1->getReplacementType(), 1052 Subst2->getReplacementType())) 1053 return false; 1054 break; 1055 } 1056 1057 case Type::SubstTemplateTypeParmPack: { 1058 const auto *Subst1 = cast<SubstTemplateTypeParmPackType>(T1); 1059 const auto *Subst2 = cast<SubstTemplateTypeParmPackType>(T2); 1060 if (!IsStructurallyEquivalent(Context, 1061 QualType(Subst1->getReplacedParameter(), 0), 1062 QualType(Subst2->getReplacedParameter(), 0))) 1063 return false; 1064 if (!IsStructurallyEquivalent(Context, Subst1->getArgumentPack(), 1065 Subst2->getArgumentPack())) 1066 return false; 1067 break; 1068 } 1069 1070 case Type::TemplateSpecialization: { 1071 const auto *Spec1 = cast<TemplateSpecializationType>(T1); 1072 const auto *Spec2 = cast<TemplateSpecializationType>(T2); 1073 if (!IsStructurallyEquivalent(Context, Spec1->getTemplateName(), 1074 Spec2->getTemplateName())) 1075 return false; 1076 if (Spec1->getNumArgs() != Spec2->getNumArgs()) 1077 return false; 1078 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) { 1079 if (!IsStructurallyEquivalent(Context, Spec1->getArg(I), 1080 Spec2->getArg(I))) 1081 return false; 1082 } 1083 break; 1084 } 1085 1086 case Type::Elaborated: { 1087 const auto *Elab1 = cast<ElaboratedType>(T1); 1088 const auto *Elab2 = cast<ElaboratedType>(T2); 1089 // CHECKME: what if a keyword is ETK_None or ETK_typename ? 1090 if (Elab1->getKeyword() != Elab2->getKeyword()) 1091 return false; 1092 if (!IsStructurallyEquivalent(Context, Elab1->getQualifier(), 1093 Elab2->getQualifier())) 1094 return false; 1095 if (!IsStructurallyEquivalent(Context, Elab1->getNamedType(), 1096 Elab2->getNamedType())) 1097 return false; 1098 break; 1099 } 1100 1101 case Type::InjectedClassName: { 1102 const auto *Inj1 = cast<InjectedClassNameType>(T1); 1103 const auto *Inj2 = cast<InjectedClassNameType>(T2); 1104 if (!IsStructurallyEquivalent(Context, 1105 Inj1->getInjectedSpecializationType(), 1106 Inj2->getInjectedSpecializationType())) 1107 return false; 1108 break; 1109 } 1110 1111 case Type::DependentName: { 1112 const auto *Typename1 = cast<DependentNameType>(T1); 1113 const auto *Typename2 = cast<DependentNameType>(T2); 1114 if (!IsStructurallyEquivalent(Context, Typename1->getQualifier(), 1115 Typename2->getQualifier())) 1116 return false; 1117 if (!IsStructurallyEquivalent(Typename1->getIdentifier(), 1118 Typename2->getIdentifier())) 1119 return false; 1120 1121 break; 1122 } 1123 1124 case Type::DependentTemplateSpecialization: { 1125 const auto *Spec1 = cast<DependentTemplateSpecializationType>(T1); 1126 const auto *Spec2 = cast<DependentTemplateSpecializationType>(T2); 1127 if (!IsStructurallyEquivalent(Context, Spec1->getQualifier(), 1128 Spec2->getQualifier())) 1129 return false; 1130 if (!IsStructurallyEquivalent(Spec1->getIdentifier(), 1131 Spec2->getIdentifier())) 1132 return false; 1133 if (Spec1->getNumArgs() != Spec2->getNumArgs()) 1134 return false; 1135 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) { 1136 if (!IsStructurallyEquivalent(Context, Spec1->getArg(I), 1137 Spec2->getArg(I))) 1138 return false; 1139 } 1140 break; 1141 } 1142 1143 case Type::PackExpansion: 1144 if (!IsStructurallyEquivalent(Context, 1145 cast<PackExpansionType>(T1)->getPattern(), 1146 cast<PackExpansionType>(T2)->getPattern())) 1147 return false; 1148 break; 1149 1150 case Type::ObjCInterface: { 1151 const auto *Iface1 = cast<ObjCInterfaceType>(T1); 1152 const auto *Iface2 = cast<ObjCInterfaceType>(T2); 1153 if (!IsStructurallyEquivalent(Context, Iface1->getDecl(), 1154 Iface2->getDecl())) 1155 return false; 1156 break; 1157 } 1158 1159 case Type::ObjCTypeParam: { 1160 const auto *Obj1 = cast<ObjCTypeParamType>(T1); 1161 const auto *Obj2 = cast<ObjCTypeParamType>(T2); 1162 if (!IsStructurallyEquivalent(Context, Obj1->getDecl(), Obj2->getDecl())) 1163 return false; 1164 1165 if (Obj1->getNumProtocols() != Obj2->getNumProtocols()) 1166 return false; 1167 for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) { 1168 if (!IsStructurallyEquivalent(Context, Obj1->getProtocol(I), 1169 Obj2->getProtocol(I))) 1170 return false; 1171 } 1172 break; 1173 } 1174 1175 case Type::ObjCObject: { 1176 const auto *Obj1 = cast<ObjCObjectType>(T1); 1177 const auto *Obj2 = cast<ObjCObjectType>(T2); 1178 if (!IsStructurallyEquivalent(Context, Obj1->getBaseType(), 1179 Obj2->getBaseType())) 1180 return false; 1181 if (Obj1->getNumProtocols() != Obj2->getNumProtocols()) 1182 return false; 1183 for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) { 1184 if (!IsStructurallyEquivalent(Context, Obj1->getProtocol(I), 1185 Obj2->getProtocol(I))) 1186 return false; 1187 } 1188 break; 1189 } 1190 1191 case Type::ObjCObjectPointer: { 1192 const auto *Ptr1 = cast<ObjCObjectPointerType>(T1); 1193 const auto *Ptr2 = cast<ObjCObjectPointerType>(T2); 1194 if (!IsStructurallyEquivalent(Context, Ptr1->getPointeeType(), 1195 Ptr2->getPointeeType())) 1196 return false; 1197 break; 1198 } 1199 1200 case Type::Atomic: 1201 if (!IsStructurallyEquivalent(Context, cast<AtomicType>(T1)->getValueType(), 1202 cast<AtomicType>(T2)->getValueType())) 1203 return false; 1204 break; 1205 1206 case Type::Pipe: 1207 if (!IsStructurallyEquivalent(Context, cast<PipeType>(T1)->getElementType(), 1208 cast<PipeType>(T2)->getElementType())) 1209 return false; 1210 break; 1211 case Type::ExtInt: { 1212 const auto *Int1 = cast<ExtIntType>(T1); 1213 const auto *Int2 = cast<ExtIntType>(T2); 1214 1215 if (Int1->isUnsigned() != Int2->isUnsigned() || 1216 Int1->getNumBits() != Int2->getNumBits()) 1217 return false; 1218 break; 1219 } 1220 case Type::DependentExtInt: { 1221 const auto *Int1 = cast<DependentExtIntType>(T1); 1222 const auto *Int2 = cast<DependentExtIntType>(T2); 1223 1224 if (Int1->isUnsigned() != Int2->isUnsigned() || 1225 !IsStructurallyEquivalent(Context, Int1->getNumBitsExpr(), 1226 Int2->getNumBitsExpr())) 1227 return false; 1228 } 1229 } // end switch 1230 1231 return true; 1232 } 1233 1234 /// Determine structural equivalence of two fields. 1235 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 1236 FieldDecl *Field1, FieldDecl *Field2) { 1237 const auto *Owner2 = cast<RecordDecl>(Field2->getDeclContext()); 1238 1239 // For anonymous structs/unions, match up the anonymous struct/union type 1240 // declarations directly, so that we don't go off searching for anonymous 1241 // types 1242 if (Field1->isAnonymousStructOrUnion() && 1243 Field2->isAnonymousStructOrUnion()) { 1244 RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl(); 1245 RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl(); 1246 return IsStructurallyEquivalent(Context, D1, D2); 1247 } 1248 1249 // Check for equivalent field names. 1250 IdentifierInfo *Name1 = Field1->getIdentifier(); 1251 IdentifierInfo *Name2 = Field2->getIdentifier(); 1252 if (!::IsStructurallyEquivalent(Name1, Name2)) { 1253 if (Context.Complain) { 1254 Context.Diag2( 1255 Owner2->getLocation(), 1256 Context.getApplicableDiagnostic(diag::err_odr_tag_type_inconsistent)) 1257 << Context.ToCtx.getTypeDeclType(Owner2); 1258 Context.Diag2(Field2->getLocation(), diag::note_odr_field_name) 1259 << Field2->getDeclName(); 1260 Context.Diag1(Field1->getLocation(), diag::note_odr_field_name) 1261 << Field1->getDeclName(); 1262 } 1263 return false; 1264 } 1265 1266 if (!IsStructurallyEquivalent(Context, Field1->getType(), 1267 Field2->getType())) { 1268 if (Context.Complain) { 1269 Context.Diag2( 1270 Owner2->getLocation(), 1271 Context.getApplicableDiagnostic(diag::err_odr_tag_type_inconsistent)) 1272 << Context.ToCtx.getTypeDeclType(Owner2); 1273 Context.Diag2(Field2->getLocation(), diag::note_odr_field) 1274 << Field2->getDeclName() << Field2->getType(); 1275 Context.Diag1(Field1->getLocation(), diag::note_odr_field) 1276 << Field1->getDeclName() << Field1->getType(); 1277 } 1278 return false; 1279 } 1280 1281 if (Field1->isBitField()) 1282 return IsStructurallyEquivalent(Context, Field1->getBitWidth(), 1283 Field2->getBitWidth()); 1284 1285 return true; 1286 } 1287 1288 /// Determine structural equivalence of two methods. 1289 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 1290 CXXMethodDecl *Method1, 1291 CXXMethodDecl *Method2) { 1292 bool PropertiesEqual = 1293 Method1->getDeclKind() == Method2->getDeclKind() && 1294 Method1->getRefQualifier() == Method2->getRefQualifier() && 1295 Method1->getAccess() == Method2->getAccess() && 1296 Method1->getOverloadedOperator() == Method2->getOverloadedOperator() && 1297 Method1->isStatic() == Method2->isStatic() && 1298 Method1->isConst() == Method2->isConst() && 1299 Method1->isVolatile() == Method2->isVolatile() && 1300 Method1->isVirtual() == Method2->isVirtual() && 1301 Method1->isPure() == Method2->isPure() && 1302 Method1->isDefaulted() == Method2->isDefaulted() && 1303 Method1->isDeleted() == Method2->isDeleted(); 1304 if (!PropertiesEqual) 1305 return false; 1306 // FIXME: Check for 'final'. 1307 1308 if (auto *Constructor1 = dyn_cast<CXXConstructorDecl>(Method1)) { 1309 auto *Constructor2 = cast<CXXConstructorDecl>(Method2); 1310 if (!Constructor1->getExplicitSpecifier().isEquivalent( 1311 Constructor2->getExplicitSpecifier())) 1312 return false; 1313 } 1314 1315 if (auto *Conversion1 = dyn_cast<CXXConversionDecl>(Method1)) { 1316 auto *Conversion2 = cast<CXXConversionDecl>(Method2); 1317 if (!Conversion1->getExplicitSpecifier().isEquivalent( 1318 Conversion2->getExplicitSpecifier())) 1319 return false; 1320 if (!IsStructurallyEquivalent(Context, Conversion1->getConversionType(), 1321 Conversion2->getConversionType())) 1322 return false; 1323 } 1324 1325 const IdentifierInfo *Name1 = Method1->getIdentifier(); 1326 const IdentifierInfo *Name2 = Method2->getIdentifier(); 1327 if (!::IsStructurallyEquivalent(Name1, Name2)) { 1328 return false; 1329 // TODO: Names do not match, add warning like at check for FieldDecl. 1330 } 1331 1332 // Check the prototypes. 1333 if (!::IsStructurallyEquivalent(Context, 1334 Method1->getType(), Method2->getType())) 1335 return false; 1336 1337 return true; 1338 } 1339 1340 /// Determine structural equivalence of two lambda classes. 1341 static bool 1342 IsStructurallyEquivalentLambdas(StructuralEquivalenceContext &Context, 1343 CXXRecordDecl *D1, CXXRecordDecl *D2) { 1344 assert(D1->isLambda() && D2->isLambda() && 1345 "Must be called on lambda classes"); 1346 if (!IsStructurallyEquivalent(Context, D1->getLambdaCallOperator(), 1347 D2->getLambdaCallOperator())) 1348 return false; 1349 1350 return true; 1351 } 1352 1353 /// Determine structural equivalence of two records. 1354 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 1355 RecordDecl *D1, RecordDecl *D2) { 1356 1357 // Check for equivalent structure names. 1358 IdentifierInfo *Name1 = D1->getIdentifier(); 1359 if (!Name1 && D1->getTypedefNameForAnonDecl()) 1360 Name1 = D1->getTypedefNameForAnonDecl()->getIdentifier(); 1361 IdentifierInfo *Name2 = D2->getIdentifier(); 1362 if (!Name2 && D2->getTypedefNameForAnonDecl()) 1363 Name2 = D2->getTypedefNameForAnonDecl()->getIdentifier(); 1364 if (!IsStructurallyEquivalent(Name1, Name2)) 1365 return false; 1366 1367 if (D1->isUnion() != D2->isUnion()) { 1368 if (Context.Complain) { 1369 Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( 1370 diag::err_odr_tag_type_inconsistent)) 1371 << Context.ToCtx.getTypeDeclType(D2); 1372 Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here) 1373 << D1->getDeclName() << (unsigned)D1->getTagKind(); 1374 } 1375 return false; 1376 } 1377 1378 if (!D1->getDeclName() && !D2->getDeclName()) { 1379 // If both anonymous structs/unions are in a record context, make sure 1380 // they occur in the same location in the context records. 1381 if (Optional<unsigned> Index1 = 1382 StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(D1)) { 1383 if (Optional<unsigned> Index2 = 1384 StructuralEquivalenceContext::findUntaggedStructOrUnionIndex( 1385 D2)) { 1386 if (*Index1 != *Index2) 1387 return false; 1388 } 1389 } 1390 } 1391 1392 // If both declarations are class template specializations, we know 1393 // the ODR applies, so check the template and template arguments. 1394 const auto *Spec1 = dyn_cast<ClassTemplateSpecializationDecl>(D1); 1395 const auto *Spec2 = dyn_cast<ClassTemplateSpecializationDecl>(D2); 1396 if (Spec1 && Spec2) { 1397 // Check that the specialized templates are the same. 1398 if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(), 1399 Spec2->getSpecializedTemplate())) 1400 return false; 1401 1402 // Check that the template arguments are the same. 1403 if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size()) 1404 return false; 1405 1406 for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I) 1407 if (!IsStructurallyEquivalent(Context, Spec1->getTemplateArgs().get(I), 1408 Spec2->getTemplateArgs().get(I))) 1409 return false; 1410 } 1411 // If one is a class template specialization and the other is not, these 1412 // structures are different. 1413 else if (Spec1 || Spec2) 1414 return false; 1415 1416 // Compare the definitions of these two records. If either or both are 1417 // incomplete (i.e. it is a forward decl), we assume that they are 1418 // equivalent. 1419 D1 = D1->getDefinition(); 1420 D2 = D2->getDefinition(); 1421 if (!D1 || !D2) 1422 return true; 1423 1424 // If any of the records has external storage and we do a minimal check (or 1425 // AST import) we assume they are equivalent. (If we didn't have this 1426 // assumption then `RecordDecl::LoadFieldsFromExternalStorage` could trigger 1427 // another AST import which in turn would call the structural equivalency 1428 // check again and finally we'd have an improper result.) 1429 if (Context.EqKind == StructuralEquivalenceKind::Minimal) 1430 if (D1->hasExternalLexicalStorage() || D2->hasExternalLexicalStorage()) 1431 return true; 1432 1433 // If one definition is currently being defined, we do not compare for 1434 // equality and we assume that the decls are equal. 1435 if (D1->isBeingDefined() || D2->isBeingDefined()) 1436 return true; 1437 1438 if (auto *D1CXX = dyn_cast<CXXRecordDecl>(D1)) { 1439 if (auto *D2CXX = dyn_cast<CXXRecordDecl>(D2)) { 1440 if (D1CXX->hasExternalLexicalStorage() && 1441 !D1CXX->isCompleteDefinition()) { 1442 D1CXX->getASTContext().getExternalSource()->CompleteType(D1CXX); 1443 } 1444 1445 if (D1CXX->isLambda() != D2CXX->isLambda()) 1446 return false; 1447 if (D1CXX->isLambda()) { 1448 if (!IsStructurallyEquivalentLambdas(Context, D1CXX, D2CXX)) 1449 return false; 1450 } 1451 1452 if (D1CXX->getNumBases() != D2CXX->getNumBases()) { 1453 if (Context.Complain) { 1454 Context.Diag2(D2->getLocation(), 1455 Context.getApplicableDiagnostic( 1456 diag::err_odr_tag_type_inconsistent)) 1457 << Context.ToCtx.getTypeDeclType(D2); 1458 Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases) 1459 << D2CXX->getNumBases(); 1460 Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases) 1461 << D1CXX->getNumBases(); 1462 } 1463 return false; 1464 } 1465 1466 // Check the base classes. 1467 for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(), 1468 BaseEnd1 = D1CXX->bases_end(), 1469 Base2 = D2CXX->bases_begin(); 1470 Base1 != BaseEnd1; ++Base1, ++Base2) { 1471 if (!IsStructurallyEquivalent(Context, Base1->getType(), 1472 Base2->getType())) { 1473 if (Context.Complain) { 1474 Context.Diag2(D2->getLocation(), 1475 Context.getApplicableDiagnostic( 1476 diag::err_odr_tag_type_inconsistent)) 1477 << Context.ToCtx.getTypeDeclType(D2); 1478 Context.Diag2(Base2->getBeginLoc(), diag::note_odr_base) 1479 << Base2->getType() << Base2->getSourceRange(); 1480 Context.Diag1(Base1->getBeginLoc(), diag::note_odr_base) 1481 << Base1->getType() << Base1->getSourceRange(); 1482 } 1483 return false; 1484 } 1485 1486 // Check virtual vs. non-virtual inheritance mismatch. 1487 if (Base1->isVirtual() != Base2->isVirtual()) { 1488 if (Context.Complain) { 1489 Context.Diag2(D2->getLocation(), 1490 Context.getApplicableDiagnostic( 1491 diag::err_odr_tag_type_inconsistent)) 1492 << Context.ToCtx.getTypeDeclType(D2); 1493 Context.Diag2(Base2->getBeginLoc(), diag::note_odr_virtual_base) 1494 << Base2->isVirtual() << Base2->getSourceRange(); 1495 Context.Diag1(Base1->getBeginLoc(), diag::note_odr_base) 1496 << Base1->isVirtual() << Base1->getSourceRange(); 1497 } 1498 return false; 1499 } 1500 } 1501 1502 // Check the friends for consistency. 1503 CXXRecordDecl::friend_iterator Friend2 = D2CXX->friend_begin(), 1504 Friend2End = D2CXX->friend_end(); 1505 for (CXXRecordDecl::friend_iterator Friend1 = D1CXX->friend_begin(), 1506 Friend1End = D1CXX->friend_end(); 1507 Friend1 != Friend1End; ++Friend1, ++Friend2) { 1508 if (Friend2 == Friend2End) { 1509 if (Context.Complain) { 1510 Context.Diag2(D2->getLocation(), 1511 Context.getApplicableDiagnostic( 1512 diag::err_odr_tag_type_inconsistent)) 1513 << Context.ToCtx.getTypeDeclType(D2CXX); 1514 Context.Diag1((*Friend1)->getFriendLoc(), diag::note_odr_friend); 1515 Context.Diag2(D2->getLocation(), diag::note_odr_missing_friend); 1516 } 1517 return false; 1518 } 1519 1520 if (!IsStructurallyEquivalent(Context, *Friend1, *Friend2)) { 1521 if (Context.Complain) { 1522 Context.Diag2(D2->getLocation(), 1523 Context.getApplicableDiagnostic( 1524 diag::err_odr_tag_type_inconsistent)) 1525 << Context.ToCtx.getTypeDeclType(D2CXX); 1526 Context.Diag1((*Friend1)->getFriendLoc(), diag::note_odr_friend); 1527 Context.Diag2((*Friend2)->getFriendLoc(), diag::note_odr_friend); 1528 } 1529 return false; 1530 } 1531 } 1532 1533 if (Friend2 != Friend2End) { 1534 if (Context.Complain) { 1535 Context.Diag2(D2->getLocation(), 1536 Context.getApplicableDiagnostic( 1537 diag::err_odr_tag_type_inconsistent)) 1538 << Context.ToCtx.getTypeDeclType(D2); 1539 Context.Diag2((*Friend2)->getFriendLoc(), diag::note_odr_friend); 1540 Context.Diag1(D1->getLocation(), diag::note_odr_missing_friend); 1541 } 1542 return false; 1543 } 1544 } else if (D1CXX->getNumBases() > 0) { 1545 if (Context.Complain) { 1546 Context.Diag2(D2->getLocation(), 1547 Context.getApplicableDiagnostic( 1548 diag::err_odr_tag_type_inconsistent)) 1549 << Context.ToCtx.getTypeDeclType(D2); 1550 const CXXBaseSpecifier *Base1 = D1CXX->bases_begin(); 1551 Context.Diag1(Base1->getBeginLoc(), diag::note_odr_base) 1552 << Base1->getType() << Base1->getSourceRange(); 1553 Context.Diag2(D2->getLocation(), diag::note_odr_missing_base); 1554 } 1555 return false; 1556 } 1557 } 1558 1559 // Check the fields for consistency. 1560 RecordDecl::field_iterator Field2 = D2->field_begin(), 1561 Field2End = D2->field_end(); 1562 for (RecordDecl::field_iterator Field1 = D1->field_begin(), 1563 Field1End = D1->field_end(); 1564 Field1 != Field1End; ++Field1, ++Field2) { 1565 if (Field2 == Field2End) { 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.Diag1(Field1->getLocation(), diag::note_odr_field) 1572 << Field1->getDeclName() << Field1->getType(); 1573 Context.Diag2(D2->getLocation(), diag::note_odr_missing_field); 1574 } 1575 return false; 1576 } 1577 1578 if (!IsStructurallyEquivalent(Context, *Field1, *Field2)) 1579 return false; 1580 } 1581 1582 if (Field2 != Field2End) { 1583 if (Context.Complain) { 1584 Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( 1585 diag::err_odr_tag_type_inconsistent)) 1586 << Context.ToCtx.getTypeDeclType(D2); 1587 Context.Diag2(Field2->getLocation(), diag::note_odr_field) 1588 << Field2->getDeclName() << Field2->getType(); 1589 Context.Diag1(D1->getLocation(), diag::note_odr_missing_field); 1590 } 1591 return false; 1592 } 1593 1594 return true; 1595 } 1596 1597 /// Determine structural equivalence of two enums. 1598 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 1599 EnumDecl *D1, EnumDecl *D2) { 1600 1601 // Check for equivalent enum names. 1602 IdentifierInfo *Name1 = D1->getIdentifier(); 1603 if (!Name1 && D1->getTypedefNameForAnonDecl()) 1604 Name1 = D1->getTypedefNameForAnonDecl()->getIdentifier(); 1605 IdentifierInfo *Name2 = D2->getIdentifier(); 1606 if (!Name2 && D2->getTypedefNameForAnonDecl()) 1607 Name2 = D2->getTypedefNameForAnonDecl()->getIdentifier(); 1608 if (!IsStructurallyEquivalent(Name1, Name2)) 1609 return false; 1610 1611 // Compare the definitions of these two enums. If either or both are 1612 // incomplete (i.e. forward declared), we assume that they are equivalent. 1613 D1 = D1->getDefinition(); 1614 D2 = D2->getDefinition(); 1615 if (!D1 || !D2) 1616 return true; 1617 1618 EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(), 1619 EC2End = D2->enumerator_end(); 1620 for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(), 1621 EC1End = D1->enumerator_end(); 1622 EC1 != EC1End; ++EC1, ++EC2) { 1623 if (EC2 == EC2End) { 1624 if (Context.Complain) { 1625 Context.Diag2(D2->getLocation(), 1626 Context.getApplicableDiagnostic( 1627 diag::err_odr_tag_type_inconsistent)) 1628 << Context.ToCtx.getTypeDeclType(D2); 1629 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator) 1630 << EC1->getDeclName() << EC1->getInitVal().toString(10); 1631 Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator); 1632 } 1633 return false; 1634 } 1635 1636 llvm::APSInt Val1 = EC1->getInitVal(); 1637 llvm::APSInt Val2 = EC2->getInitVal(); 1638 if (!llvm::APSInt::isSameValue(Val1, Val2) || 1639 !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) { 1640 if (Context.Complain) { 1641 Context.Diag2(D2->getLocation(), 1642 Context.getApplicableDiagnostic( 1643 diag::err_odr_tag_type_inconsistent)) 1644 << Context.ToCtx.getTypeDeclType(D2); 1645 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator) 1646 << EC2->getDeclName() << EC2->getInitVal().toString(10); 1647 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator) 1648 << EC1->getDeclName() << EC1->getInitVal().toString(10); 1649 } 1650 return false; 1651 } 1652 } 1653 1654 if (EC2 != EC2End) { 1655 if (Context.Complain) { 1656 Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( 1657 diag::err_odr_tag_type_inconsistent)) 1658 << Context.ToCtx.getTypeDeclType(D2); 1659 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator) 1660 << EC2->getDeclName() << EC2->getInitVal().toString(10); 1661 Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator); 1662 } 1663 return false; 1664 } 1665 1666 return true; 1667 } 1668 1669 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 1670 TemplateParameterList *Params1, 1671 TemplateParameterList *Params2) { 1672 if (Params1->size() != Params2->size()) { 1673 if (Context.Complain) { 1674 Context.Diag2(Params2->getTemplateLoc(), 1675 Context.getApplicableDiagnostic( 1676 diag::err_odr_different_num_template_parameters)) 1677 << Params1->size() << Params2->size(); 1678 Context.Diag1(Params1->getTemplateLoc(), 1679 diag::note_odr_template_parameter_list); 1680 } 1681 return false; 1682 } 1683 1684 for (unsigned I = 0, N = Params1->size(); I != N; ++I) { 1685 if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) { 1686 if (Context.Complain) { 1687 Context.Diag2(Params2->getParam(I)->getLocation(), 1688 Context.getApplicableDiagnostic( 1689 diag::err_odr_different_template_parameter_kind)); 1690 Context.Diag1(Params1->getParam(I)->getLocation(), 1691 diag::note_odr_template_parameter_here); 1692 } 1693 return false; 1694 } 1695 1696 if (!IsStructurallyEquivalent(Context, Params1->getParam(I), 1697 Params2->getParam(I))) 1698 return false; 1699 } 1700 1701 return true; 1702 } 1703 1704 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 1705 TemplateTypeParmDecl *D1, 1706 TemplateTypeParmDecl *D2) { 1707 if (D1->isParameterPack() != D2->isParameterPack()) { 1708 if (Context.Complain) { 1709 Context.Diag2(D2->getLocation(), 1710 Context.getApplicableDiagnostic( 1711 diag::err_odr_parameter_pack_non_pack)) 1712 << D2->isParameterPack(); 1713 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack) 1714 << D1->isParameterPack(); 1715 } 1716 return false; 1717 } 1718 1719 return true; 1720 } 1721 1722 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 1723 NonTypeTemplateParmDecl *D1, 1724 NonTypeTemplateParmDecl *D2) { 1725 if (D1->isParameterPack() != D2->isParameterPack()) { 1726 if (Context.Complain) { 1727 Context.Diag2(D2->getLocation(), 1728 Context.getApplicableDiagnostic( 1729 diag::err_odr_parameter_pack_non_pack)) 1730 << D2->isParameterPack(); 1731 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack) 1732 << D1->isParameterPack(); 1733 } 1734 return false; 1735 } 1736 1737 // Check types. 1738 if (!IsStructurallyEquivalent(Context, D1->getType(), D2->getType())) { 1739 if (Context.Complain) { 1740 Context.Diag2(D2->getLocation(), 1741 Context.getApplicableDiagnostic( 1742 diag::err_odr_non_type_parameter_type_inconsistent)) 1743 << D2->getType() << D1->getType(); 1744 Context.Diag1(D1->getLocation(), diag::note_odr_value_here) 1745 << D1->getType(); 1746 } 1747 return false; 1748 } 1749 1750 return true; 1751 } 1752 1753 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 1754 TemplateTemplateParmDecl *D1, 1755 TemplateTemplateParmDecl *D2) { 1756 if (D1->isParameterPack() != D2->isParameterPack()) { 1757 if (Context.Complain) { 1758 Context.Diag2(D2->getLocation(), 1759 Context.getApplicableDiagnostic( 1760 diag::err_odr_parameter_pack_non_pack)) 1761 << D2->isParameterPack(); 1762 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack) 1763 << D1->isParameterPack(); 1764 } 1765 return false; 1766 } 1767 1768 // Check template parameter lists. 1769 return IsStructurallyEquivalent(Context, D1->getTemplateParameters(), 1770 D2->getTemplateParameters()); 1771 } 1772 1773 static bool IsTemplateDeclCommonStructurallyEquivalent( 1774 StructuralEquivalenceContext &Ctx, TemplateDecl *D1, TemplateDecl *D2) { 1775 if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier())) 1776 return false; 1777 if (!D1->getIdentifier()) // Special name 1778 if (D1->getNameAsString() != D2->getNameAsString()) 1779 return false; 1780 return IsStructurallyEquivalent(Ctx, D1->getTemplateParameters(), 1781 D2->getTemplateParameters()); 1782 } 1783 1784 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 1785 ClassTemplateDecl *D1, 1786 ClassTemplateDecl *D2) { 1787 // Check template parameters. 1788 if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2)) 1789 return false; 1790 1791 // Check the templated declaration. 1792 return IsStructurallyEquivalent(Context, D1->getTemplatedDecl(), 1793 D2->getTemplatedDecl()); 1794 } 1795 1796 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 1797 FunctionTemplateDecl *D1, 1798 FunctionTemplateDecl *D2) { 1799 // Check template parameters. 1800 if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2)) 1801 return false; 1802 1803 // Check the templated declaration. 1804 return IsStructurallyEquivalent(Context, D1->getTemplatedDecl()->getType(), 1805 D2->getTemplatedDecl()->getType()); 1806 } 1807 1808 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 1809 ConceptDecl *D1, 1810 ConceptDecl *D2) { 1811 // Check template parameters. 1812 if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2)) 1813 return false; 1814 1815 // Check the constraint expression. 1816 return IsStructurallyEquivalent(Context, D1->getConstraintExpr(), 1817 D2->getConstraintExpr()); 1818 } 1819 1820 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 1821 FriendDecl *D1, FriendDecl *D2) { 1822 if ((D1->getFriendType() && D2->getFriendDecl()) || 1823 (D1->getFriendDecl() && D2->getFriendType())) { 1824 return false; 1825 } 1826 if (D1->getFriendType() && D2->getFriendType()) 1827 return IsStructurallyEquivalent(Context, 1828 D1->getFriendType()->getType(), 1829 D2->getFriendType()->getType()); 1830 if (D1->getFriendDecl() && D2->getFriendDecl()) 1831 return IsStructurallyEquivalent(Context, D1->getFriendDecl(), 1832 D2->getFriendDecl()); 1833 return false; 1834 } 1835 1836 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 1837 TypedefNameDecl *D1, TypedefNameDecl *D2) { 1838 if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier())) 1839 return false; 1840 1841 return IsStructurallyEquivalent(Context, D1->getUnderlyingType(), 1842 D2->getUnderlyingType()); 1843 } 1844 1845 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 1846 FunctionDecl *D1, FunctionDecl *D2) { 1847 if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier())) 1848 return false; 1849 1850 if (D1->isOverloadedOperator()) { 1851 if (!D2->isOverloadedOperator()) 1852 return false; 1853 if (D1->getOverloadedOperator() != D2->getOverloadedOperator()) 1854 return false; 1855 } 1856 1857 // FIXME: Consider checking for function attributes as well. 1858 if (!IsStructurallyEquivalent(Context, D1->getType(), D2->getType())) 1859 return false; 1860 1861 return true; 1862 } 1863 1864 /// Determine structural equivalence of two declarations. 1865 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, 1866 Decl *D1, Decl *D2) { 1867 // FIXME: Check for known structural equivalences via a callback of some sort. 1868 1869 D1 = D1->getCanonicalDecl(); 1870 D2 = D2->getCanonicalDecl(); 1871 std::pair<Decl *, Decl *> P{D1, D2}; 1872 1873 // Check whether we already know that these two declarations are not 1874 // structurally equivalent. 1875 if (Context.NonEquivalentDecls.count(P)) 1876 return false; 1877 1878 // Check if a check for these declarations is already pending. 1879 // If yes D1 and D2 will be checked later (from DeclsToCheck), 1880 // or these are already checked (and equivalent). 1881 bool Inserted = Context.VisitedDecls.insert(P).second; 1882 if (!Inserted) 1883 return true; 1884 1885 Context.DeclsToCheck.push(P); 1886 1887 return true; 1888 } 1889 1890 DiagnosticBuilder StructuralEquivalenceContext::Diag1(SourceLocation Loc, 1891 unsigned DiagID) { 1892 assert(Complain && "Not allowed to complain"); 1893 if (LastDiagFromC2) 1894 FromCtx.getDiagnostics().notePriorDiagnosticFrom(ToCtx.getDiagnostics()); 1895 LastDiagFromC2 = false; 1896 return FromCtx.getDiagnostics().Report(Loc, DiagID); 1897 } 1898 1899 DiagnosticBuilder StructuralEquivalenceContext::Diag2(SourceLocation Loc, 1900 unsigned DiagID) { 1901 assert(Complain && "Not allowed to complain"); 1902 if (!LastDiagFromC2) 1903 ToCtx.getDiagnostics().notePriorDiagnosticFrom(FromCtx.getDiagnostics()); 1904 LastDiagFromC2 = true; 1905 return ToCtx.getDiagnostics().Report(Loc, DiagID); 1906 } 1907 1908 Optional<unsigned> 1909 StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(RecordDecl *Anon) { 1910 ASTContext &Context = Anon->getASTContext(); 1911 QualType AnonTy = Context.getRecordType(Anon); 1912 1913 const auto *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext()); 1914 if (!Owner) 1915 return None; 1916 1917 unsigned Index = 0; 1918 for (const auto *D : Owner->noload_decls()) { 1919 const auto *F = dyn_cast<FieldDecl>(D); 1920 if (!F) 1921 continue; 1922 1923 if (F->isAnonymousStructOrUnion()) { 1924 if (Context.hasSameType(F->getType(), AnonTy)) 1925 break; 1926 ++Index; 1927 continue; 1928 } 1929 1930 // If the field looks like this: 1931 // struct { ... } A; 1932 QualType FieldType = F->getType(); 1933 // In case of nested structs. 1934 while (const auto *ElabType = dyn_cast<ElaboratedType>(FieldType)) 1935 FieldType = ElabType->getNamedType(); 1936 1937 if (const auto *RecType = dyn_cast<RecordType>(FieldType)) { 1938 const RecordDecl *RecDecl = RecType->getDecl(); 1939 if (RecDecl->getDeclContext() == Owner && !RecDecl->getIdentifier()) { 1940 if (Context.hasSameType(FieldType, AnonTy)) 1941 break; 1942 ++Index; 1943 continue; 1944 } 1945 } 1946 } 1947 1948 return Index; 1949 } 1950 1951 unsigned StructuralEquivalenceContext::getApplicableDiagnostic( 1952 unsigned ErrorDiagnostic) { 1953 if (ErrorOnTagTypeMismatch) 1954 return ErrorDiagnostic; 1955 1956 switch (ErrorDiagnostic) { 1957 case diag::err_odr_variable_type_inconsistent: 1958 return diag::warn_odr_variable_type_inconsistent; 1959 case diag::err_odr_variable_multiple_def: 1960 return diag::warn_odr_variable_multiple_def; 1961 case diag::err_odr_function_type_inconsistent: 1962 return diag::warn_odr_function_type_inconsistent; 1963 case diag::err_odr_tag_type_inconsistent: 1964 return diag::warn_odr_tag_type_inconsistent; 1965 case diag::err_odr_field_type_inconsistent: 1966 return diag::warn_odr_field_type_inconsistent; 1967 case diag::err_odr_ivar_type_inconsistent: 1968 return diag::warn_odr_ivar_type_inconsistent; 1969 case diag::err_odr_objc_superclass_inconsistent: 1970 return diag::warn_odr_objc_superclass_inconsistent; 1971 case diag::err_odr_objc_method_result_type_inconsistent: 1972 return diag::warn_odr_objc_method_result_type_inconsistent; 1973 case diag::err_odr_objc_method_num_params_inconsistent: 1974 return diag::warn_odr_objc_method_num_params_inconsistent; 1975 case diag::err_odr_objc_method_param_type_inconsistent: 1976 return diag::warn_odr_objc_method_param_type_inconsistent; 1977 case diag::err_odr_objc_method_variadic_inconsistent: 1978 return diag::warn_odr_objc_method_variadic_inconsistent; 1979 case diag::err_odr_objc_property_type_inconsistent: 1980 return diag::warn_odr_objc_property_type_inconsistent; 1981 case diag::err_odr_objc_property_impl_kind_inconsistent: 1982 return diag::warn_odr_objc_property_impl_kind_inconsistent; 1983 case diag::err_odr_objc_synthesize_ivar_inconsistent: 1984 return diag::warn_odr_objc_synthesize_ivar_inconsistent; 1985 case diag::err_odr_different_num_template_parameters: 1986 return diag::warn_odr_different_num_template_parameters; 1987 case diag::err_odr_different_template_parameter_kind: 1988 return diag::warn_odr_different_template_parameter_kind; 1989 case diag::err_odr_parameter_pack_non_pack: 1990 return diag::warn_odr_parameter_pack_non_pack; 1991 case diag::err_odr_non_type_parameter_type_inconsistent: 1992 return diag::warn_odr_non_type_parameter_type_inconsistent; 1993 } 1994 llvm_unreachable("Diagnostic kind not handled in preceding switch"); 1995 } 1996 1997 bool StructuralEquivalenceContext::IsEquivalent(Decl *D1, Decl *D2) { 1998 1999 // Ensure that the implementation functions (all static functions in this TU) 2000 // never call the public ASTStructuralEquivalence::IsEquivalent() functions, 2001 // because that will wreak havoc the internal state (DeclsToCheck and 2002 // VisitedDecls members) and can cause faulty behaviour. 2003 // In other words: Do not start a graph search from a new node with the 2004 // internal data of another search in progress. 2005 // FIXME: Better encapsulation and separation of internal and public 2006 // functionality. 2007 assert(DeclsToCheck.empty()); 2008 assert(VisitedDecls.empty()); 2009 2010 if (!::IsStructurallyEquivalent(*this, D1, D2)) 2011 return false; 2012 2013 return !Finish(); 2014 } 2015 2016 bool StructuralEquivalenceContext::IsEquivalent(QualType T1, QualType T2) { 2017 assert(DeclsToCheck.empty()); 2018 assert(VisitedDecls.empty()); 2019 if (!::IsStructurallyEquivalent(*this, T1, T2)) 2020 return false; 2021 2022 return !Finish(); 2023 } 2024 2025 bool StructuralEquivalenceContext::IsEquivalent(Stmt *S1, Stmt *S2) { 2026 assert(DeclsToCheck.empty()); 2027 assert(VisitedDecls.empty()); 2028 if (!::IsStructurallyEquivalent(*this, S1, S2)) 2029 return false; 2030 2031 return !Finish(); 2032 } 2033 2034 bool StructuralEquivalenceContext::CheckCommonEquivalence(Decl *D1, Decl *D2) { 2035 // Check for equivalent described template. 2036 TemplateDecl *Template1 = D1->getDescribedTemplate(); 2037 TemplateDecl *Template2 = D2->getDescribedTemplate(); 2038 if ((Template1 != nullptr) != (Template2 != nullptr)) 2039 return false; 2040 if (Template1 && !IsStructurallyEquivalent(*this, Template1, Template2)) 2041 return false; 2042 2043 // FIXME: Move check for identifier names into this function. 2044 2045 return true; 2046 } 2047 2048 bool StructuralEquivalenceContext::CheckKindSpecificEquivalence( 2049 Decl *D1, Decl *D2) { 2050 2051 // Kind mismatch. 2052 if (D1->getKind() != D2->getKind()) 2053 return false; 2054 2055 // Cast the Decls to their actual subclass so that the right overload of 2056 // IsStructurallyEquivalent is called. 2057 switch (D1->getKind()) { 2058 #define ABSTRACT_DECL(DECL) 2059 #define DECL(DERIVED, BASE) \ 2060 case Decl::Kind::DERIVED: \ 2061 return ::IsStructurallyEquivalent(*this, static_cast<DERIVED##Decl *>(D1), \ 2062 static_cast<DERIVED##Decl *>(D2)); 2063 #include "clang/AST/DeclNodes.inc" 2064 } 2065 return true; 2066 } 2067 2068 bool StructuralEquivalenceContext::Finish() { 2069 while (!DeclsToCheck.empty()) { 2070 // Check the next declaration. 2071 std::pair<Decl *, Decl *> P = DeclsToCheck.front(); 2072 DeclsToCheck.pop(); 2073 2074 Decl *D1 = P.first; 2075 Decl *D2 = P.second; 2076 2077 bool Equivalent = 2078 CheckCommonEquivalence(D1, D2) && CheckKindSpecificEquivalence(D1, D2); 2079 2080 if (!Equivalent) { 2081 // Note that these two declarations are not equivalent (and we already 2082 // know about it). 2083 NonEquivalentDecls.insert(P); 2084 2085 return true; 2086 } 2087 } 2088 2089 return false; 2090 } 2091