1 //===--- ASTImporter.cpp - Importing ASTs from other Contexts ---*- 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 defines the ASTImporter class which imports AST nodes from one
11 // context into another context.
12 //
13 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTImporter.h"
15
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTDiagnostic.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclVisitor.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/AST/TypeVisitor.h"
23 #include "clang/Basic/FileManager.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include <deque>
27
28 using namespace clang;
29
30 namespace {
31 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, QualType>,
32 public DeclVisitor<ASTNodeImporter, Decl *>,
33 public StmtVisitor<ASTNodeImporter, Stmt *> {
34 ASTImporter &Importer;
35
36 public:
ASTNodeImporter(ASTImporter & Importer)37 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) { }
38
39 using TypeVisitor<ASTNodeImporter, QualType>::Visit;
40 using DeclVisitor<ASTNodeImporter, Decl *>::Visit;
41 using StmtVisitor<ASTNodeImporter, Stmt *>::Visit;
42
43 // Importing types
44 QualType VisitType(const Type *T);
45 QualType VisitBuiltinType(const BuiltinType *T);
46 QualType VisitComplexType(const ComplexType *T);
47 QualType VisitPointerType(const PointerType *T);
48 QualType VisitBlockPointerType(const BlockPointerType *T);
49 QualType VisitLValueReferenceType(const LValueReferenceType *T);
50 QualType VisitRValueReferenceType(const RValueReferenceType *T);
51 QualType VisitMemberPointerType(const MemberPointerType *T);
52 QualType VisitConstantArrayType(const ConstantArrayType *T);
53 QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
54 QualType VisitVariableArrayType(const VariableArrayType *T);
55 // FIXME: DependentSizedArrayType
56 // FIXME: DependentSizedExtVectorType
57 QualType VisitVectorType(const VectorType *T);
58 QualType VisitExtVectorType(const ExtVectorType *T);
59 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
60 QualType VisitFunctionProtoType(const FunctionProtoType *T);
61 // FIXME: UnresolvedUsingType
62 QualType VisitTypedefType(const TypedefType *T);
63 QualType VisitTypeOfExprType(const TypeOfExprType *T);
64 // FIXME: DependentTypeOfExprType
65 QualType VisitTypeOfType(const TypeOfType *T);
66 QualType VisitDecltypeType(const DecltypeType *T);
67 QualType VisitUnaryTransformType(const UnaryTransformType *T);
68 QualType VisitAutoType(const AutoType *T);
69 // FIXME: DependentDecltypeType
70 QualType VisitRecordType(const RecordType *T);
71 QualType VisitEnumType(const EnumType *T);
72 // FIXME: TemplateTypeParmType
73 // FIXME: SubstTemplateTypeParmType
74 QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
75 QualType VisitElaboratedType(const ElaboratedType *T);
76 // FIXME: DependentNameType
77 // FIXME: DependentTemplateSpecializationType
78 QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
79 QualType VisitObjCObjectType(const ObjCObjectType *T);
80 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
81
82 // Importing declarations
83 bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,
84 DeclContext *&LexicalDC, DeclarationName &Name,
85 SourceLocation &Loc);
86 void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
87 DeclarationNameInfo& To);
88 void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
89 bool ImportDefinition(RecordDecl *From, RecordDecl *To, bool ForceImport = false);
90 TemplateParameterList *ImportTemplateParameterList(
91 TemplateParameterList *Params);
92 TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
93 bool ImportTemplateArguments(const TemplateArgument *FromArgs,
94 unsigned NumFromArgs,
95 llvm::SmallVectorImpl<TemplateArgument> &ToArgs);
96 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord);
97 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
98 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
99 Decl *VisitDecl(Decl *D);
100 Decl *VisitNamespaceDecl(NamespaceDecl *D);
101 Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
102 Decl *VisitTypedefDecl(TypedefDecl *D);
103 Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
104 Decl *VisitEnumDecl(EnumDecl *D);
105 Decl *VisitRecordDecl(RecordDecl *D);
106 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
107 Decl *VisitFunctionDecl(FunctionDecl *D);
108 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
109 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
110 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
111 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
112 Decl *VisitFieldDecl(FieldDecl *D);
113 Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
114 Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
115 Decl *VisitVarDecl(VarDecl *D);
116 Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
117 Decl *VisitParmVarDecl(ParmVarDecl *D);
118 Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
119 Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
120 Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
121 Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
122 Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
123 Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
124 Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
125 Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
126 Decl *VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
127 Decl *VisitObjCClassDecl(ObjCClassDecl *D);
128 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
129 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
130 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
131 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
132 Decl *VisitClassTemplateSpecializationDecl(
133 ClassTemplateSpecializationDecl *D);
134
135 // Importing statements
136 Stmt *VisitStmt(Stmt *S);
137
138 // Importing expressions
139 Expr *VisitExpr(Expr *E);
140 Expr *VisitDeclRefExpr(DeclRefExpr *E);
141 Expr *VisitIntegerLiteral(IntegerLiteral *E);
142 Expr *VisitCharacterLiteral(CharacterLiteral *E);
143 Expr *VisitParenExpr(ParenExpr *E);
144 Expr *VisitUnaryOperator(UnaryOperator *E);
145 Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
146 Expr *VisitBinaryOperator(BinaryOperator *E);
147 Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
148 Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
149 Expr *VisitCStyleCastExpr(CStyleCastExpr *E);
150 };
151 }
152
153 //----------------------------------------------------------------------------
154 // Structural Equivalence
155 //----------------------------------------------------------------------------
156
157 namespace {
158 struct StructuralEquivalenceContext {
159 /// \brief AST contexts for which we are checking structural equivalence.
160 ASTContext &C1, &C2;
161
162 /// \brief The set of "tentative" equivalences between two canonical
163 /// declarations, mapping from a declaration in the first context to the
164 /// declaration in the second context that we believe to be equivalent.
165 llvm::DenseMap<Decl *, Decl *> TentativeEquivalences;
166
167 /// \brief Queue of declarations in the first context whose equivalence
168 /// with a declaration in the second context still needs to be verified.
169 std::deque<Decl *> DeclsToCheck;
170
171 /// \brief Declaration (from, to) pairs that are known not to be equivalent
172 /// (which we have already complained about).
173 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls;
174
175 /// \brief Whether we're being strict about the spelling of types when
176 /// unifying two types.
177 bool StrictTypeSpelling;
178
StructuralEquivalenceContext__anon2b7705100211::StructuralEquivalenceContext179 StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2,
180 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls,
181 bool StrictTypeSpelling = false)
182 : C1(C1), C2(C2), NonEquivalentDecls(NonEquivalentDecls),
183 StrictTypeSpelling(StrictTypeSpelling) { }
184
185 /// \brief Determine whether the two declarations are structurally
186 /// equivalent.
187 bool IsStructurallyEquivalent(Decl *D1, Decl *D2);
188
189 /// \brief Determine whether the two types are structurally equivalent.
190 bool IsStructurallyEquivalent(QualType T1, QualType T2);
191
192 private:
193 /// \brief Finish checking all of the structural equivalences.
194 ///
195 /// \returns true if an error occurred, false otherwise.
196 bool Finish();
197
198 public:
Diag1__anon2b7705100211::StructuralEquivalenceContext199 DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) {
200 return C1.getDiagnostics().Report(Loc, DiagID);
201 }
202
Diag2__anon2b7705100211::StructuralEquivalenceContext203 DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) {
204 return C2.getDiagnostics().Report(Loc, DiagID);
205 }
206 };
207 }
208
209 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
210 QualType T1, QualType T2);
211 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
212 Decl *D1, Decl *D2);
213
214 /// \brief Determine if two APInts have the same value, after zero-extending
215 /// one of them (if needed!) to ensure that the bit-widths match.
IsSameValue(const llvm::APInt & I1,const llvm::APInt & I2)216 static bool IsSameValue(const llvm::APInt &I1, const llvm::APInt &I2) {
217 if (I1.getBitWidth() == I2.getBitWidth())
218 return I1 == I2;
219
220 if (I1.getBitWidth() > I2.getBitWidth())
221 return I1 == I2.zext(I1.getBitWidth());
222
223 return I1.zext(I2.getBitWidth()) == I2;
224 }
225
226 /// \brief Determine if two APSInts have the same value, zero- or sign-extending
227 /// as needed.
IsSameValue(const llvm::APSInt & I1,const llvm::APSInt & I2)228 static bool IsSameValue(const llvm::APSInt &I1, const llvm::APSInt &I2) {
229 if (I1.getBitWidth() == I2.getBitWidth() && I1.isSigned() == I2.isSigned())
230 return I1 == I2;
231
232 // Check for a bit-width mismatch.
233 if (I1.getBitWidth() > I2.getBitWidth())
234 return IsSameValue(I1, I2.extend(I1.getBitWidth()));
235 else if (I2.getBitWidth() > I1.getBitWidth())
236 return IsSameValue(I1.extend(I2.getBitWidth()), I2);
237
238 // We have a signedness mismatch. Turn the signed value into an unsigned
239 // value.
240 if (I1.isSigned()) {
241 if (I1.isNegative())
242 return false;
243
244 return llvm::APSInt(I1, true) == I2;
245 }
246
247 if (I2.isNegative())
248 return false;
249
250 return I1 == llvm::APSInt(I2, true);
251 }
252
253 /// \brief Determine structural equivalence of two expressions.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,Expr * E1,Expr * E2)254 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
255 Expr *E1, Expr *E2) {
256 if (!E1 || !E2)
257 return E1 == E2;
258
259 // FIXME: Actually perform a structural comparison!
260 return true;
261 }
262
263 /// \brief Determine whether two identifiers are equivalent.
IsStructurallyEquivalent(const IdentifierInfo * Name1,const IdentifierInfo * Name2)264 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
265 const IdentifierInfo *Name2) {
266 if (!Name1 || !Name2)
267 return Name1 == Name2;
268
269 return Name1->getName() == Name2->getName();
270 }
271
272 /// \brief Determine whether two nested-name-specifiers are equivalent.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,NestedNameSpecifier * NNS1,NestedNameSpecifier * NNS2)273 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
274 NestedNameSpecifier *NNS1,
275 NestedNameSpecifier *NNS2) {
276 // FIXME: Implement!
277 return true;
278 }
279
280 /// \brief Determine whether two template arguments are equivalent.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,const TemplateArgument & Arg1,const TemplateArgument & Arg2)281 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
282 const TemplateArgument &Arg1,
283 const TemplateArgument &Arg2) {
284 if (Arg1.getKind() != Arg2.getKind())
285 return false;
286
287 switch (Arg1.getKind()) {
288 case TemplateArgument::Null:
289 return true;
290
291 case TemplateArgument::Type:
292 return Context.IsStructurallyEquivalent(Arg1.getAsType(), Arg2.getAsType());
293
294 case TemplateArgument::Integral:
295 if (!Context.IsStructurallyEquivalent(Arg1.getIntegralType(),
296 Arg2.getIntegralType()))
297 return false;
298
299 return IsSameValue(*Arg1.getAsIntegral(), *Arg2.getAsIntegral());
300
301 case TemplateArgument::Declaration:
302 return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDecl());
303
304 case TemplateArgument::Template:
305 return IsStructurallyEquivalent(Context,
306 Arg1.getAsTemplate(),
307 Arg2.getAsTemplate());
308
309 case TemplateArgument::TemplateExpansion:
310 return IsStructurallyEquivalent(Context,
311 Arg1.getAsTemplateOrTemplatePattern(),
312 Arg2.getAsTemplateOrTemplatePattern());
313
314 case TemplateArgument::Expression:
315 return IsStructurallyEquivalent(Context,
316 Arg1.getAsExpr(), Arg2.getAsExpr());
317
318 case TemplateArgument::Pack:
319 if (Arg1.pack_size() != Arg2.pack_size())
320 return false;
321
322 for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I)
323 if (!IsStructurallyEquivalent(Context,
324 Arg1.pack_begin()[I],
325 Arg2.pack_begin()[I]))
326 return false;
327
328 return true;
329 }
330
331 llvm_unreachable("Invalid template argument kind");
332 return true;
333 }
334
335 /// \brief Determine structural equivalence for the common part of array
336 /// types.
IsArrayStructurallyEquivalent(StructuralEquivalenceContext & Context,const ArrayType * Array1,const ArrayType * Array2)337 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
338 const ArrayType *Array1,
339 const ArrayType *Array2) {
340 if (!IsStructurallyEquivalent(Context,
341 Array1->getElementType(),
342 Array2->getElementType()))
343 return false;
344 if (Array1->getSizeModifier() != Array2->getSizeModifier())
345 return false;
346 if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
347 return false;
348
349 return true;
350 }
351
352 /// \brief Determine structural equivalence of two types.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,QualType T1,QualType T2)353 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
354 QualType T1, QualType T2) {
355 if (T1.isNull() || T2.isNull())
356 return T1.isNull() && T2.isNull();
357
358 if (!Context.StrictTypeSpelling) {
359 // We aren't being strict about token-to-token equivalence of types,
360 // so map down to the canonical type.
361 T1 = Context.C1.getCanonicalType(T1);
362 T2 = Context.C2.getCanonicalType(T2);
363 }
364
365 if (T1.getQualifiers() != T2.getQualifiers())
366 return false;
367
368 Type::TypeClass TC = T1->getTypeClass();
369
370 if (T1->getTypeClass() != T2->getTypeClass()) {
371 // Compare function types with prototypes vs. without prototypes as if
372 // both did not have prototypes.
373 if (T1->getTypeClass() == Type::FunctionProto &&
374 T2->getTypeClass() == Type::FunctionNoProto)
375 TC = Type::FunctionNoProto;
376 else if (T1->getTypeClass() == Type::FunctionNoProto &&
377 T2->getTypeClass() == Type::FunctionProto)
378 TC = Type::FunctionNoProto;
379 else
380 return false;
381 }
382
383 switch (TC) {
384 case Type::Builtin:
385 // FIXME: Deal with Char_S/Char_U.
386 if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
387 return false;
388 break;
389
390 case Type::Complex:
391 if (!IsStructurallyEquivalent(Context,
392 cast<ComplexType>(T1)->getElementType(),
393 cast<ComplexType>(T2)->getElementType()))
394 return false;
395 break;
396
397 case Type::Pointer:
398 if (!IsStructurallyEquivalent(Context,
399 cast<PointerType>(T1)->getPointeeType(),
400 cast<PointerType>(T2)->getPointeeType()))
401 return false;
402 break;
403
404 case Type::BlockPointer:
405 if (!IsStructurallyEquivalent(Context,
406 cast<BlockPointerType>(T1)->getPointeeType(),
407 cast<BlockPointerType>(T2)->getPointeeType()))
408 return false;
409 break;
410
411 case Type::LValueReference:
412 case Type::RValueReference: {
413 const ReferenceType *Ref1 = cast<ReferenceType>(T1);
414 const ReferenceType *Ref2 = cast<ReferenceType>(T2);
415 if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
416 return false;
417 if (Ref1->isInnerRef() != Ref2->isInnerRef())
418 return false;
419 if (!IsStructurallyEquivalent(Context,
420 Ref1->getPointeeTypeAsWritten(),
421 Ref2->getPointeeTypeAsWritten()))
422 return false;
423 break;
424 }
425
426 case Type::MemberPointer: {
427 const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
428 const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
429 if (!IsStructurallyEquivalent(Context,
430 MemPtr1->getPointeeType(),
431 MemPtr2->getPointeeType()))
432 return false;
433 if (!IsStructurallyEquivalent(Context,
434 QualType(MemPtr1->getClass(), 0),
435 QualType(MemPtr2->getClass(), 0)))
436 return false;
437 break;
438 }
439
440 case Type::ConstantArray: {
441 const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
442 const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
443 if (!IsSameValue(Array1->getSize(), Array2->getSize()))
444 return false;
445
446 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
447 return false;
448 break;
449 }
450
451 case Type::IncompleteArray:
452 if (!IsArrayStructurallyEquivalent(Context,
453 cast<ArrayType>(T1),
454 cast<ArrayType>(T2)))
455 return false;
456 break;
457
458 case Type::VariableArray: {
459 const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
460 const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
461 if (!IsStructurallyEquivalent(Context,
462 Array1->getSizeExpr(), Array2->getSizeExpr()))
463 return false;
464
465 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
466 return false;
467
468 break;
469 }
470
471 case Type::DependentSizedArray: {
472 const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
473 const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
474 if (!IsStructurallyEquivalent(Context,
475 Array1->getSizeExpr(), Array2->getSizeExpr()))
476 return false;
477
478 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
479 return false;
480
481 break;
482 }
483
484 case Type::DependentSizedExtVector: {
485 const DependentSizedExtVectorType *Vec1
486 = cast<DependentSizedExtVectorType>(T1);
487 const DependentSizedExtVectorType *Vec2
488 = cast<DependentSizedExtVectorType>(T2);
489 if (!IsStructurallyEquivalent(Context,
490 Vec1->getSizeExpr(), Vec2->getSizeExpr()))
491 return false;
492 if (!IsStructurallyEquivalent(Context,
493 Vec1->getElementType(),
494 Vec2->getElementType()))
495 return false;
496 break;
497 }
498
499 case Type::Vector:
500 case Type::ExtVector: {
501 const VectorType *Vec1 = cast<VectorType>(T1);
502 const VectorType *Vec2 = cast<VectorType>(T2);
503 if (!IsStructurallyEquivalent(Context,
504 Vec1->getElementType(),
505 Vec2->getElementType()))
506 return false;
507 if (Vec1->getNumElements() != Vec2->getNumElements())
508 return false;
509 if (Vec1->getVectorKind() != Vec2->getVectorKind())
510 return false;
511 break;
512 }
513
514 case Type::FunctionProto: {
515 const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
516 const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
517 if (Proto1->getNumArgs() != Proto2->getNumArgs())
518 return false;
519 for (unsigned I = 0, N = Proto1->getNumArgs(); I != N; ++I) {
520 if (!IsStructurallyEquivalent(Context,
521 Proto1->getArgType(I),
522 Proto2->getArgType(I)))
523 return false;
524 }
525 if (Proto1->isVariadic() != Proto2->isVariadic())
526 return false;
527 if (Proto1->getExceptionSpecType() != Proto2->getExceptionSpecType())
528 return false;
529 if (Proto1->getExceptionSpecType() == EST_Dynamic) {
530 if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
531 return false;
532 for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
533 if (!IsStructurallyEquivalent(Context,
534 Proto1->getExceptionType(I),
535 Proto2->getExceptionType(I)))
536 return false;
537 }
538 } else if (Proto1->getExceptionSpecType() == EST_ComputedNoexcept) {
539 if (!IsStructurallyEquivalent(Context,
540 Proto1->getNoexceptExpr(),
541 Proto2->getNoexceptExpr()))
542 return false;
543 }
544 if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
545 return false;
546
547 // Fall through to check the bits common with FunctionNoProtoType.
548 }
549
550 case Type::FunctionNoProto: {
551 const FunctionType *Function1 = cast<FunctionType>(T1);
552 const FunctionType *Function2 = cast<FunctionType>(T2);
553 if (!IsStructurallyEquivalent(Context,
554 Function1->getResultType(),
555 Function2->getResultType()))
556 return false;
557 if (Function1->getExtInfo() != Function2->getExtInfo())
558 return false;
559 break;
560 }
561
562 case Type::UnresolvedUsing:
563 if (!IsStructurallyEquivalent(Context,
564 cast<UnresolvedUsingType>(T1)->getDecl(),
565 cast<UnresolvedUsingType>(T2)->getDecl()))
566 return false;
567
568 break;
569
570 case Type::Attributed:
571 if (!IsStructurallyEquivalent(Context,
572 cast<AttributedType>(T1)->getModifiedType(),
573 cast<AttributedType>(T2)->getModifiedType()))
574 return false;
575 if (!IsStructurallyEquivalent(Context,
576 cast<AttributedType>(T1)->getEquivalentType(),
577 cast<AttributedType>(T2)->getEquivalentType()))
578 return false;
579 break;
580
581 case Type::Paren:
582 if (!IsStructurallyEquivalent(Context,
583 cast<ParenType>(T1)->getInnerType(),
584 cast<ParenType>(T2)->getInnerType()))
585 return false;
586 break;
587
588 case Type::Typedef:
589 if (!IsStructurallyEquivalent(Context,
590 cast<TypedefType>(T1)->getDecl(),
591 cast<TypedefType>(T2)->getDecl()))
592 return false;
593 break;
594
595 case Type::TypeOfExpr:
596 if (!IsStructurallyEquivalent(Context,
597 cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
598 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
599 return false;
600 break;
601
602 case Type::TypeOf:
603 if (!IsStructurallyEquivalent(Context,
604 cast<TypeOfType>(T1)->getUnderlyingType(),
605 cast<TypeOfType>(T2)->getUnderlyingType()))
606 return false;
607 break;
608
609 case Type::UnaryTransform:
610 if (!IsStructurallyEquivalent(Context,
611 cast<UnaryTransformType>(T1)->getUnderlyingType(),
612 cast<UnaryTransformType>(T1)->getUnderlyingType()))
613 return false;
614 break;
615
616 case Type::Decltype:
617 if (!IsStructurallyEquivalent(Context,
618 cast<DecltypeType>(T1)->getUnderlyingExpr(),
619 cast<DecltypeType>(T2)->getUnderlyingExpr()))
620 return false;
621 break;
622
623 case Type::Auto:
624 if (!IsStructurallyEquivalent(Context,
625 cast<AutoType>(T1)->getDeducedType(),
626 cast<AutoType>(T2)->getDeducedType()))
627 return false;
628 break;
629
630 case Type::Record:
631 case Type::Enum:
632 if (!IsStructurallyEquivalent(Context,
633 cast<TagType>(T1)->getDecl(),
634 cast<TagType>(T2)->getDecl()))
635 return false;
636 break;
637
638 case Type::TemplateTypeParm: {
639 const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
640 const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
641 if (Parm1->getDepth() != Parm2->getDepth())
642 return false;
643 if (Parm1->getIndex() != Parm2->getIndex())
644 return false;
645 if (Parm1->isParameterPack() != Parm2->isParameterPack())
646 return false;
647
648 // Names of template type parameters are never significant.
649 break;
650 }
651
652 case Type::SubstTemplateTypeParm: {
653 const SubstTemplateTypeParmType *Subst1
654 = cast<SubstTemplateTypeParmType>(T1);
655 const SubstTemplateTypeParmType *Subst2
656 = cast<SubstTemplateTypeParmType>(T2);
657 if (!IsStructurallyEquivalent(Context,
658 QualType(Subst1->getReplacedParameter(), 0),
659 QualType(Subst2->getReplacedParameter(), 0)))
660 return false;
661 if (!IsStructurallyEquivalent(Context,
662 Subst1->getReplacementType(),
663 Subst2->getReplacementType()))
664 return false;
665 break;
666 }
667
668 case Type::SubstTemplateTypeParmPack: {
669 const SubstTemplateTypeParmPackType *Subst1
670 = cast<SubstTemplateTypeParmPackType>(T1);
671 const SubstTemplateTypeParmPackType *Subst2
672 = cast<SubstTemplateTypeParmPackType>(T2);
673 if (!IsStructurallyEquivalent(Context,
674 QualType(Subst1->getReplacedParameter(), 0),
675 QualType(Subst2->getReplacedParameter(), 0)))
676 return false;
677 if (!IsStructurallyEquivalent(Context,
678 Subst1->getArgumentPack(),
679 Subst2->getArgumentPack()))
680 return false;
681 break;
682 }
683 case Type::TemplateSpecialization: {
684 const TemplateSpecializationType *Spec1
685 = cast<TemplateSpecializationType>(T1);
686 const TemplateSpecializationType *Spec2
687 = cast<TemplateSpecializationType>(T2);
688 if (!IsStructurallyEquivalent(Context,
689 Spec1->getTemplateName(),
690 Spec2->getTemplateName()))
691 return false;
692 if (Spec1->getNumArgs() != Spec2->getNumArgs())
693 return false;
694 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
695 if (!IsStructurallyEquivalent(Context,
696 Spec1->getArg(I), Spec2->getArg(I)))
697 return false;
698 }
699 break;
700 }
701
702 case Type::Elaborated: {
703 const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
704 const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
705 // CHECKME: what if a keyword is ETK_None or ETK_typename ?
706 if (Elab1->getKeyword() != Elab2->getKeyword())
707 return false;
708 if (!IsStructurallyEquivalent(Context,
709 Elab1->getQualifier(),
710 Elab2->getQualifier()))
711 return false;
712 if (!IsStructurallyEquivalent(Context,
713 Elab1->getNamedType(),
714 Elab2->getNamedType()))
715 return false;
716 break;
717 }
718
719 case Type::InjectedClassName: {
720 const InjectedClassNameType *Inj1 = cast<InjectedClassNameType>(T1);
721 const InjectedClassNameType *Inj2 = cast<InjectedClassNameType>(T2);
722 if (!IsStructurallyEquivalent(Context,
723 Inj1->getInjectedSpecializationType(),
724 Inj2->getInjectedSpecializationType()))
725 return false;
726 break;
727 }
728
729 case Type::DependentName: {
730 const DependentNameType *Typename1 = cast<DependentNameType>(T1);
731 const DependentNameType *Typename2 = cast<DependentNameType>(T2);
732 if (!IsStructurallyEquivalent(Context,
733 Typename1->getQualifier(),
734 Typename2->getQualifier()))
735 return false;
736 if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
737 Typename2->getIdentifier()))
738 return false;
739
740 break;
741 }
742
743 case Type::DependentTemplateSpecialization: {
744 const DependentTemplateSpecializationType *Spec1 =
745 cast<DependentTemplateSpecializationType>(T1);
746 const DependentTemplateSpecializationType *Spec2 =
747 cast<DependentTemplateSpecializationType>(T2);
748 if (!IsStructurallyEquivalent(Context,
749 Spec1->getQualifier(),
750 Spec2->getQualifier()))
751 return false;
752 if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
753 Spec2->getIdentifier()))
754 return false;
755 if (Spec1->getNumArgs() != Spec2->getNumArgs())
756 return false;
757 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
758 if (!IsStructurallyEquivalent(Context,
759 Spec1->getArg(I), Spec2->getArg(I)))
760 return false;
761 }
762 break;
763 }
764
765 case Type::PackExpansion:
766 if (!IsStructurallyEquivalent(Context,
767 cast<PackExpansionType>(T1)->getPattern(),
768 cast<PackExpansionType>(T2)->getPattern()))
769 return false;
770 break;
771
772 case Type::ObjCInterface: {
773 const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
774 const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
775 if (!IsStructurallyEquivalent(Context,
776 Iface1->getDecl(), Iface2->getDecl()))
777 return false;
778 break;
779 }
780
781 case Type::ObjCObject: {
782 const ObjCObjectType *Obj1 = cast<ObjCObjectType>(T1);
783 const ObjCObjectType *Obj2 = cast<ObjCObjectType>(T2);
784 if (!IsStructurallyEquivalent(Context,
785 Obj1->getBaseType(),
786 Obj2->getBaseType()))
787 return false;
788 if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
789 return false;
790 for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
791 if (!IsStructurallyEquivalent(Context,
792 Obj1->getProtocol(I),
793 Obj2->getProtocol(I)))
794 return false;
795 }
796 break;
797 }
798
799 case Type::ObjCObjectPointer: {
800 const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
801 const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
802 if (!IsStructurallyEquivalent(Context,
803 Ptr1->getPointeeType(),
804 Ptr2->getPointeeType()))
805 return false;
806 break;
807 }
808
809 } // end switch
810
811 return true;
812 }
813
814 /// \brief Determine structural equivalence of two records.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,RecordDecl * D1,RecordDecl * D2)815 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
816 RecordDecl *D1, RecordDecl *D2) {
817 if (D1->isUnion() != D2->isUnion()) {
818 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
819 << Context.C2.getTypeDeclType(D2);
820 Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
821 << D1->getDeclName() << (unsigned)D1->getTagKind();
822 return false;
823 }
824
825 // If both declarations are class template specializations, we know
826 // the ODR applies, so check the template and template arguments.
827 ClassTemplateSpecializationDecl *Spec1
828 = dyn_cast<ClassTemplateSpecializationDecl>(D1);
829 ClassTemplateSpecializationDecl *Spec2
830 = dyn_cast<ClassTemplateSpecializationDecl>(D2);
831 if (Spec1 && Spec2) {
832 // Check that the specialized templates are the same.
833 if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
834 Spec2->getSpecializedTemplate()))
835 return false;
836
837 // Check that the template arguments are the same.
838 if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
839 return false;
840
841 for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
842 if (!IsStructurallyEquivalent(Context,
843 Spec1->getTemplateArgs().get(I),
844 Spec2->getTemplateArgs().get(I)))
845 return false;
846 }
847 // If one is a class template specialization and the other is not, these
848 // structures are different.
849 else if (Spec1 || Spec2)
850 return false;
851
852 // Compare the definitions of these two records. If either or both are
853 // incomplete, we assume that they are equivalent.
854 D1 = D1->getDefinition();
855 D2 = D2->getDefinition();
856 if (!D1 || !D2)
857 return true;
858
859 if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
860 if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
861 if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
862 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
863 << Context.C2.getTypeDeclType(D2);
864 Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
865 << D2CXX->getNumBases();
866 Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
867 << D1CXX->getNumBases();
868 return false;
869 }
870
871 // Check the base classes.
872 for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(),
873 BaseEnd1 = D1CXX->bases_end(),
874 Base2 = D2CXX->bases_begin();
875 Base1 != BaseEnd1;
876 ++Base1, ++Base2) {
877 if (!IsStructurallyEquivalent(Context,
878 Base1->getType(), Base2->getType())) {
879 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
880 << Context.C2.getTypeDeclType(D2);
881 Context.Diag2(Base2->getSourceRange().getBegin(), diag::note_odr_base)
882 << Base2->getType()
883 << Base2->getSourceRange();
884 Context.Diag1(Base1->getSourceRange().getBegin(), diag::note_odr_base)
885 << Base1->getType()
886 << Base1->getSourceRange();
887 return false;
888 }
889
890 // Check virtual vs. non-virtual inheritance mismatch.
891 if (Base1->isVirtual() != Base2->isVirtual()) {
892 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
893 << Context.C2.getTypeDeclType(D2);
894 Context.Diag2(Base2->getSourceRange().getBegin(),
895 diag::note_odr_virtual_base)
896 << Base2->isVirtual() << Base2->getSourceRange();
897 Context.Diag1(Base1->getSourceRange().getBegin(), diag::note_odr_base)
898 << Base1->isVirtual()
899 << Base1->getSourceRange();
900 return false;
901 }
902 }
903 } else if (D1CXX->getNumBases() > 0) {
904 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
905 << Context.C2.getTypeDeclType(D2);
906 const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
907 Context.Diag1(Base1->getSourceRange().getBegin(), diag::note_odr_base)
908 << Base1->getType()
909 << Base1->getSourceRange();
910 Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
911 return false;
912 }
913 }
914
915 // Check the fields for consistency.
916 CXXRecordDecl::field_iterator Field2 = D2->field_begin(),
917 Field2End = D2->field_end();
918 for (CXXRecordDecl::field_iterator Field1 = D1->field_begin(),
919 Field1End = D1->field_end();
920 Field1 != Field1End;
921 ++Field1, ++Field2) {
922 if (Field2 == Field2End) {
923 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
924 << Context.C2.getTypeDeclType(D2);
925 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
926 << Field1->getDeclName() << Field1->getType();
927 Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
928 return false;
929 }
930
931 if (!IsStructurallyEquivalent(Context,
932 Field1->getType(), Field2->getType())) {
933 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
934 << Context.C2.getTypeDeclType(D2);
935 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
936 << Field2->getDeclName() << Field2->getType();
937 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
938 << Field1->getDeclName() << Field1->getType();
939 return false;
940 }
941
942 if (Field1->isBitField() != Field2->isBitField()) {
943 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
944 << Context.C2.getTypeDeclType(D2);
945 if (Field1->isBitField()) {
946 llvm::APSInt Bits;
947 Field1->getBitWidth()->isIntegerConstantExpr(Bits, Context.C1);
948 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
949 << Field1->getDeclName() << Field1->getType()
950 << Bits.toString(10, false);
951 Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
952 << Field2->getDeclName();
953 } else {
954 llvm::APSInt Bits;
955 Field2->getBitWidth()->isIntegerConstantExpr(Bits, Context.C2);
956 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
957 << Field2->getDeclName() << Field2->getType()
958 << Bits.toString(10, false);
959 Context.Diag1(Field1->getLocation(),
960 diag::note_odr_not_bit_field)
961 << Field1->getDeclName();
962 }
963 return false;
964 }
965
966 if (Field1->isBitField()) {
967 // Make sure that the bit-fields are the same length.
968 llvm::APSInt Bits1, Bits2;
969 if (!Field1->getBitWidth()->isIntegerConstantExpr(Bits1, Context.C1))
970 return false;
971 if (!Field2->getBitWidth()->isIntegerConstantExpr(Bits2, Context.C2))
972 return false;
973
974 if (!IsSameValue(Bits1, Bits2)) {
975 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
976 << Context.C2.getTypeDeclType(D2);
977 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
978 << Field2->getDeclName() << Field2->getType()
979 << Bits2.toString(10, false);
980 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
981 << Field1->getDeclName() << Field1->getType()
982 << Bits1.toString(10, false);
983 return false;
984 }
985 }
986 }
987
988 if (Field2 != Field2End) {
989 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
990 << Context.C2.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 return false;
995 }
996
997 return true;
998 }
999
1000 /// \brief Determine structural equivalence of two enums.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,EnumDecl * D1,EnumDecl * D2)1001 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1002 EnumDecl *D1, EnumDecl *D2) {
1003 EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
1004 EC2End = D2->enumerator_end();
1005 for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
1006 EC1End = D1->enumerator_end();
1007 EC1 != EC1End; ++EC1, ++EC2) {
1008 if (EC2 == EC2End) {
1009 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1010 << Context.C2.getTypeDeclType(D2);
1011 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1012 << EC1->getDeclName()
1013 << EC1->getInitVal().toString(10);
1014 Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
1015 return false;
1016 }
1017
1018 llvm::APSInt Val1 = EC1->getInitVal();
1019 llvm::APSInt Val2 = EC2->getInitVal();
1020 if (!IsSameValue(Val1, Val2) ||
1021 !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
1022 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1023 << Context.C2.getTypeDeclType(D2);
1024 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1025 << EC2->getDeclName()
1026 << EC2->getInitVal().toString(10);
1027 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1028 << EC1->getDeclName()
1029 << EC1->getInitVal().toString(10);
1030 return false;
1031 }
1032 }
1033
1034 if (EC2 != EC2End) {
1035 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1036 << Context.C2.getTypeDeclType(D2);
1037 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1038 << EC2->getDeclName()
1039 << EC2->getInitVal().toString(10);
1040 Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
1041 return false;
1042 }
1043
1044 return true;
1045 }
1046
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,TemplateParameterList * Params1,TemplateParameterList * Params2)1047 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1048 TemplateParameterList *Params1,
1049 TemplateParameterList *Params2) {
1050 if (Params1->size() != Params2->size()) {
1051 Context.Diag2(Params2->getTemplateLoc(),
1052 diag::err_odr_different_num_template_parameters)
1053 << Params1->size() << Params2->size();
1054 Context.Diag1(Params1->getTemplateLoc(),
1055 diag::note_odr_template_parameter_list);
1056 return false;
1057 }
1058
1059 for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
1060 if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
1061 Context.Diag2(Params2->getParam(I)->getLocation(),
1062 diag::err_odr_different_template_parameter_kind);
1063 Context.Diag1(Params1->getParam(I)->getLocation(),
1064 diag::note_odr_template_parameter_here);
1065 return false;
1066 }
1067
1068 if (!Context.IsStructurallyEquivalent(Params1->getParam(I),
1069 Params2->getParam(I))) {
1070
1071 return false;
1072 }
1073 }
1074
1075 return true;
1076 }
1077
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,TemplateTypeParmDecl * D1,TemplateTypeParmDecl * D2)1078 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1079 TemplateTypeParmDecl *D1,
1080 TemplateTypeParmDecl *D2) {
1081 if (D1->isParameterPack() != D2->isParameterPack()) {
1082 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1083 << D2->isParameterPack();
1084 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1085 << D1->isParameterPack();
1086 return false;
1087 }
1088
1089 return true;
1090 }
1091
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,NonTypeTemplateParmDecl * D1,NonTypeTemplateParmDecl * D2)1092 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1093 NonTypeTemplateParmDecl *D1,
1094 NonTypeTemplateParmDecl *D2) {
1095 // FIXME: Enable once we have variadic templates.
1096 #if 0
1097 if (D1->isParameterPack() != D2->isParameterPack()) {
1098 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1099 << D2->isParameterPack();
1100 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1101 << D1->isParameterPack();
1102 return false;
1103 }
1104 #endif
1105
1106 // Check types.
1107 if (!Context.IsStructurallyEquivalent(D1->getType(), D2->getType())) {
1108 Context.Diag2(D2->getLocation(),
1109 diag::err_odr_non_type_parameter_type_inconsistent)
1110 << D2->getType() << D1->getType();
1111 Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
1112 << D1->getType();
1113 return false;
1114 }
1115
1116 return true;
1117 }
1118
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,TemplateTemplateParmDecl * D1,TemplateTemplateParmDecl * D2)1119 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1120 TemplateTemplateParmDecl *D1,
1121 TemplateTemplateParmDecl *D2) {
1122 // FIXME: Enable once we have variadic templates.
1123 #if 0
1124 if (D1->isParameterPack() != D2->isParameterPack()) {
1125 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1126 << D2->isParameterPack();
1127 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1128 << D1->isParameterPack();
1129 return false;
1130 }
1131 #endif
1132
1133 // Check template parameter lists.
1134 return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1135 D2->getTemplateParameters());
1136 }
1137
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,ClassTemplateDecl * D1,ClassTemplateDecl * D2)1138 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1139 ClassTemplateDecl *D1,
1140 ClassTemplateDecl *D2) {
1141 // Check template parameters.
1142 if (!IsStructurallyEquivalent(Context,
1143 D1->getTemplateParameters(),
1144 D2->getTemplateParameters()))
1145 return false;
1146
1147 // Check the templated declaration.
1148 return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(),
1149 D2->getTemplatedDecl());
1150 }
1151
1152 /// \brief Determine structural equivalence of two declarations.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,Decl * D1,Decl * D2)1153 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1154 Decl *D1, Decl *D2) {
1155 // FIXME: Check for known structural equivalences via a callback of some sort.
1156
1157 // Check whether we already know that these two declarations are not
1158 // structurally equivalent.
1159 if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(),
1160 D2->getCanonicalDecl())))
1161 return false;
1162
1163 // Determine whether we've already produced a tentative equivalence for D1.
1164 Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
1165 if (EquivToD1)
1166 return EquivToD1 == D2->getCanonicalDecl();
1167
1168 // Produce a tentative equivalence D1 <-> D2, which will be checked later.
1169 EquivToD1 = D2->getCanonicalDecl();
1170 Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
1171 return true;
1172 }
1173
IsStructurallyEquivalent(Decl * D1,Decl * D2)1174 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1,
1175 Decl *D2) {
1176 if (!::IsStructurallyEquivalent(*this, D1, D2))
1177 return false;
1178
1179 return !Finish();
1180 }
1181
IsStructurallyEquivalent(QualType T1,QualType T2)1182 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1,
1183 QualType T2) {
1184 if (!::IsStructurallyEquivalent(*this, T1, T2))
1185 return false;
1186
1187 return !Finish();
1188 }
1189
Finish()1190 bool StructuralEquivalenceContext::Finish() {
1191 while (!DeclsToCheck.empty()) {
1192 // Check the next declaration.
1193 Decl *D1 = DeclsToCheck.front();
1194 DeclsToCheck.pop_front();
1195
1196 Decl *D2 = TentativeEquivalences[D1];
1197 assert(D2 && "Unrecorded tentative equivalence?");
1198
1199 bool Equivalent = true;
1200
1201 // FIXME: Switch on all declaration kinds. For now, we're just going to
1202 // check the obvious ones.
1203 if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
1204 if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
1205 // Check for equivalent structure names.
1206 IdentifierInfo *Name1 = Record1->getIdentifier();
1207 if (!Name1 && Record1->getTypedefNameForAnonDecl())
1208 Name1 = Record1->getTypedefNameForAnonDecl()->getIdentifier();
1209 IdentifierInfo *Name2 = Record2->getIdentifier();
1210 if (!Name2 && Record2->getTypedefNameForAnonDecl())
1211 Name2 = Record2->getTypedefNameForAnonDecl()->getIdentifier();
1212 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1213 !::IsStructurallyEquivalent(*this, Record1, Record2))
1214 Equivalent = false;
1215 } else {
1216 // Record/non-record mismatch.
1217 Equivalent = false;
1218 }
1219 } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
1220 if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
1221 // Check for equivalent enum names.
1222 IdentifierInfo *Name1 = Enum1->getIdentifier();
1223 if (!Name1 && Enum1->getTypedefNameForAnonDecl())
1224 Name1 = Enum1->getTypedefNameForAnonDecl()->getIdentifier();
1225 IdentifierInfo *Name2 = Enum2->getIdentifier();
1226 if (!Name2 && Enum2->getTypedefNameForAnonDecl())
1227 Name2 = Enum2->getTypedefNameForAnonDecl()->getIdentifier();
1228 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1229 !::IsStructurallyEquivalent(*this, Enum1, Enum2))
1230 Equivalent = false;
1231 } else {
1232 // Enum/non-enum mismatch
1233 Equivalent = false;
1234 }
1235 } else if (TypedefNameDecl *Typedef1 = dyn_cast<TypedefNameDecl>(D1)) {
1236 if (TypedefNameDecl *Typedef2 = dyn_cast<TypedefNameDecl>(D2)) {
1237 if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
1238 Typedef2->getIdentifier()) ||
1239 !::IsStructurallyEquivalent(*this,
1240 Typedef1->getUnderlyingType(),
1241 Typedef2->getUnderlyingType()))
1242 Equivalent = false;
1243 } else {
1244 // Typedef/non-typedef mismatch.
1245 Equivalent = false;
1246 }
1247 } else if (ClassTemplateDecl *ClassTemplate1
1248 = dyn_cast<ClassTemplateDecl>(D1)) {
1249 if (ClassTemplateDecl *ClassTemplate2 = dyn_cast<ClassTemplateDecl>(D2)) {
1250 if (!::IsStructurallyEquivalent(ClassTemplate1->getIdentifier(),
1251 ClassTemplate2->getIdentifier()) ||
1252 !::IsStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2))
1253 Equivalent = false;
1254 } else {
1255 // Class template/non-class-template mismatch.
1256 Equivalent = false;
1257 }
1258 } else if (TemplateTypeParmDecl *TTP1= dyn_cast<TemplateTypeParmDecl>(D1)) {
1259 if (TemplateTypeParmDecl *TTP2 = dyn_cast<TemplateTypeParmDecl>(D2)) {
1260 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1261 Equivalent = false;
1262 } else {
1263 // Kind mismatch.
1264 Equivalent = false;
1265 }
1266 } else if (NonTypeTemplateParmDecl *NTTP1
1267 = dyn_cast<NonTypeTemplateParmDecl>(D1)) {
1268 if (NonTypeTemplateParmDecl *NTTP2
1269 = dyn_cast<NonTypeTemplateParmDecl>(D2)) {
1270 if (!::IsStructurallyEquivalent(*this, NTTP1, NTTP2))
1271 Equivalent = false;
1272 } else {
1273 // Kind mismatch.
1274 Equivalent = false;
1275 }
1276 } else if (TemplateTemplateParmDecl *TTP1
1277 = dyn_cast<TemplateTemplateParmDecl>(D1)) {
1278 if (TemplateTemplateParmDecl *TTP2
1279 = dyn_cast<TemplateTemplateParmDecl>(D2)) {
1280 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1281 Equivalent = false;
1282 } else {
1283 // Kind mismatch.
1284 Equivalent = false;
1285 }
1286 }
1287
1288 if (!Equivalent) {
1289 // Note that these two declarations are not equivalent (and we already
1290 // know about it).
1291 NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(),
1292 D2->getCanonicalDecl()));
1293 return true;
1294 }
1295 // FIXME: Check other declaration kinds!
1296 }
1297
1298 return false;
1299 }
1300
1301 //----------------------------------------------------------------------------
1302 // Import Types
1303 //----------------------------------------------------------------------------
1304
VisitType(const Type * T)1305 QualType ASTNodeImporter::VisitType(const Type *T) {
1306 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1307 << T->getTypeClassName();
1308 return QualType();
1309 }
1310
VisitBuiltinType(const BuiltinType * T)1311 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1312 switch (T->getKind()) {
1313 case BuiltinType::Void: return Importer.getToContext().VoidTy;
1314 case BuiltinType::Bool: return Importer.getToContext().BoolTy;
1315
1316 case BuiltinType::Char_U:
1317 // The context we're importing from has an unsigned 'char'. If we're
1318 // importing into a context with a signed 'char', translate to
1319 // 'unsigned char' instead.
1320 if (Importer.getToContext().getLangOptions().CharIsSigned)
1321 return Importer.getToContext().UnsignedCharTy;
1322
1323 return Importer.getToContext().CharTy;
1324
1325 case BuiltinType::UChar: return Importer.getToContext().UnsignedCharTy;
1326
1327 case BuiltinType::Char16:
1328 // FIXME: Make sure that the "to" context supports C++!
1329 return Importer.getToContext().Char16Ty;
1330
1331 case BuiltinType::Char32:
1332 // FIXME: Make sure that the "to" context supports C++!
1333 return Importer.getToContext().Char32Ty;
1334
1335 case BuiltinType::UShort: return Importer.getToContext().UnsignedShortTy;
1336 case BuiltinType::UInt: return Importer.getToContext().UnsignedIntTy;
1337 case BuiltinType::ULong: return Importer.getToContext().UnsignedLongTy;
1338 case BuiltinType::ULongLong:
1339 return Importer.getToContext().UnsignedLongLongTy;
1340 case BuiltinType::UInt128: return Importer.getToContext().UnsignedInt128Ty;
1341
1342 case BuiltinType::Char_S:
1343 // The context we're importing from has an unsigned 'char'. If we're
1344 // importing into a context with a signed 'char', translate to
1345 // 'unsigned char' instead.
1346 if (!Importer.getToContext().getLangOptions().CharIsSigned)
1347 return Importer.getToContext().SignedCharTy;
1348
1349 return Importer.getToContext().CharTy;
1350
1351 case BuiltinType::SChar: return Importer.getToContext().SignedCharTy;
1352 case BuiltinType::WChar_S:
1353 case BuiltinType::WChar_U:
1354 // FIXME: If not in C++, shall we translate to the C equivalent of
1355 // wchar_t?
1356 return Importer.getToContext().WCharTy;
1357
1358 case BuiltinType::Short : return Importer.getToContext().ShortTy;
1359 case BuiltinType::Int : return Importer.getToContext().IntTy;
1360 case BuiltinType::Long : return Importer.getToContext().LongTy;
1361 case BuiltinType::LongLong : return Importer.getToContext().LongLongTy;
1362 case BuiltinType::Int128 : return Importer.getToContext().Int128Ty;
1363 case BuiltinType::Float: return Importer.getToContext().FloatTy;
1364 case BuiltinType::Double: return Importer.getToContext().DoubleTy;
1365 case BuiltinType::LongDouble: return Importer.getToContext().LongDoubleTy;
1366
1367 case BuiltinType::NullPtr:
1368 // FIXME: Make sure that the "to" context supports C++0x!
1369 return Importer.getToContext().NullPtrTy;
1370
1371 case BuiltinType::Overload: return Importer.getToContext().OverloadTy;
1372 case BuiltinType::Dependent: return Importer.getToContext().DependentTy;
1373 case BuiltinType::UnknownAny: return Importer.getToContext().UnknownAnyTy;
1374 case BuiltinType::BoundMember: return Importer.getToContext().BoundMemberTy;
1375
1376 case BuiltinType::ObjCId:
1377 // FIXME: Make sure that the "to" context supports Objective-C!
1378 return Importer.getToContext().ObjCBuiltinIdTy;
1379
1380 case BuiltinType::ObjCClass:
1381 return Importer.getToContext().ObjCBuiltinClassTy;
1382
1383 case BuiltinType::ObjCSel:
1384 return Importer.getToContext().ObjCBuiltinSelTy;
1385 }
1386
1387 return QualType();
1388 }
1389
VisitComplexType(const ComplexType * T)1390 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1391 QualType ToElementType = Importer.Import(T->getElementType());
1392 if (ToElementType.isNull())
1393 return QualType();
1394
1395 return Importer.getToContext().getComplexType(ToElementType);
1396 }
1397
VisitPointerType(const PointerType * T)1398 QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1399 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1400 if (ToPointeeType.isNull())
1401 return QualType();
1402
1403 return Importer.getToContext().getPointerType(ToPointeeType);
1404 }
1405
VisitBlockPointerType(const BlockPointerType * T)1406 QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1407 // FIXME: Check for blocks support in "to" context.
1408 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1409 if (ToPointeeType.isNull())
1410 return QualType();
1411
1412 return Importer.getToContext().getBlockPointerType(ToPointeeType);
1413 }
1414
1415 QualType
VisitLValueReferenceType(const LValueReferenceType * T)1416 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1417 // FIXME: Check for C++ support in "to" context.
1418 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1419 if (ToPointeeType.isNull())
1420 return QualType();
1421
1422 return Importer.getToContext().getLValueReferenceType(ToPointeeType);
1423 }
1424
1425 QualType
VisitRValueReferenceType(const RValueReferenceType * T)1426 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1427 // FIXME: Check for C++0x support in "to" context.
1428 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1429 if (ToPointeeType.isNull())
1430 return QualType();
1431
1432 return Importer.getToContext().getRValueReferenceType(ToPointeeType);
1433 }
1434
VisitMemberPointerType(const MemberPointerType * T)1435 QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1436 // FIXME: Check for C++ support in "to" context.
1437 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1438 if (ToPointeeType.isNull())
1439 return QualType();
1440
1441 QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
1442 return Importer.getToContext().getMemberPointerType(ToPointeeType,
1443 ClassType.getTypePtr());
1444 }
1445
VisitConstantArrayType(const ConstantArrayType * T)1446 QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1447 QualType ToElementType = Importer.Import(T->getElementType());
1448 if (ToElementType.isNull())
1449 return QualType();
1450
1451 return Importer.getToContext().getConstantArrayType(ToElementType,
1452 T->getSize(),
1453 T->getSizeModifier(),
1454 T->getIndexTypeCVRQualifiers());
1455 }
1456
1457 QualType
VisitIncompleteArrayType(const IncompleteArrayType * T)1458 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1459 QualType ToElementType = Importer.Import(T->getElementType());
1460 if (ToElementType.isNull())
1461 return QualType();
1462
1463 return Importer.getToContext().getIncompleteArrayType(ToElementType,
1464 T->getSizeModifier(),
1465 T->getIndexTypeCVRQualifiers());
1466 }
1467
VisitVariableArrayType(const VariableArrayType * T)1468 QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1469 QualType ToElementType = Importer.Import(T->getElementType());
1470 if (ToElementType.isNull())
1471 return QualType();
1472
1473 Expr *Size = Importer.Import(T->getSizeExpr());
1474 if (!Size)
1475 return QualType();
1476
1477 SourceRange Brackets = Importer.Import(T->getBracketsRange());
1478 return Importer.getToContext().getVariableArrayType(ToElementType, Size,
1479 T->getSizeModifier(),
1480 T->getIndexTypeCVRQualifiers(),
1481 Brackets);
1482 }
1483
VisitVectorType(const VectorType * T)1484 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1485 QualType ToElementType = Importer.Import(T->getElementType());
1486 if (ToElementType.isNull())
1487 return QualType();
1488
1489 return Importer.getToContext().getVectorType(ToElementType,
1490 T->getNumElements(),
1491 T->getVectorKind());
1492 }
1493
VisitExtVectorType(const ExtVectorType * T)1494 QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1495 QualType ToElementType = Importer.Import(T->getElementType());
1496 if (ToElementType.isNull())
1497 return QualType();
1498
1499 return Importer.getToContext().getExtVectorType(ToElementType,
1500 T->getNumElements());
1501 }
1502
1503 QualType
VisitFunctionNoProtoType(const FunctionNoProtoType * T)1504 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1505 // FIXME: What happens if we're importing a function without a prototype
1506 // into C++? Should we make it variadic?
1507 QualType ToResultType = Importer.Import(T->getResultType());
1508 if (ToResultType.isNull())
1509 return QualType();
1510
1511 return Importer.getToContext().getFunctionNoProtoType(ToResultType,
1512 T->getExtInfo());
1513 }
1514
VisitFunctionProtoType(const FunctionProtoType * T)1515 QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1516 QualType ToResultType = Importer.Import(T->getResultType());
1517 if (ToResultType.isNull())
1518 return QualType();
1519
1520 // Import argument types
1521 llvm::SmallVector<QualType, 4> ArgTypes;
1522 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
1523 AEnd = T->arg_type_end();
1524 A != AEnd; ++A) {
1525 QualType ArgType = Importer.Import(*A);
1526 if (ArgType.isNull())
1527 return QualType();
1528 ArgTypes.push_back(ArgType);
1529 }
1530
1531 // Import exception types
1532 llvm::SmallVector<QualType, 4> ExceptionTypes;
1533 for (FunctionProtoType::exception_iterator E = T->exception_begin(),
1534 EEnd = T->exception_end();
1535 E != EEnd; ++E) {
1536 QualType ExceptionType = Importer.Import(*E);
1537 if (ExceptionType.isNull())
1538 return QualType();
1539 ExceptionTypes.push_back(ExceptionType);
1540 }
1541
1542 FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
1543 EPI.Exceptions = ExceptionTypes.data();
1544
1545 return Importer.getToContext().getFunctionType(ToResultType, ArgTypes.data(),
1546 ArgTypes.size(), EPI);
1547 }
1548
VisitTypedefType(const TypedefType * T)1549 QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1550 TypedefNameDecl *ToDecl
1551 = dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
1552 if (!ToDecl)
1553 return QualType();
1554
1555 return Importer.getToContext().getTypeDeclType(ToDecl);
1556 }
1557
VisitTypeOfExprType(const TypeOfExprType * T)1558 QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1559 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1560 if (!ToExpr)
1561 return QualType();
1562
1563 return Importer.getToContext().getTypeOfExprType(ToExpr);
1564 }
1565
VisitTypeOfType(const TypeOfType * T)1566 QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1567 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1568 if (ToUnderlyingType.isNull())
1569 return QualType();
1570
1571 return Importer.getToContext().getTypeOfType(ToUnderlyingType);
1572 }
1573
VisitDecltypeType(const DecltypeType * T)1574 QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1575 // FIXME: Make sure that the "to" context supports C++0x!
1576 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1577 if (!ToExpr)
1578 return QualType();
1579
1580 return Importer.getToContext().getDecltypeType(ToExpr);
1581 }
1582
VisitUnaryTransformType(const UnaryTransformType * T)1583 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1584 QualType ToBaseType = Importer.Import(T->getBaseType());
1585 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1586 if (ToBaseType.isNull() || ToUnderlyingType.isNull())
1587 return QualType();
1588
1589 return Importer.getToContext().getUnaryTransformType(ToBaseType,
1590 ToUnderlyingType,
1591 T->getUTTKind());
1592 }
1593
VisitAutoType(const AutoType * T)1594 QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1595 // FIXME: Make sure that the "to" context supports C++0x!
1596 QualType FromDeduced = T->getDeducedType();
1597 QualType ToDeduced;
1598 if (!FromDeduced.isNull()) {
1599 ToDeduced = Importer.Import(FromDeduced);
1600 if (ToDeduced.isNull())
1601 return QualType();
1602 }
1603
1604 return Importer.getToContext().getAutoType(ToDeduced);
1605 }
1606
VisitRecordType(const RecordType * T)1607 QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1608 RecordDecl *ToDecl
1609 = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
1610 if (!ToDecl)
1611 return QualType();
1612
1613 return Importer.getToContext().getTagDeclType(ToDecl);
1614 }
1615
VisitEnumType(const EnumType * T)1616 QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1617 EnumDecl *ToDecl
1618 = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
1619 if (!ToDecl)
1620 return QualType();
1621
1622 return Importer.getToContext().getTagDeclType(ToDecl);
1623 }
1624
VisitTemplateSpecializationType(const TemplateSpecializationType * T)1625 QualType ASTNodeImporter::VisitTemplateSpecializationType(
1626 const TemplateSpecializationType *T) {
1627 TemplateName ToTemplate = Importer.Import(T->getTemplateName());
1628 if (ToTemplate.isNull())
1629 return QualType();
1630
1631 llvm::SmallVector<TemplateArgument, 2> ToTemplateArgs;
1632 if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1633 return QualType();
1634
1635 QualType ToCanonType;
1636 if (!QualType(T, 0).isCanonical()) {
1637 QualType FromCanonType
1638 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1639 ToCanonType =Importer.Import(FromCanonType);
1640 if (ToCanonType.isNull())
1641 return QualType();
1642 }
1643 return Importer.getToContext().getTemplateSpecializationType(ToTemplate,
1644 ToTemplateArgs.data(),
1645 ToTemplateArgs.size(),
1646 ToCanonType);
1647 }
1648
VisitElaboratedType(const ElaboratedType * T)1649 QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1650 NestedNameSpecifier *ToQualifier = 0;
1651 // Note: the qualifier in an ElaboratedType is optional.
1652 if (T->getQualifier()) {
1653 ToQualifier = Importer.Import(T->getQualifier());
1654 if (!ToQualifier)
1655 return QualType();
1656 }
1657
1658 QualType ToNamedType = Importer.Import(T->getNamedType());
1659 if (ToNamedType.isNull())
1660 return QualType();
1661
1662 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1663 ToQualifier, ToNamedType);
1664 }
1665
VisitObjCInterfaceType(const ObjCInterfaceType * T)1666 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1667 ObjCInterfaceDecl *Class
1668 = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
1669 if (!Class)
1670 return QualType();
1671
1672 return Importer.getToContext().getObjCInterfaceType(Class);
1673 }
1674
VisitObjCObjectType(const ObjCObjectType * T)1675 QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1676 QualType ToBaseType = Importer.Import(T->getBaseType());
1677 if (ToBaseType.isNull())
1678 return QualType();
1679
1680 llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
1681 for (ObjCObjectType::qual_iterator P = T->qual_begin(),
1682 PEnd = T->qual_end();
1683 P != PEnd; ++P) {
1684 ObjCProtocolDecl *Protocol
1685 = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(*P));
1686 if (!Protocol)
1687 return QualType();
1688 Protocols.push_back(Protocol);
1689 }
1690
1691 return Importer.getToContext().getObjCObjectType(ToBaseType,
1692 Protocols.data(),
1693 Protocols.size());
1694 }
1695
1696 QualType
VisitObjCObjectPointerType(const ObjCObjectPointerType * T)1697 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1698 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1699 if (ToPointeeType.isNull())
1700 return QualType();
1701
1702 return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
1703 }
1704
1705 //----------------------------------------------------------------------------
1706 // Import Declarations
1707 //----------------------------------------------------------------------------
ImportDeclParts(NamedDecl * D,DeclContext * & DC,DeclContext * & LexicalDC,DeclarationName & Name,SourceLocation & Loc)1708 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC,
1709 DeclContext *&LexicalDC,
1710 DeclarationName &Name,
1711 SourceLocation &Loc) {
1712 // Import the context of this declaration.
1713 DC = Importer.ImportContext(D->getDeclContext());
1714 if (!DC)
1715 return true;
1716
1717 LexicalDC = DC;
1718 if (D->getDeclContext() != D->getLexicalDeclContext()) {
1719 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1720 if (!LexicalDC)
1721 return true;
1722 }
1723
1724 // Import the name of this declaration.
1725 Name = Importer.Import(D->getDeclName());
1726 if (D->getDeclName() && !Name)
1727 return true;
1728
1729 // Import the location of this declaration.
1730 Loc = Importer.Import(D->getLocation());
1731 return false;
1732 }
1733
1734 void
ImportDeclarationNameLoc(const DeclarationNameInfo & From,DeclarationNameInfo & To)1735 ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
1736 DeclarationNameInfo& To) {
1737 // NOTE: To.Name and To.Loc are already imported.
1738 // We only have to import To.LocInfo.
1739 switch (To.getName().getNameKind()) {
1740 case DeclarationName::Identifier:
1741 case DeclarationName::ObjCZeroArgSelector:
1742 case DeclarationName::ObjCOneArgSelector:
1743 case DeclarationName::ObjCMultiArgSelector:
1744 case DeclarationName::CXXUsingDirective:
1745 return;
1746
1747 case DeclarationName::CXXOperatorName: {
1748 SourceRange Range = From.getCXXOperatorNameRange();
1749 To.setCXXOperatorNameRange(Importer.Import(Range));
1750 return;
1751 }
1752 case DeclarationName::CXXLiteralOperatorName: {
1753 SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
1754 To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
1755 return;
1756 }
1757 case DeclarationName::CXXConstructorName:
1758 case DeclarationName::CXXDestructorName:
1759 case DeclarationName::CXXConversionFunctionName: {
1760 TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
1761 To.setNamedTypeInfo(Importer.Import(FromTInfo));
1762 return;
1763 }
1764 assert(0 && "Unknown name kind.");
1765 }
1766 }
1767
ImportDeclContext(DeclContext * FromDC,bool ForceImport)1768 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1769 if (Importer.isMinimalImport() && !ForceImport) {
1770 if (DeclContext *ToDC = Importer.ImportContext(FromDC)) {
1771 ToDC->setHasExternalLexicalStorage();
1772 ToDC->setHasExternalVisibleStorage();
1773 }
1774 return;
1775 }
1776
1777 for (DeclContext::decl_iterator From = FromDC->decls_begin(),
1778 FromEnd = FromDC->decls_end();
1779 From != FromEnd;
1780 ++From)
1781 Importer.Import(*From);
1782 }
1783
ImportDefinition(RecordDecl * From,RecordDecl * To,bool ForceImport)1784 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To, bool ForceImport) {
1785 if (To->getDefinition())
1786 return false;
1787
1788 To->startDefinition();
1789
1790 // Add base classes.
1791 if (CXXRecordDecl *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
1792 CXXRecordDecl *FromCXX = cast<CXXRecordDecl>(From);
1793
1794 llvm::SmallVector<CXXBaseSpecifier *, 4> Bases;
1795 for (CXXRecordDecl::base_class_iterator
1796 Base1 = FromCXX->bases_begin(),
1797 FromBaseEnd = FromCXX->bases_end();
1798 Base1 != FromBaseEnd;
1799 ++Base1) {
1800 QualType T = Importer.Import(Base1->getType());
1801 if (T.isNull())
1802 return true;
1803
1804 SourceLocation EllipsisLoc;
1805 if (Base1->isPackExpansion())
1806 EllipsisLoc = Importer.Import(Base1->getEllipsisLoc());
1807
1808 Bases.push_back(
1809 new (Importer.getToContext())
1810 CXXBaseSpecifier(Importer.Import(Base1->getSourceRange()),
1811 Base1->isVirtual(),
1812 Base1->isBaseOfClass(),
1813 Base1->getAccessSpecifierAsWritten(),
1814 Importer.Import(Base1->getTypeSourceInfo()),
1815 EllipsisLoc));
1816 }
1817 if (!Bases.empty())
1818 ToCXX->setBases(Bases.data(), Bases.size());
1819 }
1820
1821 ImportDeclContext(From, ForceImport);
1822 To->completeDefinition();
1823 return false;
1824 }
1825
ImportTemplateParameterList(TemplateParameterList * Params)1826 TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
1827 TemplateParameterList *Params) {
1828 llvm::SmallVector<NamedDecl *, 4> ToParams;
1829 ToParams.reserve(Params->size());
1830 for (TemplateParameterList::iterator P = Params->begin(),
1831 PEnd = Params->end();
1832 P != PEnd; ++P) {
1833 Decl *To = Importer.Import(*P);
1834 if (!To)
1835 return 0;
1836
1837 ToParams.push_back(cast<NamedDecl>(To));
1838 }
1839
1840 return TemplateParameterList::Create(Importer.getToContext(),
1841 Importer.Import(Params->getTemplateLoc()),
1842 Importer.Import(Params->getLAngleLoc()),
1843 ToParams.data(), ToParams.size(),
1844 Importer.Import(Params->getRAngleLoc()));
1845 }
1846
1847 TemplateArgument
ImportTemplateArgument(const TemplateArgument & From)1848 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
1849 switch (From.getKind()) {
1850 case TemplateArgument::Null:
1851 return TemplateArgument();
1852
1853 case TemplateArgument::Type: {
1854 QualType ToType = Importer.Import(From.getAsType());
1855 if (ToType.isNull())
1856 return TemplateArgument();
1857 return TemplateArgument(ToType);
1858 }
1859
1860 case TemplateArgument::Integral: {
1861 QualType ToType = Importer.Import(From.getIntegralType());
1862 if (ToType.isNull())
1863 return TemplateArgument();
1864 return TemplateArgument(*From.getAsIntegral(), ToType);
1865 }
1866
1867 case TemplateArgument::Declaration:
1868 if (Decl *To = Importer.Import(From.getAsDecl()))
1869 return TemplateArgument(To);
1870 return TemplateArgument();
1871
1872 case TemplateArgument::Template: {
1873 TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
1874 if (ToTemplate.isNull())
1875 return TemplateArgument();
1876
1877 return TemplateArgument(ToTemplate);
1878 }
1879
1880 case TemplateArgument::TemplateExpansion: {
1881 TemplateName ToTemplate
1882 = Importer.Import(From.getAsTemplateOrTemplatePattern());
1883 if (ToTemplate.isNull())
1884 return TemplateArgument();
1885
1886 return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
1887 }
1888
1889 case TemplateArgument::Expression:
1890 if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
1891 return TemplateArgument(ToExpr);
1892 return TemplateArgument();
1893
1894 case TemplateArgument::Pack: {
1895 llvm::SmallVector<TemplateArgument, 2> ToPack;
1896 ToPack.reserve(From.pack_size());
1897 if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
1898 return TemplateArgument();
1899
1900 TemplateArgument *ToArgs
1901 = new (Importer.getToContext()) TemplateArgument[ToPack.size()];
1902 std::copy(ToPack.begin(), ToPack.end(), ToArgs);
1903 return TemplateArgument(ToArgs, ToPack.size());
1904 }
1905 }
1906
1907 llvm_unreachable("Invalid template argument kind");
1908 return TemplateArgument();
1909 }
1910
ImportTemplateArguments(const TemplateArgument * FromArgs,unsigned NumFromArgs,llvm::SmallVectorImpl<TemplateArgument> & ToArgs)1911 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
1912 unsigned NumFromArgs,
1913 llvm::SmallVectorImpl<TemplateArgument> &ToArgs) {
1914 for (unsigned I = 0; I != NumFromArgs; ++I) {
1915 TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
1916 if (To.isNull() && !FromArgs[I].isNull())
1917 return true;
1918
1919 ToArgs.push_back(To);
1920 }
1921
1922 return false;
1923 }
1924
IsStructuralMatch(RecordDecl * FromRecord,RecordDecl * ToRecord)1925 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
1926 RecordDecl *ToRecord) {
1927 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1928 Importer.getToContext(),
1929 Importer.getNonEquivalentDecls());
1930 return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
1931 }
1932
IsStructuralMatch(EnumDecl * FromEnum,EnumDecl * ToEnum)1933 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
1934 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1935 Importer.getToContext(),
1936 Importer.getNonEquivalentDecls());
1937 return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
1938 }
1939
IsStructuralMatch(ClassTemplateDecl * From,ClassTemplateDecl * To)1940 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
1941 ClassTemplateDecl *To) {
1942 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1943 Importer.getToContext(),
1944 Importer.getNonEquivalentDecls());
1945 return Ctx.IsStructurallyEquivalent(From, To);
1946 }
1947
VisitDecl(Decl * D)1948 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
1949 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1950 << D->getDeclKindName();
1951 return 0;
1952 }
1953
VisitNamespaceDecl(NamespaceDecl * D)1954 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
1955 // Import the major distinguishing characteristics of this namespace.
1956 DeclContext *DC, *LexicalDC;
1957 DeclarationName Name;
1958 SourceLocation Loc;
1959 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1960 return 0;
1961
1962 NamespaceDecl *MergeWithNamespace = 0;
1963 if (!Name) {
1964 // This is an anonymous namespace. Adopt an existing anonymous
1965 // namespace if we can.
1966 // FIXME: Not testable.
1967 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
1968 MergeWithNamespace = TU->getAnonymousNamespace();
1969 else
1970 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
1971 } else {
1972 llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
1973 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
1974 Lookup.first != Lookup.second;
1975 ++Lookup.first) {
1976 if (!(*Lookup.first)->isInIdentifierNamespace(Decl::IDNS_Namespace))
1977 continue;
1978
1979 if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(*Lookup.first)) {
1980 MergeWithNamespace = FoundNS;
1981 ConflictingDecls.clear();
1982 break;
1983 }
1984
1985 ConflictingDecls.push_back(*Lookup.first);
1986 }
1987
1988 if (!ConflictingDecls.empty()) {
1989 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
1990 ConflictingDecls.data(),
1991 ConflictingDecls.size());
1992 }
1993 }
1994
1995 // Create the "to" namespace, if needed.
1996 NamespaceDecl *ToNamespace = MergeWithNamespace;
1997 if (!ToNamespace) {
1998 ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC,
1999 Importer.Import(D->getLocStart()),
2000 Loc, Name.getAsIdentifierInfo());
2001 ToNamespace->setLexicalDeclContext(LexicalDC);
2002 LexicalDC->addDecl(ToNamespace);
2003
2004 // If this is an anonymous namespace, register it as the anonymous
2005 // namespace within its context.
2006 if (!Name) {
2007 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2008 TU->setAnonymousNamespace(ToNamespace);
2009 else
2010 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2011 }
2012 }
2013 Importer.Imported(D, ToNamespace);
2014
2015 ImportDeclContext(D);
2016
2017 return ToNamespace;
2018 }
2019
VisitTypedefNameDecl(TypedefNameDecl * D,bool IsAlias)2020 Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2021 // Import the major distinguishing characteristics of this typedef.
2022 DeclContext *DC, *LexicalDC;
2023 DeclarationName Name;
2024 SourceLocation Loc;
2025 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2026 return 0;
2027
2028 // If this typedef is not in block scope, determine whether we've
2029 // seen a typedef with the same name (that we can merge with) or any
2030 // other entity by that name (which name lookup could conflict with).
2031 if (!DC->isFunctionOrMethod()) {
2032 llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
2033 unsigned IDNS = Decl::IDNS_Ordinary;
2034 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2035 Lookup.first != Lookup.second;
2036 ++Lookup.first) {
2037 if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
2038 continue;
2039 if (TypedefNameDecl *FoundTypedef =
2040 dyn_cast<TypedefNameDecl>(*Lookup.first)) {
2041 if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
2042 FoundTypedef->getUnderlyingType()))
2043 return Importer.Imported(D, FoundTypedef);
2044 }
2045
2046 ConflictingDecls.push_back(*Lookup.first);
2047 }
2048
2049 if (!ConflictingDecls.empty()) {
2050 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2051 ConflictingDecls.data(),
2052 ConflictingDecls.size());
2053 if (!Name)
2054 return 0;
2055 }
2056 }
2057
2058 // Import the underlying type of this typedef;
2059 QualType T = Importer.Import(D->getUnderlyingType());
2060 if (T.isNull())
2061 return 0;
2062
2063 // Create the new typedef node.
2064 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2065 SourceLocation StartL = Importer.Import(D->getLocStart());
2066 TypedefNameDecl *ToTypedef;
2067 if (IsAlias)
2068 ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
2069 StartL, Loc,
2070 Name.getAsIdentifierInfo(),
2071 TInfo);
2072 else
2073 ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC,
2074 StartL, Loc,
2075 Name.getAsIdentifierInfo(),
2076 TInfo);
2077 ToTypedef->setAccess(D->getAccess());
2078 ToTypedef->setLexicalDeclContext(LexicalDC);
2079 Importer.Imported(D, ToTypedef);
2080 LexicalDC->addDecl(ToTypedef);
2081
2082 return ToTypedef;
2083 }
2084
VisitTypedefDecl(TypedefDecl * D)2085 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2086 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2087 }
2088
VisitTypeAliasDecl(TypeAliasDecl * D)2089 Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2090 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2091 }
2092
VisitEnumDecl(EnumDecl * D)2093 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2094 // Import the major distinguishing characteristics of this enum.
2095 DeclContext *DC, *LexicalDC;
2096 DeclarationName Name;
2097 SourceLocation Loc;
2098 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2099 return 0;
2100
2101 // Figure out what enum name we're looking for.
2102 unsigned IDNS = Decl::IDNS_Tag;
2103 DeclarationName SearchName = Name;
2104 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2105 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2106 IDNS = Decl::IDNS_Ordinary;
2107 } else if (Importer.getToContext().getLangOptions().CPlusPlus)
2108 IDNS |= Decl::IDNS_Ordinary;
2109
2110 // We may already have an enum of the same name; try to find and match it.
2111 if (!DC->isFunctionOrMethod() && SearchName) {
2112 llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
2113 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2114 Lookup.first != Lookup.second;
2115 ++Lookup.first) {
2116 if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
2117 continue;
2118
2119 Decl *Found = *Lookup.first;
2120 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2121 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2122 Found = Tag->getDecl();
2123 }
2124
2125 if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
2126 if (IsStructuralMatch(D, FoundEnum))
2127 return Importer.Imported(D, FoundEnum);
2128 }
2129
2130 ConflictingDecls.push_back(*Lookup.first);
2131 }
2132
2133 if (!ConflictingDecls.empty()) {
2134 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2135 ConflictingDecls.data(),
2136 ConflictingDecls.size());
2137 }
2138 }
2139
2140 // Create the enum declaration.
2141 EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC,
2142 Importer.Import(D->getLocStart()),
2143 Loc, Name.getAsIdentifierInfo(), 0,
2144 D->isScoped(), D->isScopedUsingClassTag(),
2145 D->isFixed());
2146 // Import the qualifier, if any.
2147 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2148 D2->setAccess(D->getAccess());
2149 D2->setLexicalDeclContext(LexicalDC);
2150 Importer.Imported(D, D2);
2151 LexicalDC->addDecl(D2);
2152
2153 // Import the integer type.
2154 QualType ToIntegerType = Importer.Import(D->getIntegerType());
2155 if (ToIntegerType.isNull())
2156 return 0;
2157 D2->setIntegerType(ToIntegerType);
2158
2159 // Import the definition
2160 if (D->isDefinition()) {
2161 QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(D));
2162 if (T.isNull())
2163 return 0;
2164
2165 QualType ToPromotionType = Importer.Import(D->getPromotionType());
2166 if (ToPromotionType.isNull())
2167 return 0;
2168
2169 D2->startDefinition();
2170 ImportDeclContext(D);
2171
2172 // FIXME: we might need to merge the number of positive or negative bits
2173 // if the enumerator lists don't match.
2174 D2->completeDefinition(T, ToPromotionType,
2175 D->getNumPositiveBits(),
2176 D->getNumNegativeBits());
2177 }
2178
2179 return D2;
2180 }
2181
VisitRecordDecl(RecordDecl * D)2182 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2183 // If this record has a definition in the translation unit we're coming from,
2184 // but this particular declaration is not that definition, import the
2185 // definition and map to that.
2186 TagDecl *Definition = D->getDefinition();
2187 if (Definition && Definition != D) {
2188 Decl *ImportedDef = Importer.Import(Definition);
2189 if (!ImportedDef)
2190 return 0;
2191
2192 return Importer.Imported(D, ImportedDef);
2193 }
2194
2195 // Import the major distinguishing characteristics of this record.
2196 DeclContext *DC, *LexicalDC;
2197 DeclarationName Name;
2198 SourceLocation Loc;
2199 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2200 return 0;
2201
2202 // Figure out what structure name we're looking for.
2203 unsigned IDNS = Decl::IDNS_Tag;
2204 DeclarationName SearchName = Name;
2205 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2206 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2207 IDNS = Decl::IDNS_Ordinary;
2208 } else if (Importer.getToContext().getLangOptions().CPlusPlus)
2209 IDNS |= Decl::IDNS_Ordinary;
2210
2211 // We may already have a record of the same name; try to find and match it.
2212 RecordDecl *AdoptDecl = 0;
2213 if (!DC->isFunctionOrMethod() && SearchName) {
2214 llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
2215 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2216 Lookup.first != Lookup.second;
2217 ++Lookup.first) {
2218 if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
2219 continue;
2220
2221 Decl *Found = *Lookup.first;
2222 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2223 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2224 Found = Tag->getDecl();
2225 }
2226
2227 if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2228 if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
2229 if (!D->isDefinition() || IsStructuralMatch(D, FoundDef)) {
2230 // The record types structurally match, or the "from" translation
2231 // unit only had a forward declaration anyway; call it the same
2232 // function.
2233 // FIXME: For C++, we should also merge methods here.
2234 return Importer.Imported(D, FoundDef);
2235 }
2236 } else {
2237 // We have a forward declaration of this type, so adopt that forward
2238 // declaration rather than building a new one.
2239 AdoptDecl = FoundRecord;
2240 continue;
2241 }
2242 }
2243
2244 ConflictingDecls.push_back(*Lookup.first);
2245 }
2246
2247 if (!ConflictingDecls.empty()) {
2248 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2249 ConflictingDecls.data(),
2250 ConflictingDecls.size());
2251 }
2252 }
2253
2254 // Create the record declaration.
2255 RecordDecl *D2 = AdoptDecl;
2256 SourceLocation StartLoc = Importer.Import(D->getLocStart());
2257 if (!D2) {
2258 if (isa<CXXRecordDecl>(D)) {
2259 CXXRecordDecl *D2CXX = CXXRecordDecl::Create(Importer.getToContext(),
2260 D->getTagKind(),
2261 DC, StartLoc, Loc,
2262 Name.getAsIdentifierInfo());
2263 D2 = D2CXX;
2264 D2->setAccess(D->getAccess());
2265 } else {
2266 D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
2267 DC, StartLoc, Loc, Name.getAsIdentifierInfo());
2268 }
2269
2270 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2271 D2->setLexicalDeclContext(LexicalDC);
2272 LexicalDC->addDecl(D2);
2273 }
2274
2275 Importer.Imported(D, D2);
2276
2277 if (D->isDefinition() && ImportDefinition(D, D2))
2278 return 0;
2279
2280 return D2;
2281 }
2282
VisitEnumConstantDecl(EnumConstantDecl * D)2283 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2284 // Import the major distinguishing characteristics of this enumerator.
2285 DeclContext *DC, *LexicalDC;
2286 DeclarationName Name;
2287 SourceLocation Loc;
2288 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2289 return 0;
2290
2291 QualType T = Importer.Import(D->getType());
2292 if (T.isNull())
2293 return 0;
2294
2295 // Determine whether there are any other declarations with the same name and
2296 // in the same context.
2297 if (!LexicalDC->isFunctionOrMethod()) {
2298 llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
2299 unsigned IDNS = Decl::IDNS_Ordinary;
2300 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2301 Lookup.first != Lookup.second;
2302 ++Lookup.first) {
2303 if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
2304 continue;
2305
2306 ConflictingDecls.push_back(*Lookup.first);
2307 }
2308
2309 if (!ConflictingDecls.empty()) {
2310 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2311 ConflictingDecls.data(),
2312 ConflictingDecls.size());
2313 if (!Name)
2314 return 0;
2315 }
2316 }
2317
2318 Expr *Init = Importer.Import(D->getInitExpr());
2319 if (D->getInitExpr() && !Init)
2320 return 0;
2321
2322 EnumConstantDecl *ToEnumerator
2323 = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2324 Name.getAsIdentifierInfo(), T,
2325 Init, D->getInitVal());
2326 ToEnumerator->setAccess(D->getAccess());
2327 ToEnumerator->setLexicalDeclContext(LexicalDC);
2328 Importer.Imported(D, ToEnumerator);
2329 LexicalDC->addDecl(ToEnumerator);
2330 return ToEnumerator;
2331 }
2332
VisitFunctionDecl(FunctionDecl * D)2333 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
2334 // Import the major distinguishing characteristics of this function.
2335 DeclContext *DC, *LexicalDC;
2336 DeclarationName Name;
2337 SourceLocation Loc;
2338 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2339 return 0;
2340
2341 // Try to find a function in our own ("to") context with the same name, same
2342 // type, and in the same context as the function we're importing.
2343 if (!LexicalDC->isFunctionOrMethod()) {
2344 llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
2345 unsigned IDNS = Decl::IDNS_Ordinary;
2346 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2347 Lookup.first != Lookup.second;
2348 ++Lookup.first) {
2349 if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
2350 continue;
2351
2352 if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(*Lookup.first)) {
2353 if (isExternalLinkage(FoundFunction->getLinkage()) &&
2354 isExternalLinkage(D->getLinkage())) {
2355 if (Importer.IsStructurallyEquivalent(D->getType(),
2356 FoundFunction->getType())) {
2357 // FIXME: Actually try to merge the body and other attributes.
2358 return Importer.Imported(D, FoundFunction);
2359 }
2360
2361 // FIXME: Check for overloading more carefully, e.g., by boosting
2362 // Sema::IsOverload out to the AST library.
2363
2364 // Function overloading is okay in C++.
2365 if (Importer.getToContext().getLangOptions().CPlusPlus)
2366 continue;
2367
2368 // Complain about inconsistent function types.
2369 Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
2370 << Name << D->getType() << FoundFunction->getType();
2371 Importer.ToDiag(FoundFunction->getLocation(),
2372 diag::note_odr_value_here)
2373 << FoundFunction->getType();
2374 }
2375 }
2376
2377 ConflictingDecls.push_back(*Lookup.first);
2378 }
2379
2380 if (!ConflictingDecls.empty()) {
2381 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2382 ConflictingDecls.data(),
2383 ConflictingDecls.size());
2384 if (!Name)
2385 return 0;
2386 }
2387 }
2388
2389 DeclarationNameInfo NameInfo(Name, Loc);
2390 // Import additional name location/type info.
2391 ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
2392
2393 // Import the type.
2394 QualType T = Importer.Import(D->getType());
2395 if (T.isNull())
2396 return 0;
2397
2398 // Import the function parameters.
2399 llvm::SmallVector<ParmVarDecl *, 8> Parameters;
2400 for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
2401 P != PEnd; ++P) {
2402 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(*P));
2403 if (!ToP)
2404 return 0;
2405
2406 Parameters.push_back(ToP);
2407 }
2408
2409 // Create the imported function.
2410 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2411 FunctionDecl *ToFunction = 0;
2412 if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
2413 ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
2414 cast<CXXRecordDecl>(DC),
2415 D->getInnerLocStart(),
2416 NameInfo, T, TInfo,
2417 FromConstructor->isExplicit(),
2418 D->isInlineSpecified(),
2419 D->isImplicit());
2420 } else if (isa<CXXDestructorDecl>(D)) {
2421 ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
2422 cast<CXXRecordDecl>(DC),
2423 D->getInnerLocStart(),
2424 NameInfo, T, TInfo,
2425 D->isInlineSpecified(),
2426 D->isImplicit());
2427 } else if (CXXConversionDecl *FromConversion
2428 = dyn_cast<CXXConversionDecl>(D)) {
2429 ToFunction = CXXConversionDecl::Create(Importer.getToContext(),
2430 cast<CXXRecordDecl>(DC),
2431 D->getInnerLocStart(),
2432 NameInfo, T, TInfo,
2433 D->isInlineSpecified(),
2434 FromConversion->isExplicit(),
2435 Importer.Import(D->getLocEnd()));
2436 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2437 ToFunction = CXXMethodDecl::Create(Importer.getToContext(),
2438 cast<CXXRecordDecl>(DC),
2439 D->getInnerLocStart(),
2440 NameInfo, T, TInfo,
2441 Method->isStatic(),
2442 Method->getStorageClassAsWritten(),
2443 Method->isInlineSpecified(),
2444 Importer.Import(D->getLocEnd()));
2445 } else {
2446 ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
2447 D->getInnerLocStart(),
2448 NameInfo, T, TInfo, D->getStorageClass(),
2449 D->getStorageClassAsWritten(),
2450 D->isInlineSpecified(),
2451 D->hasWrittenPrototype());
2452 }
2453
2454 // Import the qualifier, if any.
2455 ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2456 ToFunction->setAccess(D->getAccess());
2457 ToFunction->setLexicalDeclContext(LexicalDC);
2458 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
2459 ToFunction->setTrivial(D->isTrivial());
2460 ToFunction->setPure(D->isPure());
2461 Importer.Imported(D, ToFunction);
2462
2463 // Set the parameters.
2464 for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
2465 Parameters[I]->setOwningFunction(ToFunction);
2466 ToFunction->addDecl(Parameters[I]);
2467 }
2468 ToFunction->setParams(Parameters.data(), Parameters.size());
2469
2470 // FIXME: Other bits to merge?
2471
2472 // Add this function to the lexical context.
2473 LexicalDC->addDecl(ToFunction);
2474
2475 return ToFunction;
2476 }
2477
VisitCXXMethodDecl(CXXMethodDecl * D)2478 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
2479 return VisitFunctionDecl(D);
2480 }
2481
VisitCXXConstructorDecl(CXXConstructorDecl * D)2482 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2483 return VisitCXXMethodDecl(D);
2484 }
2485
VisitCXXDestructorDecl(CXXDestructorDecl * D)2486 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2487 return VisitCXXMethodDecl(D);
2488 }
2489
VisitCXXConversionDecl(CXXConversionDecl * D)2490 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
2491 return VisitCXXMethodDecl(D);
2492 }
2493
VisitFieldDecl(FieldDecl * D)2494 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
2495 // Import the major distinguishing characteristics of a variable.
2496 DeclContext *DC, *LexicalDC;
2497 DeclarationName Name;
2498 SourceLocation Loc;
2499 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2500 return 0;
2501
2502 // Import the type.
2503 QualType T = Importer.Import(D->getType());
2504 if (T.isNull())
2505 return 0;
2506
2507 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2508 Expr *BitWidth = Importer.Import(D->getBitWidth());
2509 if (!BitWidth && D->getBitWidth())
2510 return 0;
2511
2512 FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
2513 Importer.Import(D->getInnerLocStart()),
2514 Loc, Name.getAsIdentifierInfo(),
2515 T, TInfo, BitWidth, D->isMutable(),
2516 D->hasInClassInitializer());
2517 ToField->setAccess(D->getAccess());
2518 ToField->setLexicalDeclContext(LexicalDC);
2519 if (ToField->hasInClassInitializer())
2520 ToField->setInClassInitializer(D->getInClassInitializer());
2521 Importer.Imported(D, ToField);
2522 LexicalDC->addDecl(ToField);
2523 return ToField;
2524 }
2525
VisitIndirectFieldDecl(IndirectFieldDecl * D)2526 Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
2527 // Import the major distinguishing characteristics of a variable.
2528 DeclContext *DC, *LexicalDC;
2529 DeclarationName Name;
2530 SourceLocation Loc;
2531 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2532 return 0;
2533
2534 // Import the type.
2535 QualType T = Importer.Import(D->getType());
2536 if (T.isNull())
2537 return 0;
2538
2539 NamedDecl **NamedChain =
2540 new (Importer.getToContext())NamedDecl*[D->getChainingSize()];
2541
2542 unsigned i = 0;
2543 for (IndirectFieldDecl::chain_iterator PI = D->chain_begin(),
2544 PE = D->chain_end(); PI != PE; ++PI) {
2545 Decl* D = Importer.Import(*PI);
2546 if (!D)
2547 return 0;
2548 NamedChain[i++] = cast<NamedDecl>(D);
2549 }
2550
2551 IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create(
2552 Importer.getToContext(), DC,
2553 Loc, Name.getAsIdentifierInfo(), T,
2554 NamedChain, D->getChainingSize());
2555 ToIndirectField->setAccess(D->getAccess());
2556 ToIndirectField->setLexicalDeclContext(LexicalDC);
2557 Importer.Imported(D, ToIndirectField);
2558 LexicalDC->addDecl(ToIndirectField);
2559 return ToIndirectField;
2560 }
2561
VisitObjCIvarDecl(ObjCIvarDecl * D)2562 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
2563 // Import the major distinguishing characteristics of an ivar.
2564 DeclContext *DC, *LexicalDC;
2565 DeclarationName Name;
2566 SourceLocation Loc;
2567 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2568 return 0;
2569
2570 // Determine whether we've already imported this ivar
2571 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2572 Lookup.first != Lookup.second;
2573 ++Lookup.first) {
2574 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(*Lookup.first)) {
2575 if (Importer.IsStructurallyEquivalent(D->getType(),
2576 FoundIvar->getType())) {
2577 Importer.Imported(D, FoundIvar);
2578 return FoundIvar;
2579 }
2580
2581 Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
2582 << Name << D->getType() << FoundIvar->getType();
2583 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
2584 << FoundIvar->getType();
2585 return 0;
2586 }
2587 }
2588
2589 // Import the type.
2590 QualType T = Importer.Import(D->getType());
2591 if (T.isNull())
2592 return 0;
2593
2594 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2595 Expr *BitWidth = Importer.Import(D->getBitWidth());
2596 if (!BitWidth && D->getBitWidth())
2597 return 0;
2598
2599 ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(),
2600 cast<ObjCContainerDecl>(DC),
2601 Importer.Import(D->getInnerLocStart()),
2602 Loc, Name.getAsIdentifierInfo(),
2603 T, TInfo, D->getAccessControl(),
2604 BitWidth, D->getSynthesize());
2605 ToIvar->setLexicalDeclContext(LexicalDC);
2606 Importer.Imported(D, ToIvar);
2607 LexicalDC->addDecl(ToIvar);
2608 return ToIvar;
2609
2610 }
2611
VisitVarDecl(VarDecl * D)2612 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
2613 // Import the major distinguishing characteristics of a variable.
2614 DeclContext *DC, *LexicalDC;
2615 DeclarationName Name;
2616 SourceLocation Loc;
2617 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2618 return 0;
2619
2620 // Try to find a variable in our own ("to") context with the same name and
2621 // in the same context as the variable we're importing.
2622 if (D->isFileVarDecl()) {
2623 VarDecl *MergeWithVar = 0;
2624 llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
2625 unsigned IDNS = Decl::IDNS_Ordinary;
2626 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2627 Lookup.first != Lookup.second;
2628 ++Lookup.first) {
2629 if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
2630 continue;
2631
2632 if (VarDecl *FoundVar = dyn_cast<VarDecl>(*Lookup.first)) {
2633 // We have found a variable that we may need to merge with. Check it.
2634 if (isExternalLinkage(FoundVar->getLinkage()) &&
2635 isExternalLinkage(D->getLinkage())) {
2636 if (Importer.IsStructurallyEquivalent(D->getType(),
2637 FoundVar->getType())) {
2638 MergeWithVar = FoundVar;
2639 break;
2640 }
2641
2642 const ArrayType *FoundArray
2643 = Importer.getToContext().getAsArrayType(FoundVar->getType());
2644 const ArrayType *TArray
2645 = Importer.getToContext().getAsArrayType(D->getType());
2646 if (FoundArray && TArray) {
2647 if (isa<IncompleteArrayType>(FoundArray) &&
2648 isa<ConstantArrayType>(TArray)) {
2649 // Import the type.
2650 QualType T = Importer.Import(D->getType());
2651 if (T.isNull())
2652 return 0;
2653
2654 FoundVar->setType(T);
2655 MergeWithVar = FoundVar;
2656 break;
2657 } else if (isa<IncompleteArrayType>(TArray) &&
2658 isa<ConstantArrayType>(FoundArray)) {
2659 MergeWithVar = FoundVar;
2660 break;
2661 }
2662 }
2663
2664 Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
2665 << Name << D->getType() << FoundVar->getType();
2666 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
2667 << FoundVar->getType();
2668 }
2669 }
2670
2671 ConflictingDecls.push_back(*Lookup.first);
2672 }
2673
2674 if (MergeWithVar) {
2675 // An equivalent variable with external linkage has been found. Link
2676 // the two declarations, then merge them.
2677 Importer.Imported(D, MergeWithVar);
2678
2679 if (VarDecl *DDef = D->getDefinition()) {
2680 if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
2681 Importer.ToDiag(ExistingDef->getLocation(),
2682 diag::err_odr_variable_multiple_def)
2683 << Name;
2684 Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
2685 } else {
2686 Expr *Init = Importer.Import(DDef->getInit());
2687 MergeWithVar->setInit(Init);
2688 }
2689 }
2690
2691 return MergeWithVar;
2692 }
2693
2694 if (!ConflictingDecls.empty()) {
2695 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2696 ConflictingDecls.data(),
2697 ConflictingDecls.size());
2698 if (!Name)
2699 return 0;
2700 }
2701 }
2702
2703 // Import the type.
2704 QualType T = Importer.Import(D->getType());
2705 if (T.isNull())
2706 return 0;
2707
2708 // Create the imported variable.
2709 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2710 VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC,
2711 Importer.Import(D->getInnerLocStart()),
2712 Loc, Name.getAsIdentifierInfo(),
2713 T, TInfo,
2714 D->getStorageClass(),
2715 D->getStorageClassAsWritten());
2716 ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2717 ToVar->setAccess(D->getAccess());
2718 ToVar->setLexicalDeclContext(LexicalDC);
2719 Importer.Imported(D, ToVar);
2720 LexicalDC->addDecl(ToVar);
2721
2722 // Merge the initializer.
2723 // FIXME: Can we really import any initializer? Alternatively, we could force
2724 // ourselves to import every declaration of a variable and then only use
2725 // getInit() here.
2726 ToVar->setInit(Importer.Import(const_cast<Expr *>(D->getAnyInitializer())));
2727
2728 // FIXME: Other bits to merge?
2729
2730 return ToVar;
2731 }
2732
VisitImplicitParamDecl(ImplicitParamDecl * D)2733 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
2734 // Parameters are created in the translation unit's context, then moved
2735 // into the function declaration's context afterward.
2736 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
2737
2738 // Import the name of this declaration.
2739 DeclarationName Name = Importer.Import(D->getDeclName());
2740 if (D->getDeclName() && !Name)
2741 return 0;
2742
2743 // Import the location of this declaration.
2744 SourceLocation Loc = Importer.Import(D->getLocation());
2745
2746 // Import the parameter's type.
2747 QualType T = Importer.Import(D->getType());
2748 if (T.isNull())
2749 return 0;
2750
2751 // Create the imported parameter.
2752 ImplicitParamDecl *ToParm
2753 = ImplicitParamDecl::Create(Importer.getToContext(), DC,
2754 Loc, Name.getAsIdentifierInfo(),
2755 T);
2756 return Importer.Imported(D, ToParm);
2757 }
2758
VisitParmVarDecl(ParmVarDecl * D)2759 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
2760 // Parameters are created in the translation unit's context, then moved
2761 // into the function declaration's context afterward.
2762 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
2763
2764 // Import the name of this declaration.
2765 DeclarationName Name = Importer.Import(D->getDeclName());
2766 if (D->getDeclName() && !Name)
2767 return 0;
2768
2769 // Import the location of this declaration.
2770 SourceLocation Loc = Importer.Import(D->getLocation());
2771
2772 // Import the parameter's type.
2773 QualType T = Importer.Import(D->getType());
2774 if (T.isNull())
2775 return 0;
2776
2777 // Create the imported parameter.
2778 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2779 ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
2780 Importer.Import(D->getInnerLocStart()),
2781 Loc, Name.getAsIdentifierInfo(),
2782 T, TInfo, D->getStorageClass(),
2783 D->getStorageClassAsWritten(),
2784 /*FIXME: Default argument*/ 0);
2785 ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
2786 return Importer.Imported(D, ToParm);
2787 }
2788
VisitObjCMethodDecl(ObjCMethodDecl * D)2789 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
2790 // Import the major distinguishing characteristics of a method.
2791 DeclContext *DC, *LexicalDC;
2792 DeclarationName Name;
2793 SourceLocation Loc;
2794 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2795 return 0;
2796
2797 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2798 Lookup.first != Lookup.second;
2799 ++Lookup.first) {
2800 if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(*Lookup.first)) {
2801 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
2802 continue;
2803
2804 // Check return types.
2805 if (!Importer.IsStructurallyEquivalent(D->getResultType(),
2806 FoundMethod->getResultType())) {
2807 Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
2808 << D->isInstanceMethod() << Name
2809 << D->getResultType() << FoundMethod->getResultType();
2810 Importer.ToDiag(FoundMethod->getLocation(),
2811 diag::note_odr_objc_method_here)
2812 << D->isInstanceMethod() << Name;
2813 return 0;
2814 }
2815
2816 // Check the number of parameters.
2817 if (D->param_size() != FoundMethod->param_size()) {
2818 Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
2819 << D->isInstanceMethod() << Name
2820 << D->param_size() << FoundMethod->param_size();
2821 Importer.ToDiag(FoundMethod->getLocation(),
2822 diag::note_odr_objc_method_here)
2823 << D->isInstanceMethod() << Name;
2824 return 0;
2825 }
2826
2827 // Check parameter types.
2828 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
2829 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
2830 P != PEnd; ++P, ++FoundP) {
2831 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
2832 (*FoundP)->getType())) {
2833 Importer.FromDiag((*P)->getLocation(),
2834 diag::err_odr_objc_method_param_type_inconsistent)
2835 << D->isInstanceMethod() << Name
2836 << (*P)->getType() << (*FoundP)->getType();
2837 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
2838 << (*FoundP)->getType();
2839 return 0;
2840 }
2841 }
2842
2843 // Check variadic/non-variadic.
2844 // Check the number of parameters.
2845 if (D->isVariadic() != FoundMethod->isVariadic()) {
2846 Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
2847 << D->isInstanceMethod() << Name;
2848 Importer.ToDiag(FoundMethod->getLocation(),
2849 diag::note_odr_objc_method_here)
2850 << D->isInstanceMethod() << Name;
2851 return 0;
2852 }
2853
2854 // FIXME: Any other bits we need to merge?
2855 return Importer.Imported(D, FoundMethod);
2856 }
2857 }
2858
2859 // Import the result type.
2860 QualType ResultTy = Importer.Import(D->getResultType());
2861 if (ResultTy.isNull())
2862 return 0;
2863
2864 TypeSourceInfo *ResultTInfo = Importer.Import(D->getResultTypeSourceInfo());
2865
2866 ObjCMethodDecl *ToMethod
2867 = ObjCMethodDecl::Create(Importer.getToContext(),
2868 Loc,
2869 Importer.Import(D->getLocEnd()),
2870 Name.getObjCSelector(),
2871 ResultTy, ResultTInfo, DC,
2872 D->isInstanceMethod(),
2873 D->isVariadic(),
2874 D->isSynthesized(),
2875 D->isDefined(),
2876 D->getImplementationControl(),
2877 D->hasRelatedResultType());
2878
2879 // FIXME: When we decide to merge method definitions, we'll need to
2880 // deal with implicit parameters.
2881
2882 // Import the parameters
2883 llvm::SmallVector<ParmVarDecl *, 5> ToParams;
2884 for (ObjCMethodDecl::param_iterator FromP = D->param_begin(),
2885 FromPEnd = D->param_end();
2886 FromP != FromPEnd;
2887 ++FromP) {
2888 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(*FromP));
2889 if (!ToP)
2890 return 0;
2891
2892 ToParams.push_back(ToP);
2893 }
2894
2895 // Set the parameters.
2896 for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
2897 ToParams[I]->setOwningFunction(ToMethod);
2898 ToMethod->addDecl(ToParams[I]);
2899 }
2900 ToMethod->setMethodParams(Importer.getToContext(),
2901 ToParams.data(), ToParams.size(),
2902 ToParams.size());
2903
2904 ToMethod->setLexicalDeclContext(LexicalDC);
2905 Importer.Imported(D, ToMethod);
2906 LexicalDC->addDecl(ToMethod);
2907 return ToMethod;
2908 }
2909
VisitObjCCategoryDecl(ObjCCategoryDecl * D)2910 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
2911 // Import the major distinguishing characteristics of a category.
2912 DeclContext *DC, *LexicalDC;
2913 DeclarationName Name;
2914 SourceLocation Loc;
2915 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2916 return 0;
2917
2918 ObjCInterfaceDecl *ToInterface
2919 = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
2920 if (!ToInterface)
2921 return 0;
2922
2923 // Determine if we've already encountered this category.
2924 ObjCCategoryDecl *MergeWithCategory
2925 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
2926 ObjCCategoryDecl *ToCategory = MergeWithCategory;
2927 if (!ToCategory) {
2928 ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
2929 Importer.Import(D->getAtLoc()),
2930 Loc,
2931 Importer.Import(D->getCategoryNameLoc()),
2932 Name.getAsIdentifierInfo());
2933 ToCategory->setLexicalDeclContext(LexicalDC);
2934 LexicalDC->addDecl(ToCategory);
2935 Importer.Imported(D, ToCategory);
2936
2937 // Link this category into its class's category list.
2938 ToCategory->setClassInterface(ToInterface);
2939 ToCategory->insertNextClassCategory();
2940
2941 // Import protocols
2942 llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
2943 llvm::SmallVector<SourceLocation, 4> ProtocolLocs;
2944 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
2945 = D->protocol_loc_begin();
2946 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
2947 FromProtoEnd = D->protocol_end();
2948 FromProto != FromProtoEnd;
2949 ++FromProto, ++FromProtoLoc) {
2950 ObjCProtocolDecl *ToProto
2951 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
2952 if (!ToProto)
2953 return 0;
2954 Protocols.push_back(ToProto);
2955 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
2956 }
2957
2958 // FIXME: If we're merging, make sure that the protocol list is the same.
2959 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
2960 ProtocolLocs.data(), Importer.getToContext());
2961
2962 } else {
2963 Importer.Imported(D, ToCategory);
2964 }
2965
2966 // Import all of the members of this category.
2967 ImportDeclContext(D);
2968
2969 // If we have an implementation, import it as well.
2970 if (D->getImplementation()) {
2971 ObjCCategoryImplDecl *Impl
2972 = cast_or_null<ObjCCategoryImplDecl>(
2973 Importer.Import(D->getImplementation()));
2974 if (!Impl)
2975 return 0;
2976
2977 ToCategory->setImplementation(Impl);
2978 }
2979
2980 return ToCategory;
2981 }
2982
VisitObjCProtocolDecl(ObjCProtocolDecl * D)2983 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
2984 // Import the major distinguishing characteristics of a protocol.
2985 DeclContext *DC, *LexicalDC;
2986 DeclarationName Name;
2987 SourceLocation Loc;
2988 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2989 return 0;
2990
2991 ObjCProtocolDecl *MergeWithProtocol = 0;
2992 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2993 Lookup.first != Lookup.second;
2994 ++Lookup.first) {
2995 if (!(*Lookup.first)->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
2996 continue;
2997
2998 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(*Lookup.first)))
2999 break;
3000 }
3001
3002 ObjCProtocolDecl *ToProto = MergeWithProtocol;
3003 if (!ToProto || ToProto->isForwardDecl()) {
3004 if (!ToProto) {
3005 ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC, Loc,
3006 Name.getAsIdentifierInfo());
3007 ToProto->setForwardDecl(D->isForwardDecl());
3008 ToProto->setLexicalDeclContext(LexicalDC);
3009 LexicalDC->addDecl(ToProto);
3010 }
3011 Importer.Imported(D, ToProto);
3012
3013 // Import protocols
3014 llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
3015 llvm::SmallVector<SourceLocation, 4> ProtocolLocs;
3016 ObjCProtocolDecl::protocol_loc_iterator
3017 FromProtoLoc = D->protocol_loc_begin();
3018 for (ObjCProtocolDecl::protocol_iterator FromProto = D->protocol_begin(),
3019 FromProtoEnd = D->protocol_end();
3020 FromProto != FromProtoEnd;
3021 ++FromProto, ++FromProtoLoc) {
3022 ObjCProtocolDecl *ToProto
3023 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3024 if (!ToProto)
3025 return 0;
3026 Protocols.push_back(ToProto);
3027 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3028 }
3029
3030 // FIXME: If we're merging, make sure that the protocol list is the same.
3031 ToProto->setProtocolList(Protocols.data(), Protocols.size(),
3032 ProtocolLocs.data(), Importer.getToContext());
3033 } else {
3034 Importer.Imported(D, ToProto);
3035 }
3036
3037 // Import all of the members of this protocol.
3038 ImportDeclContext(D);
3039
3040 return ToProto;
3041 }
3042
VisitObjCInterfaceDecl(ObjCInterfaceDecl * D)3043 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
3044 // Import the major distinguishing characteristics of an @interface.
3045 DeclContext *DC, *LexicalDC;
3046 DeclarationName Name;
3047 SourceLocation Loc;
3048 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3049 return 0;
3050
3051 ObjCInterfaceDecl *MergeWithIface = 0;
3052 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
3053 Lookup.first != Lookup.second;
3054 ++Lookup.first) {
3055 if (!(*Lookup.first)->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3056 continue;
3057
3058 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(*Lookup.first)))
3059 break;
3060 }
3061
3062 ObjCInterfaceDecl *ToIface = MergeWithIface;
3063 if (!ToIface || ToIface->isForwardDecl()) {
3064 if (!ToIface) {
3065 ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(),
3066 DC, Loc,
3067 Name.getAsIdentifierInfo(),
3068 Importer.Import(D->getClassLoc()),
3069 D->isForwardDecl(),
3070 D->isImplicitInterfaceDecl());
3071 ToIface->setForwardDecl(D->isForwardDecl());
3072 ToIface->setLexicalDeclContext(LexicalDC);
3073 LexicalDC->addDecl(ToIface);
3074 }
3075 Importer.Imported(D, ToIface);
3076
3077 if (D->getSuperClass()) {
3078 ObjCInterfaceDecl *Super
3079 = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getSuperClass()));
3080 if (!Super)
3081 return 0;
3082
3083 ToIface->setSuperClass(Super);
3084 ToIface->setSuperClassLoc(Importer.Import(D->getSuperClassLoc()));
3085 }
3086
3087 // Import protocols
3088 llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
3089 llvm::SmallVector<SourceLocation, 4> ProtocolLocs;
3090 ObjCInterfaceDecl::protocol_loc_iterator
3091 FromProtoLoc = D->protocol_loc_begin();
3092
3093 // FIXME: Should we be usng all_referenced_protocol_begin() here?
3094 for (ObjCInterfaceDecl::protocol_iterator FromProto = D->protocol_begin(),
3095 FromProtoEnd = D->protocol_end();
3096 FromProto != FromProtoEnd;
3097 ++FromProto, ++FromProtoLoc) {
3098 ObjCProtocolDecl *ToProto
3099 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3100 if (!ToProto)
3101 return 0;
3102 Protocols.push_back(ToProto);
3103 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3104 }
3105
3106 // FIXME: If we're merging, make sure that the protocol list is the same.
3107 ToIface->setProtocolList(Protocols.data(), Protocols.size(),
3108 ProtocolLocs.data(), Importer.getToContext());
3109
3110 // Import @end range
3111 ToIface->setAtEndRange(Importer.Import(D->getAtEndRange()));
3112 } else {
3113 Importer.Imported(D, ToIface);
3114
3115 // Check for consistency of superclasses.
3116 DeclarationName FromSuperName, ToSuperName;
3117 if (D->getSuperClass())
3118 FromSuperName = Importer.Import(D->getSuperClass()->getDeclName());
3119 if (ToIface->getSuperClass())
3120 ToSuperName = ToIface->getSuperClass()->getDeclName();
3121 if (FromSuperName != ToSuperName) {
3122 Importer.ToDiag(ToIface->getLocation(),
3123 diag::err_odr_objc_superclass_inconsistent)
3124 << ToIface->getDeclName();
3125 if (ToIface->getSuperClass())
3126 Importer.ToDiag(ToIface->getSuperClassLoc(),
3127 diag::note_odr_objc_superclass)
3128 << ToIface->getSuperClass()->getDeclName();
3129 else
3130 Importer.ToDiag(ToIface->getLocation(),
3131 diag::note_odr_objc_missing_superclass);
3132 if (D->getSuperClass())
3133 Importer.FromDiag(D->getSuperClassLoc(),
3134 diag::note_odr_objc_superclass)
3135 << D->getSuperClass()->getDeclName();
3136 else
3137 Importer.FromDiag(D->getLocation(),
3138 diag::note_odr_objc_missing_superclass);
3139 return 0;
3140 }
3141 }
3142
3143 // Import categories. When the categories themselves are imported, they'll
3144 // hook themselves into this interface.
3145 for (ObjCCategoryDecl *FromCat = D->getCategoryList(); FromCat;
3146 FromCat = FromCat->getNextClassCategory())
3147 Importer.Import(FromCat);
3148
3149 // Import all of the members of this class.
3150 ImportDeclContext(D);
3151
3152 // If we have an @implementation, import it as well.
3153 if (D->getImplementation()) {
3154 ObjCImplementationDecl *Impl = cast_or_null<ObjCImplementationDecl>(
3155 Importer.Import(D->getImplementation()));
3156 if (!Impl)
3157 return 0;
3158
3159 ToIface->setImplementation(Impl);
3160 }
3161
3162 return ToIface;
3163 }
3164
VisitObjCCategoryImplDecl(ObjCCategoryImplDecl * D)3165 Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
3166 ObjCCategoryDecl *Category = cast_or_null<ObjCCategoryDecl>(
3167 Importer.Import(D->getCategoryDecl()));
3168 if (!Category)
3169 return 0;
3170
3171 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
3172 if (!ToImpl) {
3173 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3174 if (!DC)
3175 return 0;
3176
3177 ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
3178 Importer.Import(D->getLocation()),
3179 Importer.Import(D->getIdentifier()),
3180 Category->getClassInterface());
3181
3182 DeclContext *LexicalDC = DC;
3183 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3184 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3185 if (!LexicalDC)
3186 return 0;
3187
3188 ToImpl->setLexicalDeclContext(LexicalDC);
3189 }
3190
3191 LexicalDC->addDecl(ToImpl);
3192 Category->setImplementation(ToImpl);
3193 }
3194
3195 Importer.Imported(D, ToImpl);
3196 ImportDeclContext(D);
3197 return ToImpl;
3198 }
3199
VisitObjCImplementationDecl(ObjCImplementationDecl * D)3200 Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
3201 // Find the corresponding interface.
3202 ObjCInterfaceDecl *Iface = cast_or_null<ObjCInterfaceDecl>(
3203 Importer.Import(D->getClassInterface()));
3204 if (!Iface)
3205 return 0;
3206
3207 // Import the superclass, if any.
3208 ObjCInterfaceDecl *Super = 0;
3209 if (D->getSuperClass()) {
3210 Super = cast_or_null<ObjCInterfaceDecl>(
3211 Importer.Import(D->getSuperClass()));
3212 if (!Super)
3213 return 0;
3214 }
3215
3216 ObjCImplementationDecl *Impl = Iface->getImplementation();
3217 if (!Impl) {
3218 // We haven't imported an implementation yet. Create a new @implementation
3219 // now.
3220 Impl = ObjCImplementationDecl::Create(Importer.getToContext(),
3221 Importer.ImportContext(D->getDeclContext()),
3222 Importer.Import(D->getLocation()),
3223 Iface, Super);
3224
3225 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3226 DeclContext *LexicalDC
3227 = Importer.ImportContext(D->getLexicalDeclContext());
3228 if (!LexicalDC)
3229 return 0;
3230 Impl->setLexicalDeclContext(LexicalDC);
3231 }
3232
3233 // Associate the implementation with the class it implements.
3234 Iface->setImplementation(Impl);
3235 Importer.Imported(D, Iface->getImplementation());
3236 } else {
3237 Importer.Imported(D, Iface->getImplementation());
3238
3239 // Verify that the existing @implementation has the same superclass.
3240 if ((Super && !Impl->getSuperClass()) ||
3241 (!Super && Impl->getSuperClass()) ||
3242 (Super && Impl->getSuperClass() &&
3243 Super->getCanonicalDecl() != Impl->getSuperClass())) {
3244 Importer.ToDiag(Impl->getLocation(),
3245 diag::err_odr_objc_superclass_inconsistent)
3246 << Iface->getDeclName();
3247 // FIXME: It would be nice to have the location of the superclass
3248 // below.
3249 if (Impl->getSuperClass())
3250 Importer.ToDiag(Impl->getLocation(),
3251 diag::note_odr_objc_superclass)
3252 << Impl->getSuperClass()->getDeclName();
3253 else
3254 Importer.ToDiag(Impl->getLocation(),
3255 diag::note_odr_objc_missing_superclass);
3256 if (D->getSuperClass())
3257 Importer.FromDiag(D->getLocation(),
3258 diag::note_odr_objc_superclass)
3259 << D->getSuperClass()->getDeclName();
3260 else
3261 Importer.FromDiag(D->getLocation(),
3262 diag::note_odr_objc_missing_superclass);
3263 return 0;
3264 }
3265 }
3266
3267 // Import all of the members of this @implementation.
3268 ImportDeclContext(D);
3269
3270 return Impl;
3271 }
3272
VisitObjCPropertyDecl(ObjCPropertyDecl * D)3273 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
3274 // Import the major distinguishing characteristics of an @property.
3275 DeclContext *DC, *LexicalDC;
3276 DeclarationName Name;
3277 SourceLocation Loc;
3278 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3279 return 0;
3280
3281 // Check whether we have already imported this property.
3282 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
3283 Lookup.first != Lookup.second;
3284 ++Lookup.first) {
3285 if (ObjCPropertyDecl *FoundProp
3286 = dyn_cast<ObjCPropertyDecl>(*Lookup.first)) {
3287 // Check property types.
3288 if (!Importer.IsStructurallyEquivalent(D->getType(),
3289 FoundProp->getType())) {
3290 Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
3291 << Name << D->getType() << FoundProp->getType();
3292 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
3293 << FoundProp->getType();
3294 return 0;
3295 }
3296
3297 // FIXME: Check property attributes, getters, setters, etc.?
3298
3299 // Consider these properties to be equivalent.
3300 Importer.Imported(D, FoundProp);
3301 return FoundProp;
3302 }
3303 }
3304
3305 // Import the type.
3306 TypeSourceInfo *T = Importer.Import(D->getTypeSourceInfo());
3307 if (!T)
3308 return 0;
3309
3310 // Create the new property.
3311 ObjCPropertyDecl *ToProperty
3312 = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
3313 Name.getAsIdentifierInfo(),
3314 Importer.Import(D->getAtLoc()),
3315 T,
3316 D->getPropertyImplementation());
3317 Importer.Imported(D, ToProperty);
3318 ToProperty->setLexicalDeclContext(LexicalDC);
3319 LexicalDC->addDecl(ToProperty);
3320
3321 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
3322 ToProperty->setPropertyAttributesAsWritten(
3323 D->getPropertyAttributesAsWritten());
3324 ToProperty->setGetterName(Importer.Import(D->getGetterName()));
3325 ToProperty->setSetterName(Importer.Import(D->getSetterName()));
3326 ToProperty->setGetterMethodDecl(
3327 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
3328 ToProperty->setSetterMethodDecl(
3329 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
3330 ToProperty->setPropertyIvarDecl(
3331 cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
3332 return ToProperty;
3333 }
3334
VisitObjCPropertyImplDecl(ObjCPropertyImplDecl * D)3335 Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
3336 ObjCPropertyDecl *Property = cast_or_null<ObjCPropertyDecl>(
3337 Importer.Import(D->getPropertyDecl()));
3338 if (!Property)
3339 return 0;
3340
3341 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3342 if (!DC)
3343 return 0;
3344
3345 // Import the lexical declaration context.
3346 DeclContext *LexicalDC = DC;
3347 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3348 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3349 if (!LexicalDC)
3350 return 0;
3351 }
3352
3353 ObjCImplDecl *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
3354 if (!InImpl)
3355 return 0;
3356
3357 // Import the ivar (for an @synthesize).
3358 ObjCIvarDecl *Ivar = 0;
3359 if (D->getPropertyIvarDecl()) {
3360 Ivar = cast_or_null<ObjCIvarDecl>(
3361 Importer.Import(D->getPropertyIvarDecl()));
3362 if (!Ivar)
3363 return 0;
3364 }
3365
3366 ObjCPropertyImplDecl *ToImpl
3367 = InImpl->FindPropertyImplDecl(Property->getIdentifier());
3368 if (!ToImpl) {
3369 ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC,
3370 Importer.Import(D->getLocStart()),
3371 Importer.Import(D->getLocation()),
3372 Property,
3373 D->getPropertyImplementation(),
3374 Ivar,
3375 Importer.Import(D->getPropertyIvarDeclLoc()));
3376 ToImpl->setLexicalDeclContext(LexicalDC);
3377 Importer.Imported(D, ToImpl);
3378 LexicalDC->addDecl(ToImpl);
3379 } else {
3380 // Check that we have the same kind of property implementation (@synthesize
3381 // vs. @dynamic).
3382 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
3383 Importer.ToDiag(ToImpl->getLocation(),
3384 diag::err_odr_objc_property_impl_kind_inconsistent)
3385 << Property->getDeclName()
3386 << (ToImpl->getPropertyImplementation()
3387 == ObjCPropertyImplDecl::Dynamic);
3388 Importer.FromDiag(D->getLocation(),
3389 diag::note_odr_objc_property_impl_kind)
3390 << D->getPropertyDecl()->getDeclName()
3391 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
3392 return 0;
3393 }
3394
3395 // For @synthesize, check that we have the same
3396 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
3397 Ivar != ToImpl->getPropertyIvarDecl()) {
3398 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
3399 diag::err_odr_objc_synthesize_ivar_inconsistent)
3400 << Property->getDeclName()
3401 << ToImpl->getPropertyIvarDecl()->getDeclName()
3402 << Ivar->getDeclName();
3403 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
3404 diag::note_odr_objc_synthesize_ivar_here)
3405 << D->getPropertyIvarDecl()->getDeclName();
3406 return 0;
3407 }
3408
3409 // Merge the existing implementation with the new implementation.
3410 Importer.Imported(D, ToImpl);
3411 }
3412
3413 return ToImpl;
3414 }
3415
3416 Decl *
VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl * D)3417 ASTNodeImporter::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
3418 // Import the context of this declaration.
3419 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3420 if (!DC)
3421 return 0;
3422
3423 DeclContext *LexicalDC = DC;
3424 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3425 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3426 if (!LexicalDC)
3427 return 0;
3428 }
3429
3430 // Import the location of this declaration.
3431 SourceLocation Loc = Importer.Import(D->getLocation());
3432
3433 llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
3434 llvm::SmallVector<SourceLocation, 4> Locations;
3435 ObjCForwardProtocolDecl::protocol_loc_iterator FromProtoLoc
3436 = D->protocol_loc_begin();
3437 for (ObjCForwardProtocolDecl::protocol_iterator FromProto
3438 = D->protocol_begin(), FromProtoEnd = D->protocol_end();
3439 FromProto != FromProtoEnd;
3440 ++FromProto, ++FromProtoLoc) {
3441 ObjCProtocolDecl *ToProto
3442 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3443 if (!ToProto)
3444 continue;
3445
3446 Protocols.push_back(ToProto);
3447 Locations.push_back(Importer.Import(*FromProtoLoc));
3448 }
3449
3450 ObjCForwardProtocolDecl *ToForward
3451 = ObjCForwardProtocolDecl::Create(Importer.getToContext(), DC, Loc,
3452 Protocols.data(), Protocols.size(),
3453 Locations.data());
3454 ToForward->setLexicalDeclContext(LexicalDC);
3455 LexicalDC->addDecl(ToForward);
3456 Importer.Imported(D, ToForward);
3457 return ToForward;
3458 }
3459
VisitObjCClassDecl(ObjCClassDecl * D)3460 Decl *ASTNodeImporter::VisitObjCClassDecl(ObjCClassDecl *D) {
3461 // Import the context of this declaration.
3462 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3463 if (!DC)
3464 return 0;
3465
3466 DeclContext *LexicalDC = DC;
3467 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3468 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3469 if (!LexicalDC)
3470 return 0;
3471 }
3472
3473 // Import the location of this declaration.
3474 SourceLocation Loc = Importer.Import(D->getLocation());
3475
3476 llvm::SmallVector<ObjCInterfaceDecl *, 4> Interfaces;
3477 llvm::SmallVector<SourceLocation, 4> Locations;
3478 for (ObjCClassDecl::iterator From = D->begin(), FromEnd = D->end();
3479 From != FromEnd; ++From) {
3480 ObjCInterfaceDecl *ToIface
3481 = cast_or_null<ObjCInterfaceDecl>(Importer.Import(From->getInterface()));
3482 if (!ToIface)
3483 continue;
3484
3485 Interfaces.push_back(ToIface);
3486 Locations.push_back(Importer.Import(From->getLocation()));
3487 }
3488
3489 ObjCClassDecl *ToClass = ObjCClassDecl::Create(Importer.getToContext(), DC,
3490 Loc,
3491 Interfaces.data(),
3492 Locations.data(),
3493 Interfaces.size());
3494 ToClass->setLexicalDeclContext(LexicalDC);
3495 LexicalDC->addDecl(ToClass);
3496 Importer.Imported(D, ToClass);
3497 return ToClass;
3498 }
3499
VisitTemplateTypeParmDecl(TemplateTypeParmDecl * D)3500 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
3501 // For template arguments, we adopt the translation unit as our declaration
3502 // context. This context will be fixed when the actual template declaration
3503 // is created.
3504
3505 // FIXME: Import default argument.
3506 return TemplateTypeParmDecl::Create(Importer.getToContext(),
3507 Importer.getToContext().getTranslationUnitDecl(),
3508 Importer.Import(D->getLocStart()),
3509 Importer.Import(D->getLocation()),
3510 D->getDepth(),
3511 D->getIndex(),
3512 Importer.Import(D->getIdentifier()),
3513 D->wasDeclaredWithTypename(),
3514 D->isParameterPack());
3515 }
3516
3517 Decl *
VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl * D)3518 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
3519 // Import the name of this declaration.
3520 DeclarationName Name = Importer.Import(D->getDeclName());
3521 if (D->getDeclName() && !Name)
3522 return 0;
3523
3524 // Import the location of this declaration.
3525 SourceLocation Loc = Importer.Import(D->getLocation());
3526
3527 // Import the type of this declaration.
3528 QualType T = Importer.Import(D->getType());
3529 if (T.isNull())
3530 return 0;
3531
3532 // Import type-source information.
3533 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3534 if (D->getTypeSourceInfo() && !TInfo)
3535 return 0;
3536
3537 // FIXME: Import default argument.
3538
3539 return NonTypeTemplateParmDecl::Create(Importer.getToContext(),
3540 Importer.getToContext().getTranslationUnitDecl(),
3541 Importer.Import(D->getInnerLocStart()),
3542 Loc, D->getDepth(), D->getPosition(),
3543 Name.getAsIdentifierInfo(),
3544 T, D->isParameterPack(), TInfo);
3545 }
3546
3547 Decl *
VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl * D)3548 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
3549 // Import the name of this declaration.
3550 DeclarationName Name = Importer.Import(D->getDeclName());
3551 if (D->getDeclName() && !Name)
3552 return 0;
3553
3554 // Import the location of this declaration.
3555 SourceLocation Loc = Importer.Import(D->getLocation());
3556
3557 // Import template parameters.
3558 TemplateParameterList *TemplateParams
3559 = ImportTemplateParameterList(D->getTemplateParameters());
3560 if (!TemplateParams)
3561 return 0;
3562
3563 // FIXME: Import default argument.
3564
3565 return TemplateTemplateParmDecl::Create(Importer.getToContext(),
3566 Importer.getToContext().getTranslationUnitDecl(),
3567 Loc, D->getDepth(), D->getPosition(),
3568 D->isParameterPack(),
3569 Name.getAsIdentifierInfo(),
3570 TemplateParams);
3571 }
3572
VisitClassTemplateDecl(ClassTemplateDecl * D)3573 Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
3574 // If this record has a definition in the translation unit we're coming from,
3575 // but this particular declaration is not that definition, import the
3576 // definition and map to that.
3577 CXXRecordDecl *Definition
3578 = cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
3579 if (Definition && Definition != D->getTemplatedDecl()) {
3580 Decl *ImportedDef
3581 = Importer.Import(Definition->getDescribedClassTemplate());
3582 if (!ImportedDef)
3583 return 0;
3584
3585 return Importer.Imported(D, ImportedDef);
3586 }
3587
3588 // Import the major distinguishing characteristics of this class template.
3589 DeclContext *DC, *LexicalDC;
3590 DeclarationName Name;
3591 SourceLocation Loc;
3592 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3593 return 0;
3594
3595 // We may already have a template of the same name; try to find and match it.
3596 if (!DC->isFunctionOrMethod()) {
3597 llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
3598 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
3599 Lookup.first != Lookup.second;
3600 ++Lookup.first) {
3601 if (!(*Lookup.first)->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3602 continue;
3603
3604 Decl *Found = *Lookup.first;
3605 if (ClassTemplateDecl *FoundTemplate
3606 = dyn_cast<ClassTemplateDecl>(Found)) {
3607 if (IsStructuralMatch(D, FoundTemplate)) {
3608 // The class templates structurally match; call it the same template.
3609 // FIXME: We may be filling in a forward declaration here. Handle
3610 // this case!
3611 Importer.Imported(D->getTemplatedDecl(),
3612 FoundTemplate->getTemplatedDecl());
3613 return Importer.Imported(D, FoundTemplate);
3614 }
3615 }
3616
3617 ConflictingDecls.push_back(*Lookup.first);
3618 }
3619
3620 if (!ConflictingDecls.empty()) {
3621 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
3622 ConflictingDecls.data(),
3623 ConflictingDecls.size());
3624 }
3625
3626 if (!Name)
3627 return 0;
3628 }
3629
3630 CXXRecordDecl *DTemplated = D->getTemplatedDecl();
3631
3632 // Create the declaration that is being templated.
3633 SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
3634 SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
3635 CXXRecordDecl *D2Templated = CXXRecordDecl::Create(Importer.getToContext(),
3636 DTemplated->getTagKind(),
3637 DC, StartLoc, IdLoc,
3638 Name.getAsIdentifierInfo());
3639 D2Templated->setAccess(DTemplated->getAccess());
3640 D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
3641 D2Templated->setLexicalDeclContext(LexicalDC);
3642
3643 // Create the class template declaration itself.
3644 TemplateParameterList *TemplateParams
3645 = ImportTemplateParameterList(D->getTemplateParameters());
3646 if (!TemplateParams)
3647 return 0;
3648
3649 ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC,
3650 Loc, Name, TemplateParams,
3651 D2Templated,
3652 /*PrevDecl=*/0);
3653 D2Templated->setDescribedClassTemplate(D2);
3654
3655 D2->setAccess(D->getAccess());
3656 D2->setLexicalDeclContext(LexicalDC);
3657 LexicalDC->addDecl(D2);
3658
3659 // Note the relationship between the class templates.
3660 Importer.Imported(D, D2);
3661 Importer.Imported(DTemplated, D2Templated);
3662
3663 if (DTemplated->isDefinition() && !D2Templated->isDefinition()) {
3664 // FIXME: Import definition!
3665 }
3666
3667 return D2;
3668 }
3669
VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl * D)3670 Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
3671 ClassTemplateSpecializationDecl *D) {
3672 // If this record has a definition in the translation unit we're coming from,
3673 // but this particular declaration is not that definition, import the
3674 // definition and map to that.
3675 TagDecl *Definition = D->getDefinition();
3676 if (Definition && Definition != D) {
3677 Decl *ImportedDef = Importer.Import(Definition);
3678 if (!ImportedDef)
3679 return 0;
3680
3681 return Importer.Imported(D, ImportedDef);
3682 }
3683
3684 ClassTemplateDecl *ClassTemplate
3685 = cast_or_null<ClassTemplateDecl>(Importer.Import(
3686 D->getSpecializedTemplate()));
3687 if (!ClassTemplate)
3688 return 0;
3689
3690 // Import the context of this declaration.
3691 DeclContext *DC = ClassTemplate->getDeclContext();
3692 if (!DC)
3693 return 0;
3694
3695 DeclContext *LexicalDC = DC;
3696 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3697 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3698 if (!LexicalDC)
3699 return 0;
3700 }
3701
3702 // Import the location of this declaration.
3703 SourceLocation StartLoc = Importer.Import(D->getLocStart());
3704 SourceLocation IdLoc = Importer.Import(D->getLocation());
3705
3706 // Import template arguments.
3707 llvm::SmallVector<TemplateArgument, 2> TemplateArgs;
3708 if (ImportTemplateArguments(D->getTemplateArgs().data(),
3709 D->getTemplateArgs().size(),
3710 TemplateArgs))
3711 return 0;
3712
3713 // Try to find an existing specialization with these template arguments.
3714 void *InsertPos = 0;
3715 ClassTemplateSpecializationDecl *D2
3716 = ClassTemplate->findSpecialization(TemplateArgs.data(),
3717 TemplateArgs.size(), InsertPos);
3718 if (D2) {
3719 // We already have a class template specialization with these template
3720 // arguments.
3721
3722 // FIXME: Check for specialization vs. instantiation errors.
3723
3724 if (RecordDecl *FoundDef = D2->getDefinition()) {
3725 if (!D->isDefinition() || IsStructuralMatch(D, FoundDef)) {
3726 // The record types structurally match, or the "from" translation
3727 // unit only had a forward declaration anyway; call it the same
3728 // function.
3729 return Importer.Imported(D, FoundDef);
3730 }
3731 }
3732 } else {
3733 // Create a new specialization.
3734 D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(),
3735 D->getTagKind(), DC,
3736 StartLoc, IdLoc,
3737 ClassTemplate,
3738 TemplateArgs.data(),
3739 TemplateArgs.size(),
3740 /*PrevDecl=*/0);
3741 D2->setSpecializationKind(D->getSpecializationKind());
3742
3743 // Add this specialization to the class template.
3744 ClassTemplate->AddSpecialization(D2, InsertPos);
3745
3746 // Import the qualifier, if any.
3747 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3748
3749 // Add the specialization to this context.
3750 D2->setLexicalDeclContext(LexicalDC);
3751 LexicalDC->addDecl(D2);
3752 }
3753 Importer.Imported(D, D2);
3754
3755 if (D->isDefinition() && ImportDefinition(D, D2))
3756 return 0;
3757
3758 return D2;
3759 }
3760
3761 //----------------------------------------------------------------------------
3762 // Import Statements
3763 //----------------------------------------------------------------------------
3764
VisitStmt(Stmt * S)3765 Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
3766 Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
3767 << S->getStmtClassName();
3768 return 0;
3769 }
3770
3771 //----------------------------------------------------------------------------
3772 // Import Expressions
3773 //----------------------------------------------------------------------------
VisitExpr(Expr * E)3774 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
3775 Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
3776 << E->getStmtClassName();
3777 return 0;
3778 }
3779
VisitDeclRefExpr(DeclRefExpr * E)3780 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
3781 ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
3782 if (!ToD)
3783 return 0;
3784
3785 NamedDecl *FoundD = 0;
3786 if (E->getDecl() != E->getFoundDecl()) {
3787 FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
3788 if (!FoundD)
3789 return 0;
3790 }
3791
3792 QualType T = Importer.Import(E->getType());
3793 if (T.isNull())
3794 return 0;
3795
3796 return DeclRefExpr::Create(Importer.getToContext(),
3797 Importer.Import(E->getQualifierLoc()),
3798 ToD,
3799 Importer.Import(E->getLocation()),
3800 T, E->getValueKind(),
3801 FoundD,
3802 /*FIXME:TemplateArgs=*/0);
3803 }
3804
VisitIntegerLiteral(IntegerLiteral * E)3805 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
3806 QualType T = Importer.Import(E->getType());
3807 if (T.isNull())
3808 return 0;
3809
3810 return IntegerLiteral::Create(Importer.getToContext(),
3811 E->getValue(), T,
3812 Importer.Import(E->getLocation()));
3813 }
3814
VisitCharacterLiteral(CharacterLiteral * E)3815 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
3816 QualType T = Importer.Import(E->getType());
3817 if (T.isNull())
3818 return 0;
3819
3820 return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
3821 E->isWide(), T,
3822 Importer.Import(E->getLocation()));
3823 }
3824
VisitParenExpr(ParenExpr * E)3825 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
3826 Expr *SubExpr = Importer.Import(E->getSubExpr());
3827 if (!SubExpr)
3828 return 0;
3829
3830 return new (Importer.getToContext())
3831 ParenExpr(Importer.Import(E->getLParen()),
3832 Importer.Import(E->getRParen()),
3833 SubExpr);
3834 }
3835
VisitUnaryOperator(UnaryOperator * E)3836 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
3837 QualType T = Importer.Import(E->getType());
3838 if (T.isNull())
3839 return 0;
3840
3841 Expr *SubExpr = Importer.Import(E->getSubExpr());
3842 if (!SubExpr)
3843 return 0;
3844
3845 return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
3846 T, E->getValueKind(),
3847 E->getObjectKind(),
3848 Importer.Import(E->getOperatorLoc()));
3849 }
3850
VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr * E)3851 Expr *ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(
3852 UnaryExprOrTypeTraitExpr *E) {
3853 QualType ResultType = Importer.Import(E->getType());
3854
3855 if (E->isArgumentType()) {
3856 TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
3857 if (!TInfo)
3858 return 0;
3859
3860 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
3861 TInfo, ResultType,
3862 Importer.Import(E->getOperatorLoc()),
3863 Importer.Import(E->getRParenLoc()));
3864 }
3865
3866 Expr *SubExpr = Importer.Import(E->getArgumentExpr());
3867 if (!SubExpr)
3868 return 0;
3869
3870 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
3871 SubExpr, ResultType,
3872 Importer.Import(E->getOperatorLoc()),
3873 Importer.Import(E->getRParenLoc()));
3874 }
3875
VisitBinaryOperator(BinaryOperator * E)3876 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
3877 QualType T = Importer.Import(E->getType());
3878 if (T.isNull())
3879 return 0;
3880
3881 Expr *LHS = Importer.Import(E->getLHS());
3882 if (!LHS)
3883 return 0;
3884
3885 Expr *RHS = Importer.Import(E->getRHS());
3886 if (!RHS)
3887 return 0;
3888
3889 return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
3890 T, E->getValueKind(),
3891 E->getObjectKind(),
3892 Importer.Import(E->getOperatorLoc()));
3893 }
3894
VisitCompoundAssignOperator(CompoundAssignOperator * E)3895 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
3896 QualType T = Importer.Import(E->getType());
3897 if (T.isNull())
3898 return 0;
3899
3900 QualType CompLHSType = Importer.Import(E->getComputationLHSType());
3901 if (CompLHSType.isNull())
3902 return 0;
3903
3904 QualType CompResultType = Importer.Import(E->getComputationResultType());
3905 if (CompResultType.isNull())
3906 return 0;
3907
3908 Expr *LHS = Importer.Import(E->getLHS());
3909 if (!LHS)
3910 return 0;
3911
3912 Expr *RHS = Importer.Import(E->getRHS());
3913 if (!RHS)
3914 return 0;
3915
3916 return new (Importer.getToContext())
3917 CompoundAssignOperator(LHS, RHS, E->getOpcode(),
3918 T, E->getValueKind(),
3919 E->getObjectKind(),
3920 CompLHSType, CompResultType,
3921 Importer.Import(E->getOperatorLoc()));
3922 }
3923
ImportCastPath(CastExpr * E,CXXCastPath & Path)3924 static bool ImportCastPath(CastExpr *E, CXXCastPath &Path) {
3925 if (E->path_empty()) return false;
3926
3927 // TODO: import cast paths
3928 return true;
3929 }
3930
VisitImplicitCastExpr(ImplicitCastExpr * E)3931 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
3932 QualType T = Importer.Import(E->getType());
3933 if (T.isNull())
3934 return 0;
3935
3936 Expr *SubExpr = Importer.Import(E->getSubExpr());
3937 if (!SubExpr)
3938 return 0;
3939
3940 CXXCastPath BasePath;
3941 if (ImportCastPath(E, BasePath))
3942 return 0;
3943
3944 return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
3945 SubExpr, &BasePath, E->getValueKind());
3946 }
3947
VisitCStyleCastExpr(CStyleCastExpr * E)3948 Expr *ASTNodeImporter::VisitCStyleCastExpr(CStyleCastExpr *E) {
3949 QualType T = Importer.Import(E->getType());
3950 if (T.isNull())
3951 return 0;
3952
3953 Expr *SubExpr = Importer.Import(E->getSubExpr());
3954 if (!SubExpr)
3955 return 0;
3956
3957 TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
3958 if (!TInfo && E->getTypeInfoAsWritten())
3959 return 0;
3960
3961 CXXCastPath BasePath;
3962 if (ImportCastPath(E, BasePath))
3963 return 0;
3964
3965 return CStyleCastExpr::Create(Importer.getToContext(), T,
3966 E->getValueKind(), E->getCastKind(),
3967 SubExpr, &BasePath, TInfo,
3968 Importer.Import(E->getLParenLoc()),
3969 Importer.Import(E->getRParenLoc()));
3970 }
3971
ASTImporter(ASTContext & ToContext,FileManager & ToFileManager,ASTContext & FromContext,FileManager & FromFileManager,bool MinimalImport)3972 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
3973 ASTContext &FromContext, FileManager &FromFileManager,
3974 bool MinimalImport)
3975 : ToContext(ToContext), FromContext(FromContext),
3976 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
3977 Minimal(MinimalImport)
3978 {
3979 ImportedDecls[FromContext.getTranslationUnitDecl()]
3980 = ToContext.getTranslationUnitDecl();
3981 }
3982
~ASTImporter()3983 ASTImporter::~ASTImporter() { }
3984
Import(QualType FromT)3985 QualType ASTImporter::Import(QualType FromT) {
3986 if (FromT.isNull())
3987 return QualType();
3988
3989 const Type *fromTy = FromT.getTypePtr();
3990
3991 // Check whether we've already imported this type.
3992 llvm::DenseMap<const Type *, const Type *>::iterator Pos
3993 = ImportedTypes.find(fromTy);
3994 if (Pos != ImportedTypes.end())
3995 return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
3996
3997 // Import the type
3998 ASTNodeImporter Importer(*this);
3999 QualType ToT = Importer.Visit(fromTy);
4000 if (ToT.isNull())
4001 return ToT;
4002
4003 // Record the imported type.
4004 ImportedTypes[fromTy] = ToT.getTypePtr();
4005
4006 return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
4007 }
4008
Import(TypeSourceInfo * FromTSI)4009 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
4010 if (!FromTSI)
4011 return FromTSI;
4012
4013 // FIXME: For now we just create a "trivial" type source info based
4014 // on the type and a single location. Implement a real version of this.
4015 QualType T = Import(FromTSI->getType());
4016 if (T.isNull())
4017 return 0;
4018
4019 return ToContext.getTrivialTypeSourceInfo(T,
4020 FromTSI->getTypeLoc().getSourceRange().getBegin());
4021 }
4022
Import(Decl * FromD)4023 Decl *ASTImporter::Import(Decl *FromD) {
4024 if (!FromD)
4025 return 0;
4026
4027 // Check whether we've already imported this declaration.
4028 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
4029 if (Pos != ImportedDecls.end())
4030 return Pos->second;
4031
4032 // Import the type
4033 ASTNodeImporter Importer(*this);
4034 Decl *ToD = Importer.Visit(FromD);
4035 if (!ToD)
4036 return 0;
4037
4038 // Record the imported declaration.
4039 ImportedDecls[FromD] = ToD;
4040
4041 if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
4042 // Keep track of anonymous tags that have an associated typedef.
4043 if (FromTag->getTypedefNameForAnonDecl())
4044 AnonTagsWithPendingTypedefs.push_back(FromTag);
4045 } else if (TypedefNameDecl *FromTypedef = dyn_cast<TypedefNameDecl>(FromD)) {
4046 // When we've finished transforming a typedef, see whether it was the
4047 // typedef for an anonymous tag.
4048 for (llvm::SmallVector<TagDecl *, 4>::iterator
4049 FromTag = AnonTagsWithPendingTypedefs.begin(),
4050 FromTagEnd = AnonTagsWithPendingTypedefs.end();
4051 FromTag != FromTagEnd; ++FromTag) {
4052 if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) {
4053 if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
4054 // We found the typedef for an anonymous tag; link them.
4055 ToTag->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToD));
4056 AnonTagsWithPendingTypedefs.erase(FromTag);
4057 break;
4058 }
4059 }
4060 }
4061 }
4062
4063 return ToD;
4064 }
4065
ImportContext(DeclContext * FromDC)4066 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
4067 if (!FromDC)
4068 return FromDC;
4069
4070 return cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
4071 }
4072
Import(Expr * FromE)4073 Expr *ASTImporter::Import(Expr *FromE) {
4074 if (!FromE)
4075 return 0;
4076
4077 return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
4078 }
4079
Import(Stmt * FromS)4080 Stmt *ASTImporter::Import(Stmt *FromS) {
4081 if (!FromS)
4082 return 0;
4083
4084 // Check whether we've already imported this declaration.
4085 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
4086 if (Pos != ImportedStmts.end())
4087 return Pos->second;
4088
4089 // Import the type
4090 ASTNodeImporter Importer(*this);
4091 Stmt *ToS = Importer.Visit(FromS);
4092 if (!ToS)
4093 return 0;
4094
4095 // Record the imported declaration.
4096 ImportedStmts[FromS] = ToS;
4097 return ToS;
4098 }
4099
Import(NestedNameSpecifier * FromNNS)4100 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
4101 if (!FromNNS)
4102 return 0;
4103
4104 NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
4105
4106 switch (FromNNS->getKind()) {
4107 case NestedNameSpecifier::Identifier:
4108 if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
4109 return NestedNameSpecifier::Create(ToContext, prefix, II);
4110 }
4111 return 0;
4112
4113 case NestedNameSpecifier::Namespace:
4114 if (NamespaceDecl *NS =
4115 cast<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
4116 return NestedNameSpecifier::Create(ToContext, prefix, NS);
4117 }
4118 return 0;
4119
4120 case NestedNameSpecifier::NamespaceAlias:
4121 if (NamespaceAliasDecl *NSAD =
4122 cast<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
4123 return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
4124 }
4125 return 0;
4126
4127 case NestedNameSpecifier::Global:
4128 return NestedNameSpecifier::GlobalSpecifier(ToContext);
4129
4130 case NestedNameSpecifier::TypeSpec:
4131 case NestedNameSpecifier::TypeSpecWithTemplate: {
4132 QualType T = Import(QualType(FromNNS->getAsType(), 0u));
4133 if (!T.isNull()) {
4134 bool bTemplate = FromNNS->getKind() ==
4135 NestedNameSpecifier::TypeSpecWithTemplate;
4136 return NestedNameSpecifier::Create(ToContext, prefix,
4137 bTemplate, T.getTypePtr());
4138 }
4139 }
4140 return 0;
4141 }
4142
4143 llvm_unreachable("Invalid nested name specifier kind");
4144 return 0;
4145 }
4146
Import(NestedNameSpecifierLoc FromNNS)4147 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
4148 // FIXME: Implement!
4149 return NestedNameSpecifierLoc();
4150 }
4151
Import(TemplateName From)4152 TemplateName ASTImporter::Import(TemplateName From) {
4153 switch (From.getKind()) {
4154 case TemplateName::Template:
4155 if (TemplateDecl *ToTemplate
4156 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
4157 return TemplateName(ToTemplate);
4158
4159 return TemplateName();
4160
4161 case TemplateName::OverloadedTemplate: {
4162 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
4163 UnresolvedSet<2> ToTemplates;
4164 for (OverloadedTemplateStorage::iterator I = FromStorage->begin(),
4165 E = FromStorage->end();
4166 I != E; ++I) {
4167 if (NamedDecl *To = cast_or_null<NamedDecl>(Import(*I)))
4168 ToTemplates.addDecl(To);
4169 else
4170 return TemplateName();
4171 }
4172 return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
4173 ToTemplates.end());
4174 }
4175
4176 case TemplateName::QualifiedTemplate: {
4177 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
4178 NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
4179 if (!Qualifier)
4180 return TemplateName();
4181
4182 if (TemplateDecl *ToTemplate
4183 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
4184 return ToContext.getQualifiedTemplateName(Qualifier,
4185 QTN->hasTemplateKeyword(),
4186 ToTemplate);
4187
4188 return TemplateName();
4189 }
4190
4191 case TemplateName::DependentTemplate: {
4192 DependentTemplateName *DTN = From.getAsDependentTemplateName();
4193 NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
4194 if (!Qualifier)
4195 return TemplateName();
4196
4197 if (DTN->isIdentifier()) {
4198 return ToContext.getDependentTemplateName(Qualifier,
4199 Import(DTN->getIdentifier()));
4200 }
4201
4202 return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
4203 }
4204
4205 case TemplateName::SubstTemplateTemplateParm: {
4206 SubstTemplateTemplateParmStorage *subst
4207 = From.getAsSubstTemplateTemplateParm();
4208 TemplateTemplateParmDecl *param
4209 = cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
4210 if (!param)
4211 return TemplateName();
4212
4213 TemplateName replacement = Import(subst->getReplacement());
4214 if (replacement.isNull()) return TemplateName();
4215
4216 return ToContext.getSubstTemplateTemplateParm(param, replacement);
4217 }
4218
4219 case TemplateName::SubstTemplateTemplateParmPack: {
4220 SubstTemplateTemplateParmPackStorage *SubstPack
4221 = From.getAsSubstTemplateTemplateParmPack();
4222 TemplateTemplateParmDecl *Param
4223 = cast_or_null<TemplateTemplateParmDecl>(
4224 Import(SubstPack->getParameterPack()));
4225 if (!Param)
4226 return TemplateName();
4227
4228 ASTNodeImporter Importer(*this);
4229 TemplateArgument ArgPack
4230 = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
4231 if (ArgPack.isNull())
4232 return TemplateName();
4233
4234 return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
4235 }
4236 }
4237
4238 llvm_unreachable("Invalid template name kind");
4239 return TemplateName();
4240 }
4241
Import(SourceLocation FromLoc)4242 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
4243 if (FromLoc.isInvalid())
4244 return SourceLocation();
4245
4246 SourceManager &FromSM = FromContext.getSourceManager();
4247
4248 // For now, map everything down to its spelling location, so that we
4249 // don't have to import macro expansions.
4250 // FIXME: Import macro expansions!
4251 FromLoc = FromSM.getSpellingLoc(FromLoc);
4252 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
4253 SourceManager &ToSM = ToContext.getSourceManager();
4254 return ToSM.getLocForStartOfFile(Import(Decomposed.first))
4255 .getFileLocWithOffset(Decomposed.second);
4256 }
4257
Import(SourceRange FromRange)4258 SourceRange ASTImporter::Import(SourceRange FromRange) {
4259 return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
4260 }
4261
Import(FileID FromID)4262 FileID ASTImporter::Import(FileID FromID) {
4263 llvm::DenseMap<FileID, FileID>::iterator Pos
4264 = ImportedFileIDs.find(FromID);
4265 if (Pos != ImportedFileIDs.end())
4266 return Pos->second;
4267
4268 SourceManager &FromSM = FromContext.getSourceManager();
4269 SourceManager &ToSM = ToContext.getSourceManager();
4270 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
4271 assert(FromSLoc.isFile() && "Cannot handle macro expansions yet");
4272
4273 // Include location of this file.
4274 SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
4275
4276 // Map the FileID for to the "to" source manager.
4277 FileID ToID;
4278 const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
4279 if (Cache->OrigEntry) {
4280 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
4281 // disk again
4282 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
4283 // than mmap the files several times.
4284 const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
4285 ToID = ToSM.createFileID(Entry, ToIncludeLoc,
4286 FromSLoc.getFile().getFileCharacteristic());
4287 } else {
4288 // FIXME: We want to re-use the existing MemoryBuffer!
4289 const llvm::MemoryBuffer *
4290 FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
4291 llvm::MemoryBuffer *ToBuf
4292 = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
4293 FromBuf->getBufferIdentifier());
4294 ToID = ToSM.createFileIDForMemBuffer(ToBuf);
4295 }
4296
4297
4298 ImportedFileIDs[FromID] = ToID;
4299 return ToID;
4300 }
4301
ImportDefinition(Decl * From)4302 void ASTImporter::ImportDefinition(Decl *From) {
4303 Decl *To = Import(From);
4304 if (!To)
4305 return;
4306
4307 if (DeclContext *FromDC = cast<DeclContext>(From)) {
4308 ASTNodeImporter Importer(*this);
4309
4310 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(To)) {
4311 if (!ToRecord->getDefinition()) {
4312 Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord,
4313 /*ForceImport=*/true);
4314 return;
4315 }
4316 }
4317
4318 Importer.ImportDeclContext(FromDC, true);
4319 }
4320 }
4321
Import(DeclarationName FromName)4322 DeclarationName ASTImporter::Import(DeclarationName FromName) {
4323 if (!FromName)
4324 return DeclarationName();
4325
4326 switch (FromName.getNameKind()) {
4327 case DeclarationName::Identifier:
4328 return Import(FromName.getAsIdentifierInfo());
4329
4330 case DeclarationName::ObjCZeroArgSelector:
4331 case DeclarationName::ObjCOneArgSelector:
4332 case DeclarationName::ObjCMultiArgSelector:
4333 return Import(FromName.getObjCSelector());
4334
4335 case DeclarationName::CXXConstructorName: {
4336 QualType T = Import(FromName.getCXXNameType());
4337 if (T.isNull())
4338 return DeclarationName();
4339
4340 return ToContext.DeclarationNames.getCXXConstructorName(
4341 ToContext.getCanonicalType(T));
4342 }
4343
4344 case DeclarationName::CXXDestructorName: {
4345 QualType T = Import(FromName.getCXXNameType());
4346 if (T.isNull())
4347 return DeclarationName();
4348
4349 return ToContext.DeclarationNames.getCXXDestructorName(
4350 ToContext.getCanonicalType(T));
4351 }
4352
4353 case DeclarationName::CXXConversionFunctionName: {
4354 QualType T = Import(FromName.getCXXNameType());
4355 if (T.isNull())
4356 return DeclarationName();
4357
4358 return ToContext.DeclarationNames.getCXXConversionFunctionName(
4359 ToContext.getCanonicalType(T));
4360 }
4361
4362 case DeclarationName::CXXOperatorName:
4363 return ToContext.DeclarationNames.getCXXOperatorName(
4364 FromName.getCXXOverloadedOperator());
4365
4366 case DeclarationName::CXXLiteralOperatorName:
4367 return ToContext.DeclarationNames.getCXXLiteralOperatorName(
4368 Import(FromName.getCXXLiteralIdentifier()));
4369
4370 case DeclarationName::CXXUsingDirective:
4371 // FIXME: STATICS!
4372 return DeclarationName::getUsingDirectiveName();
4373 }
4374
4375 // Silence bogus GCC warning
4376 return DeclarationName();
4377 }
4378
Import(const IdentifierInfo * FromId)4379 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
4380 if (!FromId)
4381 return 0;
4382
4383 return &ToContext.Idents.get(FromId->getName());
4384 }
4385
Import(Selector FromSel)4386 Selector ASTImporter::Import(Selector FromSel) {
4387 if (FromSel.isNull())
4388 return Selector();
4389
4390 llvm::SmallVector<IdentifierInfo *, 4> Idents;
4391 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
4392 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
4393 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
4394 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
4395 }
4396
HandleNameConflict(DeclarationName Name,DeclContext * DC,unsigned IDNS,NamedDecl ** Decls,unsigned NumDecls)4397 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
4398 DeclContext *DC,
4399 unsigned IDNS,
4400 NamedDecl **Decls,
4401 unsigned NumDecls) {
4402 return Name;
4403 }
4404
ToDiag(SourceLocation Loc,unsigned DiagID)4405 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
4406 return ToContext.getDiagnostics().Report(Loc, DiagID);
4407 }
4408
FromDiag(SourceLocation Loc,unsigned DiagID)4409 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
4410 return FromContext.getDiagnostics().Report(Loc, DiagID);
4411 }
4412
Imported(Decl * From,Decl * To)4413 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
4414 ImportedDecls[From] = To;
4415 return To;
4416 }
4417
IsStructurallyEquivalent(QualType From,QualType To)4418 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To) {
4419 llvm::DenseMap<const Type *, const Type *>::iterator Pos
4420 = ImportedTypes.find(From.getTypePtr());
4421 if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
4422 return true;
4423
4424 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls);
4425 return Ctx.IsStructurallyEquivalent(From, To);
4426 }
4427