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