]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/AST/ASTStructuralEquivalence.cpp
Upgrade to OpenSSH 7.8p1.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / AST / ASTStructuralEquivalence.cpp
1 //===--- ASTStructuralEquivalence.cpp - -------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implement StructuralEquivalenceContext class and helper functions
11 //  for layout matching.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "clang/AST/ASTStructuralEquivalence.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTDiagnostic.h"
18 #include "clang/AST/ASTImporter.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclVisitor.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/AST/TypeVisitor.h"
24 #include "clang/Basic/SourceManager.h"
25
26 namespace {
27
28 using namespace clang;
29
30 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
31                                      QualType T1, QualType T2);
32 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
33                                      Decl *D1, Decl *D2);
34 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
35                                      const TemplateArgument &Arg1,
36                                      const TemplateArgument &Arg2);
37
38 /// Determine structural equivalence of two expressions.
39 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
40                                      Expr *E1, Expr *E2) {
41   if (!E1 || !E2)
42     return E1 == E2;
43
44   // FIXME: Actually perform a structural comparison!
45   return true;
46 }
47
48 /// Determine whether two identifiers are equivalent.
49 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
50                                      const IdentifierInfo *Name2) {
51   if (!Name1 || !Name2)
52     return Name1 == Name2;
53
54   return Name1->getName() == Name2->getName();
55 }
56
57 /// Determine whether two nested-name-specifiers are equivalent.
58 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
59                                      NestedNameSpecifier *NNS1,
60                                      NestedNameSpecifier *NNS2) {
61   if (NNS1->getKind() != NNS2->getKind())
62     return false;
63
64   NestedNameSpecifier *Prefix1 = NNS1->getPrefix(),
65                       *Prefix2 = NNS2->getPrefix();
66   if ((bool)Prefix1 != (bool)Prefix2)
67     return false;
68
69   if (Prefix1)
70     if (!IsStructurallyEquivalent(Context, Prefix1, Prefix2))
71       return false;
72
73   switch (NNS1->getKind()) {
74   case NestedNameSpecifier::Identifier:
75     return IsStructurallyEquivalent(NNS1->getAsIdentifier(),
76                                     NNS2->getAsIdentifier());
77   case NestedNameSpecifier::Namespace:
78     return IsStructurallyEquivalent(Context, NNS1->getAsNamespace(),
79                                     NNS2->getAsNamespace());
80   case NestedNameSpecifier::NamespaceAlias:
81     return IsStructurallyEquivalent(Context, NNS1->getAsNamespaceAlias(),
82                                     NNS2->getAsNamespaceAlias());
83   case NestedNameSpecifier::TypeSpec:
84   case NestedNameSpecifier::TypeSpecWithTemplate:
85     return IsStructurallyEquivalent(Context, QualType(NNS1->getAsType(), 0),
86                                     QualType(NNS2->getAsType(), 0));
87   case NestedNameSpecifier::Global:
88     return true;
89   case NestedNameSpecifier::Super:
90     return IsStructurallyEquivalent(Context, NNS1->getAsRecordDecl(),
91                                     NNS2->getAsRecordDecl());
92   }
93   return false;
94 }
95
96 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
97                                      const TemplateName &N1,
98                                      const TemplateName &N2) {
99   if (N1.getKind() != N2.getKind())
100     return false;
101   switch (N1.getKind()) {
102   case TemplateName::Template:
103     return IsStructurallyEquivalent(Context, N1.getAsTemplateDecl(),
104                                     N2.getAsTemplateDecl());
105
106   case TemplateName::OverloadedTemplate: {
107     OverloadedTemplateStorage *OS1 = N1.getAsOverloadedTemplate(),
108                               *OS2 = N2.getAsOverloadedTemplate();
109     OverloadedTemplateStorage::iterator I1 = OS1->begin(), I2 = OS2->begin(),
110                                         E1 = OS1->end(), E2 = OS2->end();
111     for (; I1 != E1 && I2 != E2; ++I1, ++I2)
112       if (!IsStructurallyEquivalent(Context, *I1, *I2))
113         return false;
114     return I1 == E1 && I2 == E2;
115   }
116
117   case TemplateName::QualifiedTemplate: {
118     QualifiedTemplateName *QN1 = N1.getAsQualifiedTemplateName(),
119                           *QN2 = N2.getAsQualifiedTemplateName();
120     return IsStructurallyEquivalent(Context, QN1->getDecl(), QN2->getDecl()) &&
121            IsStructurallyEquivalent(Context, QN1->getQualifier(),
122                                     QN2->getQualifier());
123   }
124
125   case TemplateName::DependentTemplate: {
126     DependentTemplateName *DN1 = N1.getAsDependentTemplateName(),
127                           *DN2 = N2.getAsDependentTemplateName();
128     if (!IsStructurallyEquivalent(Context, DN1->getQualifier(),
129                                   DN2->getQualifier()))
130       return false;
131     if (DN1->isIdentifier() && DN2->isIdentifier())
132       return IsStructurallyEquivalent(DN1->getIdentifier(),
133                                       DN2->getIdentifier());
134     else if (DN1->isOverloadedOperator() && DN2->isOverloadedOperator())
135       return DN1->getOperator() == DN2->getOperator();
136     return false;
137   }
138
139   case TemplateName::SubstTemplateTemplateParm: {
140     SubstTemplateTemplateParmStorage *TS1 = N1.getAsSubstTemplateTemplateParm(),
141                                      *TS2 = N2.getAsSubstTemplateTemplateParm();
142     return IsStructurallyEquivalent(Context, TS1->getParameter(),
143                                     TS2->getParameter()) &&
144            IsStructurallyEquivalent(Context, TS1->getReplacement(),
145                                     TS2->getReplacement());
146   }
147   case TemplateName::SubstTemplateTemplateParmPack: {
148     SubstTemplateTemplateParmPackStorage
149         *P1 = N1.getAsSubstTemplateTemplateParmPack(),
150         *P2 = N2.getAsSubstTemplateTemplateParmPack();
151     return IsStructurallyEquivalent(Context, P1->getArgumentPack(),
152                                     P2->getArgumentPack()) &&
153            IsStructurallyEquivalent(Context, P1->getParameterPack(),
154                                     P2->getParameterPack());
155   }
156   }
157   return false;
158 }
159
160 /// Determine whether two template arguments are equivalent.
161 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
162                                      const TemplateArgument &Arg1,
163                                      const TemplateArgument &Arg2) {
164   if (Arg1.getKind() != Arg2.getKind())
165     return false;
166
167   switch (Arg1.getKind()) {
168   case TemplateArgument::Null:
169     return true;
170
171   case TemplateArgument::Type:
172     return Context.IsStructurallyEquivalent(Arg1.getAsType(), Arg2.getAsType());
173
174   case TemplateArgument::Integral:
175     if (!Context.IsStructurallyEquivalent(Arg1.getIntegralType(),
176                                           Arg2.getIntegralType()))
177       return false;
178
179     return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
180                                      Arg2.getAsIntegral());
181
182   case TemplateArgument::Declaration:
183     return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDecl());
184
185   case TemplateArgument::NullPtr:
186     return true; // FIXME: Is this correct?
187
188   case TemplateArgument::Template:
189     return IsStructurallyEquivalent(Context, Arg1.getAsTemplate(),
190                                     Arg2.getAsTemplate());
191
192   case TemplateArgument::TemplateExpansion:
193     return IsStructurallyEquivalent(Context,
194                                     Arg1.getAsTemplateOrTemplatePattern(),
195                                     Arg2.getAsTemplateOrTemplatePattern());
196
197   case TemplateArgument::Expression:
198     return IsStructurallyEquivalent(Context, Arg1.getAsExpr(),
199                                     Arg2.getAsExpr());
200
201   case TemplateArgument::Pack:
202     if (Arg1.pack_size() != Arg2.pack_size())
203       return false;
204
205     for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I)
206       if (!IsStructurallyEquivalent(Context, Arg1.pack_begin()[I],
207                                     Arg2.pack_begin()[I]))
208         return false;
209
210     return true;
211   }
212
213   llvm_unreachable("Invalid template argument kind");
214 }
215
216 /// Determine structural equivalence for the common part of array
217 /// types.
218 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
219                                           const ArrayType *Array1,
220                                           const ArrayType *Array2) {
221   if (!IsStructurallyEquivalent(Context, Array1->getElementType(),
222                                 Array2->getElementType()))
223     return false;
224   if (Array1->getSizeModifier() != Array2->getSizeModifier())
225     return false;
226   if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
227     return false;
228
229   return true;
230 }
231
232 /// Determine structural equivalence of two types.
233 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
234                                      QualType T1, QualType T2) {
235   if (T1.isNull() || T2.isNull())
236     return T1.isNull() && T2.isNull();
237
238   if (!Context.StrictTypeSpelling) {
239     // We aren't being strict about token-to-token equivalence of types,
240     // so map down to the canonical type.
241     T1 = Context.FromCtx.getCanonicalType(T1);
242     T2 = Context.ToCtx.getCanonicalType(T2);
243   }
244
245   if (T1.getQualifiers() != T2.getQualifiers())
246     return false;
247
248   Type::TypeClass TC = T1->getTypeClass();
249
250   if (T1->getTypeClass() != T2->getTypeClass()) {
251     // Compare function types with prototypes vs. without prototypes as if
252     // both did not have prototypes.
253     if (T1->getTypeClass() == Type::FunctionProto &&
254         T2->getTypeClass() == Type::FunctionNoProto)
255       TC = Type::FunctionNoProto;
256     else if (T1->getTypeClass() == Type::FunctionNoProto &&
257              T2->getTypeClass() == Type::FunctionProto)
258       TC = Type::FunctionNoProto;
259     else
260       return false;
261   }
262
263   switch (TC) {
264   case Type::Builtin:
265     // FIXME: Deal with Char_S/Char_U.
266     if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
267       return false;
268     break;
269
270   case Type::Complex:
271     if (!IsStructurallyEquivalent(Context,
272                                   cast<ComplexType>(T1)->getElementType(),
273                                   cast<ComplexType>(T2)->getElementType()))
274       return false;
275     break;
276
277   case Type::Adjusted:
278   case Type::Decayed:
279     if (!IsStructurallyEquivalent(Context,
280                                   cast<AdjustedType>(T1)->getOriginalType(),
281                                   cast<AdjustedType>(T2)->getOriginalType()))
282       return false;
283     break;
284
285   case Type::Pointer:
286     if (!IsStructurallyEquivalent(Context,
287                                   cast<PointerType>(T1)->getPointeeType(),
288                                   cast<PointerType>(T2)->getPointeeType()))
289       return false;
290     break;
291
292   case Type::BlockPointer:
293     if (!IsStructurallyEquivalent(Context,
294                                   cast<BlockPointerType>(T1)->getPointeeType(),
295                                   cast<BlockPointerType>(T2)->getPointeeType()))
296       return false;
297     break;
298
299   case Type::LValueReference:
300   case Type::RValueReference: {
301     const ReferenceType *Ref1 = cast<ReferenceType>(T1);
302     const ReferenceType *Ref2 = cast<ReferenceType>(T2);
303     if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
304       return false;
305     if (Ref1->isInnerRef() != Ref2->isInnerRef())
306       return false;
307     if (!IsStructurallyEquivalent(Context, Ref1->getPointeeTypeAsWritten(),
308                                   Ref2->getPointeeTypeAsWritten()))
309       return false;
310     break;
311   }
312
313   case Type::MemberPointer: {
314     const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
315     const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
316     if (!IsStructurallyEquivalent(Context, MemPtr1->getPointeeType(),
317                                   MemPtr2->getPointeeType()))
318       return false;
319     if (!IsStructurallyEquivalent(Context, QualType(MemPtr1->getClass(), 0),
320                                   QualType(MemPtr2->getClass(), 0)))
321       return false;
322     break;
323   }
324
325   case Type::ConstantArray: {
326     const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
327     const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
328     if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize()))
329       return false;
330
331     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
332       return false;
333     break;
334   }
335
336   case Type::IncompleteArray:
337     if (!IsArrayStructurallyEquivalent(Context, cast<ArrayType>(T1),
338                                        cast<ArrayType>(T2)))
339       return false;
340     break;
341
342   case Type::VariableArray: {
343     const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
344     const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
345     if (!IsStructurallyEquivalent(Context, Array1->getSizeExpr(),
346                                   Array2->getSizeExpr()))
347       return false;
348
349     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
350       return false;
351
352     break;
353   }
354
355   case Type::DependentSizedArray: {
356     const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
357     const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
358     if (!IsStructurallyEquivalent(Context, Array1->getSizeExpr(),
359                                   Array2->getSizeExpr()))
360       return false;
361
362     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
363       return false;
364
365     break;
366   }
367
368   case Type::DependentAddressSpace: {
369     const DependentAddressSpaceType *DepAddressSpace1 =
370         cast<DependentAddressSpaceType>(T1);
371     const DependentAddressSpaceType *DepAddressSpace2 =
372         cast<DependentAddressSpaceType>(T2);
373     if (!IsStructurallyEquivalent(Context, DepAddressSpace1->getAddrSpaceExpr(),
374                                   DepAddressSpace2->getAddrSpaceExpr()))
375       return false;
376     if (!IsStructurallyEquivalent(Context, DepAddressSpace1->getPointeeType(),
377                                   DepAddressSpace2->getPointeeType()))
378       return false;
379
380     break;
381   }
382
383   case Type::DependentSizedExtVector: {
384     const DependentSizedExtVectorType *Vec1 =
385         cast<DependentSizedExtVectorType>(T1);
386     const DependentSizedExtVectorType *Vec2 =
387         cast<DependentSizedExtVectorType>(T2);
388     if (!IsStructurallyEquivalent(Context, Vec1->getSizeExpr(),
389                                   Vec2->getSizeExpr()))
390       return false;
391     if (!IsStructurallyEquivalent(Context, Vec1->getElementType(),
392                                   Vec2->getElementType()))
393       return false;
394     break;
395   }
396
397   case Type::Vector:
398   case Type::ExtVector: {
399     const VectorType *Vec1 = cast<VectorType>(T1);
400     const VectorType *Vec2 = cast<VectorType>(T2);
401     if (!IsStructurallyEquivalent(Context, Vec1->getElementType(),
402                                   Vec2->getElementType()))
403       return false;
404     if (Vec1->getNumElements() != Vec2->getNumElements())
405       return false;
406     if (Vec1->getVectorKind() != Vec2->getVectorKind())
407       return false;
408     break;
409   }
410
411   case Type::FunctionProto: {
412     const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
413     const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
414     if (Proto1->getNumParams() != Proto2->getNumParams())
415       return false;
416     for (unsigned I = 0, N = Proto1->getNumParams(); I != N; ++I) {
417       if (!IsStructurallyEquivalent(Context, Proto1->getParamType(I),
418                                     Proto2->getParamType(I)))
419         return false;
420     }
421     if (Proto1->isVariadic() != Proto2->isVariadic())
422       return false;
423     if (Proto1->getExceptionSpecType() != Proto2->getExceptionSpecType())
424       return false;
425     if (Proto1->getExceptionSpecType() == EST_Dynamic) {
426       if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
427         return false;
428       for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
429         if (!IsStructurallyEquivalent(Context, Proto1->getExceptionType(I),
430                                       Proto2->getExceptionType(I)))
431           return false;
432       }
433     } else if (Proto1->getExceptionSpecType() == EST_ComputedNoexcept) {
434       if (!IsStructurallyEquivalent(Context, Proto1->getNoexceptExpr(),
435                                     Proto2->getNoexceptExpr()))
436         return false;
437     }
438     if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
439       return false;
440
441     // Fall through to check the bits common with FunctionNoProtoType.
442     LLVM_FALLTHROUGH;
443   }
444
445   case Type::FunctionNoProto: {
446     const FunctionType *Function1 = cast<FunctionType>(T1);
447     const FunctionType *Function2 = cast<FunctionType>(T2);
448     if (!IsStructurallyEquivalent(Context, Function1->getReturnType(),
449                                   Function2->getReturnType()))
450       return false;
451     if (Function1->getExtInfo() != Function2->getExtInfo())
452       return false;
453     break;
454   }
455
456   case Type::UnresolvedUsing:
457     if (!IsStructurallyEquivalent(Context,
458                                   cast<UnresolvedUsingType>(T1)->getDecl(),
459                                   cast<UnresolvedUsingType>(T2)->getDecl()))
460       return false;
461
462     break;
463
464   case Type::Attributed:
465     if (!IsStructurallyEquivalent(Context,
466                                   cast<AttributedType>(T1)->getModifiedType(),
467                                   cast<AttributedType>(T2)->getModifiedType()))
468       return false;
469     if (!IsStructurallyEquivalent(
470             Context, cast<AttributedType>(T1)->getEquivalentType(),
471             cast<AttributedType>(T2)->getEquivalentType()))
472       return false;
473     break;
474
475   case Type::Paren:
476     if (!IsStructurallyEquivalent(Context, cast<ParenType>(T1)->getInnerType(),
477                                   cast<ParenType>(T2)->getInnerType()))
478       return false;
479     break;
480
481   case Type::Typedef:
482     if (!IsStructurallyEquivalent(Context, cast<TypedefType>(T1)->getDecl(),
483                                   cast<TypedefType>(T2)->getDecl()))
484       return false;
485     break;
486
487   case Type::TypeOfExpr:
488     if (!IsStructurallyEquivalent(
489             Context, cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
490             cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
491       return false;
492     break;
493
494   case Type::TypeOf:
495     if (!IsStructurallyEquivalent(Context,
496                                   cast<TypeOfType>(T1)->getUnderlyingType(),
497                                   cast<TypeOfType>(T2)->getUnderlyingType()))
498       return false;
499     break;
500
501   case Type::UnaryTransform:
502     if (!IsStructurallyEquivalent(
503             Context, cast<UnaryTransformType>(T1)->getUnderlyingType(),
504             cast<UnaryTransformType>(T1)->getUnderlyingType()))
505       return false;
506     break;
507
508   case Type::Decltype:
509     if (!IsStructurallyEquivalent(Context,
510                                   cast<DecltypeType>(T1)->getUnderlyingExpr(),
511                                   cast<DecltypeType>(T2)->getUnderlyingExpr()))
512       return false;
513     break;
514
515   case Type::Auto:
516     if (!IsStructurallyEquivalent(Context, cast<AutoType>(T1)->getDeducedType(),
517                                   cast<AutoType>(T2)->getDeducedType()))
518       return false;
519     break;
520
521   case Type::DeducedTemplateSpecialization: {
522     auto *DT1 = cast<DeducedTemplateSpecializationType>(T1);
523     auto *DT2 = cast<DeducedTemplateSpecializationType>(T2);
524     if (!IsStructurallyEquivalent(Context, DT1->getTemplateName(),
525                                   DT2->getTemplateName()))
526       return false;
527     if (!IsStructurallyEquivalent(Context, DT1->getDeducedType(),
528                                   DT2->getDeducedType()))
529       return false;
530     break;
531   }
532
533   case Type::Record:
534   case Type::Enum:
535     if (!IsStructurallyEquivalent(Context, cast<TagType>(T1)->getDecl(),
536                                   cast<TagType>(T2)->getDecl()))
537       return false;
538     break;
539
540   case Type::TemplateTypeParm: {
541     const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
542     const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
543     if (Parm1->getDepth() != Parm2->getDepth())
544       return false;
545     if (Parm1->getIndex() != Parm2->getIndex())
546       return false;
547     if (Parm1->isParameterPack() != Parm2->isParameterPack())
548       return false;
549
550     // Names of template type parameters are never significant.
551     break;
552   }
553
554   case Type::SubstTemplateTypeParm: {
555     const SubstTemplateTypeParmType *Subst1 =
556         cast<SubstTemplateTypeParmType>(T1);
557     const SubstTemplateTypeParmType *Subst2 =
558         cast<SubstTemplateTypeParmType>(T2);
559     if (!IsStructurallyEquivalent(Context,
560                                   QualType(Subst1->getReplacedParameter(), 0),
561                                   QualType(Subst2->getReplacedParameter(), 0)))
562       return false;
563     if (!IsStructurallyEquivalent(Context, Subst1->getReplacementType(),
564                                   Subst2->getReplacementType()))
565       return false;
566     break;
567   }
568
569   case Type::SubstTemplateTypeParmPack: {
570     const SubstTemplateTypeParmPackType *Subst1 =
571         cast<SubstTemplateTypeParmPackType>(T1);
572     const SubstTemplateTypeParmPackType *Subst2 =
573         cast<SubstTemplateTypeParmPackType>(T2);
574     if (!IsStructurallyEquivalent(Context,
575                                   QualType(Subst1->getReplacedParameter(), 0),
576                                   QualType(Subst2->getReplacedParameter(), 0)))
577       return false;
578     if (!IsStructurallyEquivalent(Context, Subst1->getArgumentPack(),
579                                   Subst2->getArgumentPack()))
580       return false;
581     break;
582   }
583   case Type::TemplateSpecialization: {
584     const TemplateSpecializationType *Spec1 =
585         cast<TemplateSpecializationType>(T1);
586     const TemplateSpecializationType *Spec2 =
587         cast<TemplateSpecializationType>(T2);
588     if (!IsStructurallyEquivalent(Context, Spec1->getTemplateName(),
589                                   Spec2->getTemplateName()))
590       return false;
591     if (Spec1->getNumArgs() != Spec2->getNumArgs())
592       return false;
593     for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
594       if (!IsStructurallyEquivalent(Context, Spec1->getArg(I),
595                                     Spec2->getArg(I)))
596         return false;
597     }
598     break;
599   }
600
601   case Type::Elaborated: {
602     const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
603     const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
604     // CHECKME: what if a keyword is ETK_None or ETK_typename ?
605     if (Elab1->getKeyword() != Elab2->getKeyword())
606       return false;
607     if (!IsStructurallyEquivalent(Context, Elab1->getQualifier(),
608                                   Elab2->getQualifier()))
609       return false;
610     if (!IsStructurallyEquivalent(Context, Elab1->getNamedType(),
611                                   Elab2->getNamedType()))
612       return false;
613     break;
614   }
615
616   case Type::InjectedClassName: {
617     const InjectedClassNameType *Inj1 = cast<InjectedClassNameType>(T1);
618     const InjectedClassNameType *Inj2 = cast<InjectedClassNameType>(T2);
619     if (!IsStructurallyEquivalent(Context,
620                                   Inj1->getInjectedSpecializationType(),
621                                   Inj2->getInjectedSpecializationType()))
622       return false;
623     break;
624   }
625
626   case Type::DependentName: {
627     const DependentNameType *Typename1 = cast<DependentNameType>(T1);
628     const DependentNameType *Typename2 = cast<DependentNameType>(T2);
629     if (!IsStructurallyEquivalent(Context, Typename1->getQualifier(),
630                                   Typename2->getQualifier()))
631       return false;
632     if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
633                                   Typename2->getIdentifier()))
634       return false;
635
636     break;
637   }
638
639   case Type::DependentTemplateSpecialization: {
640     const DependentTemplateSpecializationType *Spec1 =
641         cast<DependentTemplateSpecializationType>(T1);
642     const DependentTemplateSpecializationType *Spec2 =
643         cast<DependentTemplateSpecializationType>(T2);
644     if (!IsStructurallyEquivalent(Context, Spec1->getQualifier(),
645                                   Spec2->getQualifier()))
646       return false;
647     if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
648                                   Spec2->getIdentifier()))
649       return false;
650     if (Spec1->getNumArgs() != Spec2->getNumArgs())
651       return false;
652     for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
653       if (!IsStructurallyEquivalent(Context, Spec1->getArg(I),
654                                     Spec2->getArg(I)))
655         return false;
656     }
657     break;
658   }
659
660   case Type::PackExpansion:
661     if (!IsStructurallyEquivalent(Context,
662                                   cast<PackExpansionType>(T1)->getPattern(),
663                                   cast<PackExpansionType>(T2)->getPattern()))
664       return false;
665     break;
666
667   case Type::ObjCInterface: {
668     const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
669     const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
670     if (!IsStructurallyEquivalent(Context, Iface1->getDecl(),
671                                   Iface2->getDecl()))
672       return false;
673     break;
674   }
675
676   case Type::ObjCTypeParam: {
677     const ObjCTypeParamType *Obj1 = cast<ObjCTypeParamType>(T1);
678     const ObjCTypeParamType *Obj2 = cast<ObjCTypeParamType>(T2);
679     if (!IsStructurallyEquivalent(Context, Obj1->getDecl(), Obj2->getDecl()))
680       return false;
681
682     if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
683       return false;
684     for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
685       if (!IsStructurallyEquivalent(Context, Obj1->getProtocol(I),
686                                     Obj2->getProtocol(I)))
687         return false;
688     }
689     break;
690   }
691   case Type::ObjCObject: {
692     const ObjCObjectType *Obj1 = cast<ObjCObjectType>(T1);
693     const ObjCObjectType *Obj2 = cast<ObjCObjectType>(T2);
694     if (!IsStructurallyEquivalent(Context, Obj1->getBaseType(),
695                                   Obj2->getBaseType()))
696       return false;
697     if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
698       return false;
699     for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
700       if (!IsStructurallyEquivalent(Context, Obj1->getProtocol(I),
701                                     Obj2->getProtocol(I)))
702         return false;
703     }
704     break;
705   }
706
707   case Type::ObjCObjectPointer: {
708     const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
709     const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
710     if (!IsStructurallyEquivalent(Context, Ptr1->getPointeeType(),
711                                   Ptr2->getPointeeType()))
712       return false;
713     break;
714   }
715
716   case Type::Atomic: {
717     if (!IsStructurallyEquivalent(Context, cast<AtomicType>(T1)->getValueType(),
718                                   cast<AtomicType>(T2)->getValueType()))
719       return false;
720     break;
721   }
722
723   case Type::Pipe: {
724     if (!IsStructurallyEquivalent(Context, cast<PipeType>(T1)->getElementType(),
725                                   cast<PipeType>(T2)->getElementType()))
726       return false;
727     break;
728   }
729
730   } // end switch
731
732   return true;
733 }
734
735 /// Determine structural equivalence of two fields.
736 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
737                                      FieldDecl *Field1, FieldDecl *Field2) {
738   RecordDecl *Owner2 = cast<RecordDecl>(Field2->getDeclContext());
739
740   // For anonymous structs/unions, match up the anonymous struct/union type
741   // declarations directly, so that we don't go off searching for anonymous
742   // types
743   if (Field1->isAnonymousStructOrUnion() &&
744       Field2->isAnonymousStructOrUnion()) {
745     RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl();
746     RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl();
747     return IsStructurallyEquivalent(Context, D1, D2);
748   }
749
750   // Check for equivalent field names.
751   IdentifierInfo *Name1 = Field1->getIdentifier();
752   IdentifierInfo *Name2 = Field2->getIdentifier();
753   if (!::IsStructurallyEquivalent(Name1, Name2)) {
754     if (Context.Complain) {
755       Context.Diag2(Owner2->getLocation(),
756                     Context.ErrorOnTagTypeMismatch
757                         ? diag::err_odr_tag_type_inconsistent
758                         : diag::warn_odr_tag_type_inconsistent)
759           << Context.ToCtx.getTypeDeclType(Owner2);
760       Context.Diag2(Field2->getLocation(), diag::note_odr_field_name)
761           << Field2->getDeclName();
762       Context.Diag1(Field1->getLocation(), diag::note_odr_field_name)
763           << Field1->getDeclName();
764     }
765     return false;
766   }
767
768   if (!IsStructurallyEquivalent(Context, Field1->getType(),
769                                 Field2->getType())) {
770     if (Context.Complain) {
771       Context.Diag2(Owner2->getLocation(),
772                     Context.ErrorOnTagTypeMismatch
773                         ? diag::err_odr_tag_type_inconsistent
774                         : diag::warn_odr_tag_type_inconsistent)
775           << Context.ToCtx.getTypeDeclType(Owner2);
776       Context.Diag2(Field2->getLocation(), diag::note_odr_field)
777           << Field2->getDeclName() << Field2->getType();
778       Context.Diag1(Field1->getLocation(), diag::note_odr_field)
779           << Field1->getDeclName() << Field1->getType();
780     }
781     return false;
782   }
783
784   if (Field1->isBitField() != Field2->isBitField()) {
785     if (Context.Complain) {
786       Context.Diag2(Owner2->getLocation(),
787                     Context.ErrorOnTagTypeMismatch
788                         ? diag::err_odr_tag_type_inconsistent
789                         : diag::warn_odr_tag_type_inconsistent)
790           << Context.ToCtx.getTypeDeclType(Owner2);
791       if (Field1->isBitField()) {
792         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
793             << Field1->getDeclName() << Field1->getType()
794             << Field1->getBitWidthValue(Context.FromCtx);
795         Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
796             << Field2->getDeclName();
797       } else {
798         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
799             << Field2->getDeclName() << Field2->getType()
800             << Field2->getBitWidthValue(Context.ToCtx);
801         Context.Diag1(Field1->getLocation(), diag::note_odr_not_bit_field)
802             << Field1->getDeclName();
803       }
804     }
805     return false;
806   }
807
808   if (Field1->isBitField()) {
809     // Make sure that the bit-fields are the same length.
810     unsigned Bits1 = Field1->getBitWidthValue(Context.FromCtx);
811     unsigned Bits2 = Field2->getBitWidthValue(Context.ToCtx);
812
813     if (Bits1 != Bits2) {
814       if (Context.Complain) {
815         Context.Diag2(Owner2->getLocation(),
816                       Context.ErrorOnTagTypeMismatch
817                           ? diag::err_odr_tag_type_inconsistent
818                           : diag::warn_odr_tag_type_inconsistent)
819             << Context.ToCtx.getTypeDeclType(Owner2);
820         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
821             << Field2->getDeclName() << Field2->getType() << Bits2;
822         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
823             << Field1->getDeclName() << Field1->getType() << Bits1;
824       }
825       return false;
826     }
827   }
828
829   return true;
830 }
831
832 /// Determine structural equivalence of two records.
833 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
834                                      RecordDecl *D1, RecordDecl *D2) {
835   if (D1->isUnion() != D2->isUnion()) {
836     if (Context.Complain) {
837       Context.Diag2(D2->getLocation(),
838                     Context.ErrorOnTagTypeMismatch
839                         ? diag::err_odr_tag_type_inconsistent
840                         : diag::warn_odr_tag_type_inconsistent)
841           << Context.ToCtx.getTypeDeclType(D2);
842       Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
843           << D1->getDeclName() << (unsigned)D1->getTagKind();
844     }
845     return false;
846   }
847
848   if (D1->isAnonymousStructOrUnion() && D2->isAnonymousStructOrUnion()) {
849     // If both anonymous structs/unions are in a record context, make sure
850     // they occur in the same location in the context records.
851     if (Optional<unsigned> Index1 =
852             StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(D1)) {
853       if (Optional<unsigned> Index2 =
854               StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(
855                   D2)) {
856         if (*Index1 != *Index2)
857           return false;
858       }
859     }
860   }
861
862   // If both declarations are class template specializations, we know
863   // the ODR applies, so check the template and template arguments.
864   ClassTemplateSpecializationDecl *Spec1 =
865       dyn_cast<ClassTemplateSpecializationDecl>(D1);
866   ClassTemplateSpecializationDecl *Spec2 =
867       dyn_cast<ClassTemplateSpecializationDecl>(D2);
868   if (Spec1 && Spec2) {
869     // Check that the specialized templates are the same.
870     if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
871                                   Spec2->getSpecializedTemplate()))
872       return false;
873
874     // Check that the template arguments are the same.
875     if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
876       return false;
877
878     for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
879       if (!IsStructurallyEquivalent(Context, Spec1->getTemplateArgs().get(I),
880                                     Spec2->getTemplateArgs().get(I)))
881         return false;
882   }
883   // If one is a class template specialization and the other is not, these
884   // structures are different.
885   else if (Spec1 || Spec2)
886     return false;
887
888   // Compare the definitions of these two records. If either or both are
889   // incomplete, we assume that they are equivalent.
890   D1 = D1->getDefinition();
891   D2 = D2->getDefinition();
892   if (!D1 || !D2)
893     return true;
894
895   if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
896     if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
897       if (D1CXX->hasExternalLexicalStorage() &&
898           !D1CXX->isCompleteDefinition()) {
899         D1CXX->getASTContext().getExternalSource()->CompleteType(D1CXX);
900       }
901
902       if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
903         if (Context.Complain) {
904           Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
905               << Context.ToCtx.getTypeDeclType(D2);
906           Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
907               << D2CXX->getNumBases();
908           Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
909               << D1CXX->getNumBases();
910         }
911         return false;
912       }
913
914       // Check the base classes.
915       for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(),
916                                               BaseEnd1 = D1CXX->bases_end(),
917                                               Base2 = D2CXX->bases_begin();
918            Base1 != BaseEnd1; ++Base1, ++Base2) {
919         if (!IsStructurallyEquivalent(Context, Base1->getType(),
920                                       Base2->getType())) {
921           if (Context.Complain) {
922             Context.Diag2(D2->getLocation(),
923                           diag::warn_odr_tag_type_inconsistent)
924                 << Context.ToCtx.getTypeDeclType(D2);
925             Context.Diag2(Base2->getLocStart(), diag::note_odr_base)
926                 << Base2->getType() << Base2->getSourceRange();
927             Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
928                 << Base1->getType() << Base1->getSourceRange();
929           }
930           return false;
931         }
932
933         // Check virtual vs. non-virtual inheritance mismatch.
934         if (Base1->isVirtual() != Base2->isVirtual()) {
935           if (Context.Complain) {
936             Context.Diag2(D2->getLocation(),
937                           diag::warn_odr_tag_type_inconsistent)
938                 << Context.ToCtx.getTypeDeclType(D2);
939             Context.Diag2(Base2->getLocStart(), diag::note_odr_virtual_base)
940                 << Base2->isVirtual() << Base2->getSourceRange();
941             Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
942                 << Base1->isVirtual() << Base1->getSourceRange();
943           }
944           return false;
945         }
946       }
947     } else if (D1CXX->getNumBases() > 0) {
948       if (Context.Complain) {
949         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
950             << Context.ToCtx.getTypeDeclType(D2);
951         const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
952         Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
953             << Base1->getType() << Base1->getSourceRange();
954         Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
955       }
956       return false;
957     }
958   }
959
960   // Check the fields for consistency.
961   RecordDecl::field_iterator Field2 = D2->field_begin(),
962                              Field2End = D2->field_end();
963   for (RecordDecl::field_iterator Field1 = D1->field_begin(),
964                                   Field1End = D1->field_end();
965        Field1 != Field1End; ++Field1, ++Field2) {
966     if (Field2 == Field2End) {
967       if (Context.Complain) {
968         Context.Diag2(D2->getLocation(),
969                       Context.ErrorOnTagTypeMismatch
970                           ? diag::err_odr_tag_type_inconsistent
971                           : diag::warn_odr_tag_type_inconsistent)
972             << Context.ToCtx.getTypeDeclType(D2);
973         Context.Diag1(Field1->getLocation(), diag::note_odr_field)
974             << Field1->getDeclName() << Field1->getType();
975         Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
976       }
977       return false;
978     }
979
980     if (!IsStructurallyEquivalent(Context, *Field1, *Field2))
981       return false;
982   }
983
984   if (Field2 != Field2End) {
985     if (Context.Complain) {
986       Context.Diag2(D2->getLocation(),
987                     Context.ErrorOnTagTypeMismatch
988                         ? diag::err_odr_tag_type_inconsistent
989                         : diag::warn_odr_tag_type_inconsistent)
990           << Context.ToCtx.getTypeDeclType(D2);
991       Context.Diag2(Field2->getLocation(), diag::note_odr_field)
992           << Field2->getDeclName() << Field2->getType();
993       Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
994     }
995     return false;
996   }
997
998   return true;
999 }
1000
1001 /// Determine structural equivalence of two enums.
1002 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1003                                      EnumDecl *D1, EnumDecl *D2) {
1004   EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
1005                                 EC2End = D2->enumerator_end();
1006   for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
1007                                      EC1End = D1->enumerator_end();
1008        EC1 != EC1End; ++EC1, ++EC2) {
1009     if (EC2 == EC2End) {
1010       if (Context.Complain) {
1011         Context.Diag2(D2->getLocation(),
1012                       Context.ErrorOnTagTypeMismatch
1013                           ? diag::err_odr_tag_type_inconsistent
1014                           : diag::warn_odr_tag_type_inconsistent)
1015             << Context.ToCtx.getTypeDeclType(D2);
1016         Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1017             << EC1->getDeclName() << EC1->getInitVal().toString(10);
1018         Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
1019       }
1020       return false;
1021     }
1022
1023     llvm::APSInt Val1 = EC1->getInitVal();
1024     llvm::APSInt Val2 = EC2->getInitVal();
1025     if (!llvm::APSInt::isSameValue(Val1, Val2) ||
1026         !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
1027       if (Context.Complain) {
1028         Context.Diag2(D2->getLocation(),
1029                       Context.ErrorOnTagTypeMismatch
1030                           ? diag::err_odr_tag_type_inconsistent
1031                           : diag::warn_odr_tag_type_inconsistent)
1032             << Context.ToCtx.getTypeDeclType(D2);
1033         Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1034             << EC2->getDeclName() << EC2->getInitVal().toString(10);
1035         Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1036             << EC1->getDeclName() << EC1->getInitVal().toString(10);
1037       }
1038       return false;
1039     }
1040   }
1041
1042   if (EC2 != EC2End) {
1043     if (Context.Complain) {
1044       Context.Diag2(D2->getLocation(),
1045                     Context.ErrorOnTagTypeMismatch
1046                         ? diag::err_odr_tag_type_inconsistent
1047                         : diag::warn_odr_tag_type_inconsistent)
1048           << Context.ToCtx.getTypeDeclType(D2);
1049       Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1050           << EC2->getDeclName() << EC2->getInitVal().toString(10);
1051       Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
1052     }
1053     return false;
1054   }
1055
1056   return true;
1057 }
1058
1059 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1060                                      TemplateParameterList *Params1,
1061                                      TemplateParameterList *Params2) {
1062   if (Params1->size() != Params2->size()) {
1063     if (Context.Complain) {
1064       Context.Diag2(Params2->getTemplateLoc(),
1065                     diag::err_odr_different_num_template_parameters)
1066           << Params1->size() << Params2->size();
1067       Context.Diag1(Params1->getTemplateLoc(),
1068                     diag::note_odr_template_parameter_list);
1069     }
1070     return false;
1071   }
1072
1073   for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
1074     if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
1075       if (Context.Complain) {
1076         Context.Diag2(Params2->getParam(I)->getLocation(),
1077                       diag::err_odr_different_template_parameter_kind);
1078         Context.Diag1(Params1->getParam(I)->getLocation(),
1079                       diag::note_odr_template_parameter_here);
1080       }
1081       return false;
1082     }
1083
1084     if (!Context.IsStructurallyEquivalent(Params1->getParam(I),
1085                                           Params2->getParam(I))) {
1086
1087       return false;
1088     }
1089   }
1090
1091   return true;
1092 }
1093
1094 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1095                                      TemplateTypeParmDecl *D1,
1096                                      TemplateTypeParmDecl *D2) {
1097   if (D1->isParameterPack() != D2->isParameterPack()) {
1098     if (Context.Complain) {
1099       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1100           << D2->isParameterPack();
1101       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1102           << D1->isParameterPack();
1103     }
1104     return false;
1105   }
1106
1107   return true;
1108 }
1109
1110 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1111                                      NonTypeTemplateParmDecl *D1,
1112                                      NonTypeTemplateParmDecl *D2) {
1113   if (D1->isParameterPack() != D2->isParameterPack()) {
1114     if (Context.Complain) {
1115       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1116           << D2->isParameterPack();
1117       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1118           << D1->isParameterPack();
1119     }
1120     return false;
1121   }
1122
1123   // Check types.
1124   if (!Context.IsStructurallyEquivalent(D1->getType(), D2->getType())) {
1125     if (Context.Complain) {
1126       Context.Diag2(D2->getLocation(),
1127                     diag::err_odr_non_type_parameter_type_inconsistent)
1128           << D2->getType() << D1->getType();
1129       Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
1130           << D1->getType();
1131     }
1132     return false;
1133   }
1134
1135   return true;
1136 }
1137
1138 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1139                                      TemplateTemplateParmDecl *D1,
1140                                      TemplateTemplateParmDecl *D2) {
1141   if (D1->isParameterPack() != D2->isParameterPack()) {
1142     if (Context.Complain) {
1143       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1144           << D2->isParameterPack();
1145       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1146           << D1->isParameterPack();
1147     }
1148     return false;
1149   }
1150
1151   // Check template parameter lists.
1152   return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1153                                   D2->getTemplateParameters());
1154 }
1155
1156 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1157                                      ClassTemplateDecl *D1,
1158                                      ClassTemplateDecl *D2) {
1159   // Check template parameters.
1160   if (!IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1161                                 D2->getTemplateParameters()))
1162     return false;
1163
1164   // Check the templated declaration.
1165   return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(),
1166                                           D2->getTemplatedDecl());
1167 }
1168
1169 /// Determine structural equivalence of two declarations.
1170 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1171                                      Decl *D1, Decl *D2) {
1172   // FIXME: Check for known structural equivalences via a callback of some sort.
1173
1174   // Check whether we already know that these two declarations are not
1175   // structurally equivalent.
1176   if (Context.NonEquivalentDecls.count(
1177           std::make_pair(D1->getCanonicalDecl(), D2->getCanonicalDecl())))
1178     return false;
1179
1180   // Determine whether we've already produced a tentative equivalence for D1.
1181   Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
1182   if (EquivToD1)
1183     return EquivToD1 == D2->getCanonicalDecl();
1184
1185   // Produce a tentative equivalence D1 <-> D2, which will be checked later.
1186   EquivToD1 = D2->getCanonicalDecl();
1187   Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
1188   return true;
1189 }
1190 } // namespace
1191
1192 namespace clang {
1193
1194 DiagnosticBuilder StructuralEquivalenceContext::Diag1(SourceLocation Loc,
1195                                                       unsigned DiagID) {
1196   assert(Complain && "Not allowed to complain");
1197   if (LastDiagFromC2)
1198     FromCtx.getDiagnostics().notePriorDiagnosticFrom(ToCtx.getDiagnostics());
1199   LastDiagFromC2 = false;
1200   return FromCtx.getDiagnostics().Report(Loc, DiagID);
1201 }
1202
1203 DiagnosticBuilder StructuralEquivalenceContext::Diag2(SourceLocation Loc,
1204                                                       unsigned DiagID) {
1205   assert(Complain && "Not allowed to complain");
1206   if (!LastDiagFromC2)
1207     ToCtx.getDiagnostics().notePriorDiagnosticFrom(FromCtx.getDiagnostics());
1208   LastDiagFromC2 = true;
1209   return ToCtx.getDiagnostics().Report(Loc, DiagID);
1210 }
1211
1212 Optional<unsigned>
1213 StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(RecordDecl *Anon) {
1214   ASTContext &Context = Anon->getASTContext();
1215   QualType AnonTy = Context.getRecordType(Anon);
1216
1217   RecordDecl *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext());
1218   if (!Owner)
1219     return None;
1220
1221   unsigned Index = 0;
1222   for (const auto *D : Owner->noload_decls()) {
1223     const auto *F = dyn_cast<FieldDecl>(D);
1224     if (!F)
1225       continue;
1226
1227     if (F->isAnonymousStructOrUnion()) {
1228       if (Context.hasSameType(F->getType(), AnonTy))
1229         break;
1230       ++Index;
1231       continue;
1232     }
1233
1234     // If the field looks like this:
1235     // struct { ... } A;
1236     QualType FieldType = F->getType();
1237     if (const auto *RecType = dyn_cast<RecordType>(FieldType)) {
1238       const RecordDecl *RecDecl = RecType->getDecl();
1239       if (RecDecl->getDeclContext() == Owner && !RecDecl->getIdentifier()) {
1240         if (Context.hasSameType(FieldType, AnonTy))
1241           break;
1242         ++Index;
1243         continue;
1244       }
1245     }
1246   }
1247
1248   return Index;
1249 }
1250
1251 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1,
1252                                                             Decl *D2) {
1253   if (!::IsStructurallyEquivalent(*this, D1, D2))
1254     return false;
1255
1256   return !Finish();
1257 }
1258
1259 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1,
1260                                                             QualType T2) {
1261   if (!::IsStructurallyEquivalent(*this, T1, T2))
1262     return false;
1263
1264   return !Finish();
1265 }
1266
1267 bool StructuralEquivalenceContext::Finish() {
1268   while (!DeclsToCheck.empty()) {
1269     // Check the next declaration.
1270     Decl *D1 = DeclsToCheck.front();
1271     DeclsToCheck.pop_front();
1272
1273     Decl *D2 = TentativeEquivalences[D1];
1274     assert(D2 && "Unrecorded tentative equivalence?");
1275
1276     bool Equivalent = true;
1277
1278     // FIXME: Switch on all declaration kinds. For now, we're just going to
1279     // check the obvious ones.
1280     if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
1281       if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
1282         // Check for equivalent structure names.
1283         IdentifierInfo *Name1 = Record1->getIdentifier();
1284         if (!Name1 && Record1->getTypedefNameForAnonDecl())
1285           Name1 = Record1->getTypedefNameForAnonDecl()->getIdentifier();
1286         IdentifierInfo *Name2 = Record2->getIdentifier();
1287         if (!Name2 && Record2->getTypedefNameForAnonDecl())
1288           Name2 = Record2->getTypedefNameForAnonDecl()->getIdentifier();
1289         if (!::IsStructurallyEquivalent(Name1, Name2) ||
1290             !::IsStructurallyEquivalent(*this, Record1, Record2))
1291           Equivalent = false;
1292       } else {
1293         // Record/non-record mismatch.
1294         Equivalent = false;
1295       }
1296     } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
1297       if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
1298         // Check for equivalent enum names.
1299         IdentifierInfo *Name1 = Enum1->getIdentifier();
1300         if (!Name1 && Enum1->getTypedefNameForAnonDecl())
1301           Name1 = Enum1->getTypedefNameForAnonDecl()->getIdentifier();
1302         IdentifierInfo *Name2 = Enum2->getIdentifier();
1303         if (!Name2 && Enum2->getTypedefNameForAnonDecl())
1304           Name2 = Enum2->getTypedefNameForAnonDecl()->getIdentifier();
1305         if (!::IsStructurallyEquivalent(Name1, Name2) ||
1306             !::IsStructurallyEquivalent(*this, Enum1, Enum2))
1307           Equivalent = false;
1308       } else {
1309         // Enum/non-enum mismatch
1310         Equivalent = false;
1311       }
1312     } else if (TypedefNameDecl *Typedef1 = dyn_cast<TypedefNameDecl>(D1)) {
1313       if (TypedefNameDecl *Typedef2 = dyn_cast<TypedefNameDecl>(D2)) {
1314         if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
1315                                         Typedef2->getIdentifier()) ||
1316             !::IsStructurallyEquivalent(*this, Typedef1->getUnderlyingType(),
1317                                         Typedef2->getUnderlyingType()))
1318           Equivalent = false;
1319       } else {
1320         // Typedef/non-typedef mismatch.
1321         Equivalent = false;
1322       }
1323     } else if (ClassTemplateDecl *ClassTemplate1 =
1324                    dyn_cast<ClassTemplateDecl>(D1)) {
1325       if (ClassTemplateDecl *ClassTemplate2 = dyn_cast<ClassTemplateDecl>(D2)) {
1326         if (!::IsStructurallyEquivalent(ClassTemplate1->getIdentifier(),
1327                                         ClassTemplate2->getIdentifier()) ||
1328             !::IsStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2))
1329           Equivalent = false;
1330       } else {
1331         // Class template/non-class-template mismatch.
1332         Equivalent = false;
1333       }
1334     } else if (TemplateTypeParmDecl *TTP1 =
1335                    dyn_cast<TemplateTypeParmDecl>(D1)) {
1336       if (TemplateTypeParmDecl *TTP2 = dyn_cast<TemplateTypeParmDecl>(D2)) {
1337         if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1338           Equivalent = false;
1339       } else {
1340         // Kind mismatch.
1341         Equivalent = false;
1342       }
1343     } else if (NonTypeTemplateParmDecl *NTTP1 =
1344                    dyn_cast<NonTypeTemplateParmDecl>(D1)) {
1345       if (NonTypeTemplateParmDecl *NTTP2 =
1346               dyn_cast<NonTypeTemplateParmDecl>(D2)) {
1347         if (!::IsStructurallyEquivalent(*this, NTTP1, NTTP2))
1348           Equivalent = false;
1349       } else {
1350         // Kind mismatch.
1351         Equivalent = false;
1352       }
1353     } else if (TemplateTemplateParmDecl *TTP1 =
1354                    dyn_cast<TemplateTemplateParmDecl>(D1)) {
1355       if (TemplateTemplateParmDecl *TTP2 =
1356               dyn_cast<TemplateTemplateParmDecl>(D2)) {
1357         if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1358           Equivalent = false;
1359       } else {
1360         // Kind mismatch.
1361         Equivalent = false;
1362       }
1363     }
1364
1365     if (!Equivalent) {
1366       // Note that these two declarations are not equivalent (and we already
1367       // know about it).
1368       NonEquivalentDecls.insert(
1369           std::make_pair(D1->getCanonicalDecl(), D2->getCanonicalDecl()));
1370       return true;
1371     }
1372     // FIXME: Check other declaration kinds!
1373   }
1374
1375   return false;
1376 }
1377 } // namespace clang