clang  10.0.0svn
ASTImporter.cpp
Go to the documentation of this file.
1 //===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the ASTImporter class which imports AST nodes from one
10 // context into another context.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTImporter.h"
16 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclBase.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclFriend.h"
25 #include "clang/AST/DeclGroup.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/DeclVisitor.h"
30 #include "clang/AST/Expr.h"
31 #include "clang/AST/ExprCXX.h"
32 #include "clang/AST/ExprObjC.h"
37 #include "clang/AST/Stmt.h"
38 #include "clang/AST/StmtCXX.h"
39 #include "clang/AST/StmtObjC.h"
40 #include "clang/AST/StmtVisitor.h"
41 #include "clang/AST/TemplateBase.h"
42 #include "clang/AST/TemplateName.h"
43 #include "clang/AST/Type.h"
44 #include "clang/AST/TypeLoc.h"
45 #include "clang/AST/TypeVisitor.h"
50 #include "clang/Basic/LLVM.h"
54 #include "clang/Basic/Specifiers.h"
55 #include "llvm/ADT/APSInt.h"
56 #include "llvm/ADT/ArrayRef.h"
57 #include "llvm/ADT/DenseMap.h"
58 #include "llvm/ADT/None.h"
59 #include "llvm/ADT/Optional.h"
60 #include "llvm/ADT/ScopeExit.h"
61 #include "llvm/ADT/STLExtras.h"
62 #include "llvm/ADT/SmallVector.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/MemoryBuffer.h"
66 #include <algorithm>
67 #include <cassert>
68 #include <cstddef>
69 #include <memory>
70 #include <type_traits>
71 #include <utility>
72 
73 namespace clang {
74 
75  using llvm::make_error;
76  using llvm::Error;
77  using llvm::Expected;
84 
85  std::string ImportError::toString() const {
86  // FIXME: Improve error texts.
87  switch (Error) {
88  case NameConflict:
89  return "NameConflict";
91  return "UnsupportedConstruct";
92  case Unknown:
93  return "Unknown error";
94  }
95  llvm_unreachable("Invalid error code.");
96  return "Invalid error code.";
97  }
98 
99  void ImportError::log(raw_ostream &OS) const {
100  OS << toString();
101  }
102 
103  std::error_code ImportError::convertToErrorCode() const {
104  llvm_unreachable("Function not implemented.");
105  }
106 
107  char ImportError::ID;
108 
109  template <class T>
112  SmallVector<Decl *, 2> Redecls;
113  for (auto *R : D->getFirstDecl()->redecls()) {
114  if (R != D->getFirstDecl())
115  Redecls.push_back(R);
116  }
117  Redecls.push_back(D->getFirstDecl());
118  std::reverse(Redecls.begin(), Redecls.end());
119  return Redecls;
120  }
121 
123  if (auto *FD = dyn_cast<FunctionDecl>(D))
124  return getCanonicalForwardRedeclChain<FunctionDecl>(FD);
125  if (auto *VD = dyn_cast<VarDecl>(D))
126  return getCanonicalForwardRedeclChain<VarDecl>(VD);
127  if (auto *TD = dyn_cast<TagDecl>(D))
128  return getCanonicalForwardRedeclChain<TagDecl>(TD);
129  llvm_unreachable("Bad declaration kind");
130  }
131 
132  void updateFlags(const Decl *From, Decl *To) {
133  // Check if some flags or attrs are new in 'From' and copy into 'To'.
134  // FIXME: Other flags or attrs?
135  if (From->isUsed(false) && !To->isUsed(false))
136  To->setIsUsed();
137  }
138 
139  class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>,
140  public DeclVisitor<ASTNodeImporter, ExpectedDecl>,
141  public StmtVisitor<ASTNodeImporter, ExpectedStmt> {
142  ASTImporter &Importer;
143 
144  // Use this instead of Importer.importInto .
145  template <typename ImportT>
146  LLVM_NODISCARD Error importInto(ImportT &To, const ImportT &From) {
147  return Importer.importInto(To, From);
148  }
149 
150  // Use this to import pointers of specific type.
151  template <typename ImportT>
152  LLVM_NODISCARD Error importInto(ImportT *&To, ImportT *From) {
153  auto ToOrErr = Importer.Import(From);
154  if (ToOrErr)
155  To = cast_or_null<ImportT>(*ToOrErr);
156  return ToOrErr.takeError();
157  }
158 
159  // Call the import function of ASTImporter for a baseclass of type `T` and
160  // cast the return value to `T`.
161  template <typename T>
162  Expected<T *> import(T *From) {
163  auto ToOrErr = Importer.Import(From);
164  if (!ToOrErr)
165  return ToOrErr.takeError();
166  return cast_or_null<T>(*ToOrErr);
167  }
168 
169  template <typename T>
170  Expected<T *> import(const T *From) {
171  return import(const_cast<T *>(From));
172  }
173 
174  // Call the import function of ASTImporter for type `T`.
175  template <typename T>
176  Expected<T> import(const T &From) {
177  return Importer.Import(From);
178  }
179 
180  // Import an Optional<T> by importing the contained T, if any.
181  template<typename T>
182  Expected<Optional<T>> import(Optional<T> From) {
183  if (!From)
184  return Optional<T>();
185  return import(*From);
186  }
187 
188  template <class T>
190  importSeq(const T &From) {
191  Expected<T> ToOrErr = import(From);
192  if (!ToOrErr)
193  return ToOrErr.takeError();
194  return std::make_tuple<T>(std::move(*ToOrErr));
195  }
196 
197  // Import multiple objects with a single function call.
198  // This should work for every type for which a variant of `import` exists.
199  // The arguments are processed from left to right and import is stopped on
200  // first error.
201  template <class THead, class... TTail>
202  Expected<std::tuple<THead, TTail...>>
203  importSeq(const THead &FromHead, const TTail &...FromTail) {
204  Expected<std::tuple<THead>> ToHeadOrErr = importSeq(FromHead);
205  if (!ToHeadOrErr)
206  return ToHeadOrErr.takeError();
207  Expected<std::tuple<TTail...>> ToTailOrErr = importSeq(FromTail...);
208  if (!ToTailOrErr)
209  return ToTailOrErr.takeError();
210  return std::tuple_cat(*ToHeadOrErr, *ToTailOrErr);
211  }
212 
213 // Wrapper for an overload set.
214  template <typename ToDeclT> struct CallOverloadedCreateFun {
215  template <typename... Args>
216  auto operator()(Args &&... args)
217  -> decltype(ToDeclT::Create(std::forward<Args>(args)...)) {
218  return ToDeclT::Create(std::forward<Args>(args)...);
219  }
220  };
221 
222  // Always use these functions to create a Decl during import. There are
223  // certain tasks which must be done after the Decl was created, e.g. we
224  // must immediately register that as an imported Decl. The parameter `ToD`
225  // will be set to the newly created Decl or if had been imported before
226  // then to the already imported Decl. Returns a bool value set to true if
227  // the `FromD` had been imported before.
228  template <typename ToDeclT, typename FromDeclT, typename... Args>
229  LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
230  Args &&... args) {
231  // There may be several overloads of ToDeclT::Create. We must make sure
232  // to call the one which would be chosen by the arguments, thus we use a
233  // wrapper for the overload set.
234  CallOverloadedCreateFun<ToDeclT> OC;
235  return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
236  std::forward<Args>(args)...);
237  }
238  // Use this overload if a special Type is needed to be created. E.g if we
239  // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
240  // then:
241  // TypedefNameDecl *ToTypedef;
242  // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
243  template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
244  typename... Args>
245  LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
246  Args &&... args) {
247  CallOverloadedCreateFun<NewDeclT> OC;
248  return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
249  std::forward<Args>(args)...);
250  }
251  // Use this version if a special create function must be
252  // used, e.g. CXXRecordDecl::CreateLambda .
253  template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
254  typename... Args>
255  LLVM_NODISCARD bool
256  GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
257  FromDeclT *FromD, Args &&... args) {
258  if (Importer.getImportDeclErrorIfAny(FromD)) {
259  ToD = nullptr;
260  return true; // Already imported but with error.
261  }
262  ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
263  if (ToD)
264  return true; // Already imported.
265  ToD = CreateFun(std::forward<Args>(args)...);
266  // Keep track of imported Decls.
267  Importer.RegisterImportedDecl(FromD, ToD);
268  InitializeImportedDecl(FromD, ToD);
269  return false; // A new Decl is created.
270  }
271 
272  void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
274  if (FromD->hasAttrs())
275  for (const Attr *FromAttr : FromD->getAttrs()) {
276  // FIXME: Return of the error here is not possible until store of
277  // import errors is implemented.
278  auto ToAttrOrErr = import(FromAttr);
279  if (ToAttrOrErr)
280  ToD->addAttr(*ToAttrOrErr);
281  else
282  llvm::consumeError(ToAttrOrErr.takeError());
283  }
284  if (FromD->isUsed())
285  ToD->setIsUsed();
286  if (FromD->isImplicit())
287  ToD->setImplicit();
288  }
289 
290  // Check if we have found an existing definition. Returns with that
291  // definition if yes, otherwise returns null.
292  Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) {
293  const FunctionDecl *Definition = nullptr;
294  if (D->doesThisDeclarationHaveABody() &&
295  FoundFunction->hasBody(Definition))
296  return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition));
297  return nullptr;
298  }
299 
300  public:
301  explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
302 
306 
307  // Importing types
308  ExpectedType VisitType(const Type *T);
309  ExpectedType VisitAtomicType(const AtomicType *T);
310  ExpectedType VisitBuiltinType(const BuiltinType *T);
311  ExpectedType VisitDecayedType(const DecayedType *T);
312  ExpectedType VisitComplexType(const ComplexType *T);
313  ExpectedType VisitPointerType(const PointerType *T);
314  ExpectedType VisitBlockPointerType(const BlockPointerType *T);
315  ExpectedType VisitLValueReferenceType(const LValueReferenceType *T);
316  ExpectedType VisitRValueReferenceType(const RValueReferenceType *T);
317  ExpectedType VisitMemberPointerType(const MemberPointerType *T);
318  ExpectedType VisitConstantArrayType(const ConstantArrayType *T);
319  ExpectedType VisitIncompleteArrayType(const IncompleteArrayType *T);
320  ExpectedType VisitVariableArrayType(const VariableArrayType *T);
321  ExpectedType VisitDependentSizedArrayType(const DependentSizedArrayType *T);
322  // FIXME: DependentSizedExtVectorType
323  ExpectedType VisitVectorType(const VectorType *T);
324  ExpectedType VisitExtVectorType(const ExtVectorType *T);
325  ExpectedType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
326  ExpectedType VisitFunctionProtoType(const FunctionProtoType *T);
327  ExpectedType VisitUnresolvedUsingType(const UnresolvedUsingType *T);
328  ExpectedType VisitParenType(const ParenType *T);
329  ExpectedType VisitTypedefType(const TypedefType *T);
330  ExpectedType VisitTypeOfExprType(const TypeOfExprType *T);
331  // FIXME: DependentTypeOfExprType
332  ExpectedType VisitTypeOfType(const TypeOfType *T);
333  ExpectedType VisitDecltypeType(const DecltypeType *T);
334  ExpectedType VisitUnaryTransformType(const UnaryTransformType *T);
335  ExpectedType VisitAutoType(const AutoType *T);
336  ExpectedType VisitInjectedClassNameType(const InjectedClassNameType *T);
337  // FIXME: DependentDecltypeType
338  ExpectedType VisitRecordType(const RecordType *T);
339  ExpectedType VisitEnumType(const EnumType *T);
340  ExpectedType VisitAttributedType(const AttributedType *T);
341  ExpectedType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
342  ExpectedType VisitSubstTemplateTypeParmType(
343  const SubstTemplateTypeParmType *T);
344  ExpectedType VisitTemplateSpecializationType(
345  const TemplateSpecializationType *T);
346  ExpectedType VisitElaboratedType(const ElaboratedType *T);
347  ExpectedType VisitDependentNameType(const DependentNameType *T);
348  ExpectedType VisitPackExpansionType(const PackExpansionType *T);
349  ExpectedType VisitDependentTemplateSpecializationType(
351  ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T);
352  ExpectedType VisitObjCObjectType(const ObjCObjectType *T);
353  ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
354 
355  // Importing declarations
356  Error ImportDeclParts(
357  NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
358  DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc);
359  Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
360  Error ImportDeclarationNameLoc(
361  const DeclarationNameInfo &From, DeclarationNameInfo &To);
362  Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
363  Error ImportDeclContext(
364  Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
365  Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
366 
367  Expected<CXXCastPath> ImportCastPath(CastExpr *E);
368 
370 
371  /// What we should import from the definition.
373  /// Import the default subset of the definition, which might be
374  /// nothing (if minimal import is set) or might be everything (if minimal
375  /// import is not set).
377  /// Import everything.
379  /// Import only the bare bones needed to establish a valid
380  /// DeclContext.
381  IDK_Basic
382  };
383 
385  return IDK == IDK_Everything ||
386  (IDK == IDK_Default && !Importer.isMinimalImport());
387  }
388 
389  Error ImportInitializer(VarDecl *From, VarDecl *To);
390  Error ImportDefinition(
391  RecordDecl *From, RecordDecl *To,
392  ImportDefinitionKind Kind = IDK_Default);
393  Error ImportDefinition(
394  EnumDecl *From, EnumDecl *To,
395  ImportDefinitionKind Kind = IDK_Default);
396  Error ImportDefinition(
398  ImportDefinitionKind Kind = IDK_Default);
399  Error ImportDefinition(
401  ImportDefinitionKind Kind = IDK_Default);
402  Error ImportTemplateArguments(
403  const TemplateArgument *FromArgs, unsigned NumFromArgs,
406  ImportTemplateArgument(const TemplateArgument &From);
407 
408  template <typename InContainerTy>
409  Error ImportTemplateArgumentListInfo(
410  const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
411 
412  template<typename InContainerTy>
413  Error ImportTemplateArgumentListInfo(
414  SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
415  const InContainerTy &Container, TemplateArgumentListInfo &Result);
416 
419  std::tuple<FunctionTemplateDecl *, TemplateArgsTy>;
421  ImportFunctionTemplateWithTemplateArgsFromSpecialization(
422  FunctionDecl *FromFD);
423  Error ImportTemplateParameterLists(const DeclaratorDecl *FromD,
424  DeclaratorDecl *ToD);
425 
426  Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
427 
428  Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD);
429 
430  Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam,
431  ParmVarDecl *ToParam);
432 
433  template <typename T>
434  bool hasSameVisibilityContext(T *Found, T *From);
435 
436  bool IsStructuralMatch(Decl *From, Decl *To, bool Complain);
437  bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
438  bool Complain = true);
439  bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
440  bool Complain = true);
441  bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
442  bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
443  bool IsStructuralMatch(FunctionTemplateDecl *From,
445  bool IsStructuralMatch(FunctionDecl *From, FunctionDecl *To);
446  bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
447  bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
448  ExpectedDecl VisitDecl(Decl *D);
449  ExpectedDecl VisitImportDecl(ImportDecl *D);
450  ExpectedDecl VisitEmptyDecl(EmptyDecl *D);
451  ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D);
452  ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D);
453  ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D);
454  ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D);
455  ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
456  ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
457  ExpectedDecl VisitTypedefDecl(TypedefDecl *D);
458  ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D);
459  ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
460  ExpectedDecl VisitLabelDecl(LabelDecl *D);
461  ExpectedDecl VisitEnumDecl(EnumDecl *D);
462  ExpectedDecl VisitRecordDecl(RecordDecl *D);
463  ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D);
464  ExpectedDecl VisitFunctionDecl(FunctionDecl *D);
465  ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D);
466  ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D);
467  ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D);
468  ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D);
469  ExpectedDecl VisitFieldDecl(FieldDecl *D);
470  ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D);
471  ExpectedDecl VisitFriendDecl(FriendDecl *D);
472  ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D);
473  ExpectedDecl VisitVarDecl(VarDecl *D);
474  ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D);
475  ExpectedDecl VisitParmVarDecl(ParmVarDecl *D);
476  ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D);
477  ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
478  ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D);
479  ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D);
480  ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D);
481  ExpectedDecl VisitUsingDecl(UsingDecl *D);
482  ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D);
483  ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
484  ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
485  ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
486 
488  ImportObjCTypeParamList(ObjCTypeParamList *list);
489 
490  ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
491  ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
492  ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D);
493  ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D);
494  ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
495  ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
496  ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
497  ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
498  ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D);
499  ExpectedDecl VisitClassTemplateSpecializationDecl(
501  ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D);
502  ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
503  ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
504 
505  // Importing statements
506  ExpectedStmt VisitStmt(Stmt *S);
507  ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S);
508  ExpectedStmt VisitDeclStmt(DeclStmt *S);
509  ExpectedStmt VisitNullStmt(NullStmt *S);
510  ExpectedStmt VisitCompoundStmt(CompoundStmt *S);
511  ExpectedStmt VisitCaseStmt(CaseStmt *S);
512  ExpectedStmt VisitDefaultStmt(DefaultStmt *S);
513  ExpectedStmt VisitLabelStmt(LabelStmt *S);
514  ExpectedStmt VisitAttributedStmt(AttributedStmt *S);
515  ExpectedStmt VisitIfStmt(IfStmt *S);
516  ExpectedStmt VisitSwitchStmt(SwitchStmt *S);
517  ExpectedStmt VisitWhileStmt(WhileStmt *S);
518  ExpectedStmt VisitDoStmt(DoStmt *S);
519  ExpectedStmt VisitForStmt(ForStmt *S);
520  ExpectedStmt VisitGotoStmt(GotoStmt *S);
521  ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S);
522  ExpectedStmt VisitContinueStmt(ContinueStmt *S);
523  ExpectedStmt VisitBreakStmt(BreakStmt *S);
524  ExpectedStmt VisitReturnStmt(ReturnStmt *S);
525  // FIXME: MSAsmStmt
526  // FIXME: SEHExceptStmt
527  // FIXME: SEHFinallyStmt
528  // FIXME: SEHTryStmt
529  // FIXME: SEHLeaveStmt
530  // FIXME: CapturedStmt
531  ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S);
532  ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S);
533  ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S);
534  // FIXME: MSDependentExistsStmt
535  ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
536  ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
537  ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
538  ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S);
539  ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
540  ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
541  ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
542 
543  // Importing expressions
544  ExpectedStmt VisitExpr(Expr *E);
545  ExpectedStmt VisitVAArgExpr(VAArgExpr *E);
546  ExpectedStmt VisitChooseExpr(ChooseExpr *E);
547  ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E);
548  ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E);
549  ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E);
550  ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
551  ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E);
552  ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
553  ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E);
554  ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E);
555  ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E);
556  ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E);
557  ExpectedStmt VisitStringLiteral(StringLiteral *E);
558  ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
559  ExpectedStmt VisitAtomicExpr(AtomicExpr *E);
560  ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E);
561  ExpectedStmt VisitConstantExpr(ConstantExpr *E);
562  ExpectedStmt VisitParenExpr(ParenExpr *E);
563  ExpectedStmt VisitParenListExpr(ParenListExpr *E);
564  ExpectedStmt VisitStmtExpr(StmtExpr *E);
565  ExpectedStmt VisitUnaryOperator(UnaryOperator *E);
566  ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
567  ExpectedStmt VisitBinaryOperator(BinaryOperator *E);
568  ExpectedStmt VisitConditionalOperator(ConditionalOperator *E);
569  ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
570  ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E);
571  ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
572  ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E);
573  ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E);
574  ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E);
575  ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E);
576  ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E);
577  ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE);
578  ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E);
579  ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
580  ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
581  ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
582  ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
583  ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
584  ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
585  ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E);
586  ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E);
587  ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E);
588  ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E);
589  ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E);
590  ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
591  ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
592  ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
593  ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
594  ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E);
595  ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
596  ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E);
597  ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E);
598  ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
599  ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
600  ExpectedStmt VisitMemberExpr(MemberExpr *E);
601  ExpectedStmt VisitCallExpr(CallExpr *E);
602  ExpectedStmt VisitLambdaExpr(LambdaExpr *LE);
603  ExpectedStmt VisitInitListExpr(InitListExpr *E);
604  ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
605  ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E);
606  ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
607  ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
608  ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
609  ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
610  ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
611  ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E);
612  ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E);
613 
614  template<typename IIter, typename OIter>
615  Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
616  using ItemT = typename std::remove_reference<decltype(*Obegin)>::type;
617  for (; Ibegin != Iend; ++Ibegin, ++Obegin) {
618  Expected<ItemT> ToOrErr = import(*Ibegin);
619  if (!ToOrErr)
620  return ToOrErr.takeError();
621  *Obegin = *ToOrErr;
622  }
623  return Error::success();
624  }
625 
626  // Import every item from a container structure into an output container.
627  // If error occurs, stops at first error and returns the error.
628  // The output container should have space for all needed elements (it is not
629  // expanded, new items are put into from the beginning).
630  template<typename InContainerTy, typename OutContainerTy>
632  const InContainerTy &InContainer, OutContainerTy &OutContainer) {
633  return ImportArrayChecked(
634  InContainer.begin(), InContainer.end(), OutContainer.begin());
635  }
636 
637  template<typename InContainerTy, typename OIter>
638  Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
639  return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
640  }
641 
642  Error ImportOverriddenMethods(CXXMethodDecl *ToMethod,
643  CXXMethodDecl *FromMethod);
644 
645  Expected<FunctionDecl *> FindFunctionTemplateSpecialization(
646  FunctionDecl *FromFD);
647  };
648 
649 template <typename InContainerTy>
651  SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
652  const InContainerTy &Container, TemplateArgumentListInfo &Result) {
653  auto ToLAngleLocOrErr = import(FromLAngleLoc);
654  if (!ToLAngleLocOrErr)
655  return ToLAngleLocOrErr.takeError();
656  auto ToRAngleLocOrErr = import(FromRAngleLoc);
657  if (!ToRAngleLocOrErr)
658  return ToRAngleLocOrErr.takeError();
659 
660  TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
661  if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
662  return Err;
663  Result = ToTAInfo;
664  return Error::success();
665 }
666 
667 template <>
668 Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
670  return ImportTemplateArgumentListInfo(
671  From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
672 }
673 
674 template <>
677  const ASTTemplateArgumentListInfo &From,
679  return ImportTemplateArgumentListInfo(
680  From.LAngleLoc, From.RAngleLoc, From.arguments(), Result);
681 }
682 
685  FunctionDecl *FromFD) {
686  assert(FromFD->getTemplatedKind() ==
688 
690 
691  auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
692  if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate()))
693  return std::move(Err);
694 
695  // Import template arguments.
696  auto TemplArgs = FTSInfo->TemplateArguments->asArray();
697  if (Error Err = ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(),
698  std::get<1>(Result)))
699  return std::move(Err);
700 
701  return Result;
702 }
703 
704 template <>
706 ASTNodeImporter::import(TemplateParameterList *From) {
707  SmallVector<NamedDecl *, 4> To(From->size());
708  if (Error Err = ImportContainerChecked(*From, To))
709  return std::move(Err);
710 
711  ExpectedExpr ToRequiresClause = import(From->getRequiresClause());
712  if (!ToRequiresClause)
713  return ToRequiresClause.takeError();
714 
715  auto ToTemplateLocOrErr = import(From->getTemplateLoc());
716  if (!ToTemplateLocOrErr)
717  return ToTemplateLocOrErr.takeError();
718  auto ToLAngleLocOrErr = import(From->getLAngleLoc());
719  if (!ToLAngleLocOrErr)
720  return ToLAngleLocOrErr.takeError();
721  auto ToRAngleLocOrErr = import(From->getRAngleLoc());
722  if (!ToRAngleLocOrErr)
723  return ToRAngleLocOrErr.takeError();
724 
726  Importer.getToContext(),
727  *ToTemplateLocOrErr,
728  *ToLAngleLocOrErr,
729  To,
730  *ToRAngleLocOrErr,
731  *ToRequiresClause);
732 }
733 
734 template <>
736 ASTNodeImporter::import(const TemplateArgument &From) {
737  switch (From.getKind()) {
739  return TemplateArgument();
740 
741  case TemplateArgument::Type: {
742  ExpectedType ToTypeOrErr = import(From.getAsType());
743  if (!ToTypeOrErr)
744  return ToTypeOrErr.takeError();
745  return TemplateArgument(*ToTypeOrErr);
746  }
747 
749  ExpectedType ToTypeOrErr = import(From.getIntegralType());
750  if (!ToTypeOrErr)
751  return ToTypeOrErr.takeError();
752  return TemplateArgument(From, *ToTypeOrErr);
753  }
754 
756  Expected<ValueDecl *> ToOrErr = import(From.getAsDecl());
757  if (!ToOrErr)
758  return ToOrErr.takeError();
759  ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl());
760  if (!ToTypeOrErr)
761  return ToTypeOrErr.takeError();
762  return TemplateArgument(*ToOrErr, *ToTypeOrErr);
763  }
764 
766  ExpectedType ToTypeOrErr = import(From.getNullPtrType());
767  if (!ToTypeOrErr)
768  return ToTypeOrErr.takeError();
769  return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/true);
770  }
771 
773  Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate());
774  if (!ToTemplateOrErr)
775  return ToTemplateOrErr.takeError();
776 
777  return TemplateArgument(*ToTemplateOrErr);
778  }
779 
781  Expected<TemplateName> ToTemplateOrErr =
782  import(From.getAsTemplateOrTemplatePattern());
783  if (!ToTemplateOrErr)
784  return ToTemplateOrErr.takeError();
785 
786  return TemplateArgument(
787  *ToTemplateOrErr, From.getNumTemplateExpansions());
788  }
789 
791  if (ExpectedExpr ToExpr = import(From.getAsExpr()))
792  return TemplateArgument(*ToExpr);
793  else
794  return ToExpr.takeError();
795 
796  case TemplateArgument::Pack: {
798  ToPack.reserve(From.pack_size());
799  if (Error Err = ImportTemplateArguments(
800  From.pack_begin(), From.pack_size(), ToPack))
801  return std::move(Err);
802 
803  return TemplateArgument(
804  llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
805  }
806  }
807 
808  llvm_unreachable("Invalid template argument kind");
809 }
810 
811 template <>
813 ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
814  Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument());
815  if (!ArgOrErr)
816  return ArgOrErr.takeError();
817  TemplateArgument Arg = *ArgOrErr;
818 
819  TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
820 
822  if (Arg.getKind() == TemplateArgument::Expression) {
823  ExpectedExpr E = import(FromInfo.getAsExpr());
824  if (!E)
825  return E.takeError();
826  ToInfo = TemplateArgumentLocInfo(*E);
827  } else if (Arg.getKind() == TemplateArgument::Type) {
828  if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo()))
829  ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
830  else
831  return TSIOrErr.takeError();
832  } else {
833  auto ToTemplateQualifierLocOrErr =
834  import(FromInfo.getTemplateQualifierLoc());
835  if (!ToTemplateQualifierLocOrErr)
836  return ToTemplateQualifierLocOrErr.takeError();
837  auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc());
838  if (!ToTemplateNameLocOrErr)
839  return ToTemplateNameLocOrErr.takeError();
840  auto ToTemplateEllipsisLocOrErr =
841  import(FromInfo.getTemplateEllipsisLoc());
842  if (!ToTemplateEllipsisLocOrErr)
843  return ToTemplateEllipsisLocOrErr.takeError();
844 
845  ToInfo = TemplateArgumentLocInfo(
846  *ToTemplateQualifierLocOrErr,
847  *ToTemplateNameLocOrErr,
848  *ToTemplateEllipsisLocOrErr);
849  }
850 
851  return TemplateArgumentLoc(Arg, ToInfo);
852 }
853 
854 template <>
855 Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
856  if (DG.isNull())
857  return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
858  size_t NumDecls = DG.end() - DG.begin();
859  SmallVector<Decl *, 1> ToDecls;
860  ToDecls.reserve(NumDecls);
861  for (Decl *FromD : DG) {
862  if (auto ToDOrErr = import(FromD))
863  ToDecls.push_back(*ToDOrErr);
864  else
865  return ToDOrErr.takeError();
866  }
867  return DeclGroupRef::Create(Importer.getToContext(),
868  ToDecls.begin(),
869  NumDecls);
870 }
871 
872 template <>
874 ASTNodeImporter::import(const Designator &D) {
875  if (D.isFieldDesignator()) {
876  IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
877 
878  ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc());
879  if (!ToDotLocOrErr)
880  return ToDotLocOrErr.takeError();
881 
882  ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc());
883  if (!ToFieldLocOrErr)
884  return ToFieldLocOrErr.takeError();
885 
886  return Designator(ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr);
887  }
888 
889  ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc());
890  if (!ToLBracketLocOrErr)
891  return ToLBracketLocOrErr.takeError();
892 
893  ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc());
894  if (!ToRBracketLocOrErr)
895  return ToRBracketLocOrErr.takeError();
896 
897  if (D.isArrayDesignator())
898  return Designator(D.getFirstExprIndex(),
899  *ToLBracketLocOrErr, *ToRBracketLocOrErr);
900 
901  ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc());
902  if (!ToEllipsisLocOrErr)
903  return ToEllipsisLocOrErr.takeError();
904 
905  assert(D.isArrayRangeDesignator());
906  return Designator(
907  D.getFirstExprIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr,
908  *ToRBracketLocOrErr);
909 }
910 
911 template <>
912 Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
913  VarDecl *Var = nullptr;
914  if (From.capturesVariable()) {
915  if (auto VarOrErr = import(From.getCapturedVar()))
916  Var = *VarOrErr;
917  else
918  return VarOrErr.takeError();
919  }
920 
921  auto LocationOrErr = import(From.getLocation());
922  if (!LocationOrErr)
923  return LocationOrErr.takeError();
924 
925  SourceLocation EllipsisLoc;
926  if (From.isPackExpansion())
927  if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc()))
928  return std::move(Err);
929 
930  return LambdaCapture(
931  *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
932  EllipsisLoc);
933 }
934 
935 template <typename T>
937  if (From->hasExternalFormalLinkage())
938  return Found->hasExternalFormalLinkage();
939  if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl())
940  return false;
941  if (From->isInAnonymousNamespace())
942  return Found->isInAnonymousNamespace();
943  else
944  return !Found->isInAnonymousNamespace() &&
945  !Found->hasExternalFormalLinkage();
946 }
947 
948 template <>
950  TypedefNameDecl *From) {
951  if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace())
952  return Importer.GetFromTU(Found) == From->getTranslationUnitDecl();
953  return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace();
954 }
955 
956 } // namespace clang
957 
958 //----------------------------------------------------------------------------
959 // Import Types
960 //----------------------------------------------------------------------------
961 
962 using namespace clang;
963 
965  Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
966  << T->getTypeClassName();
967  return make_error<ImportError>(ImportError::UnsupportedConstruct);
968 }
969 
971  ExpectedType UnderlyingTypeOrErr = import(T->getValueType());
972  if (!UnderlyingTypeOrErr)
973  return UnderlyingTypeOrErr.takeError();
974 
975  return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr);
976 }
977 
979  switch (T->getKind()) {
980 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
981  case BuiltinType::Id: \
982  return Importer.getToContext().SingletonId;
983 #include "clang/Basic/OpenCLImageTypes.def"
984 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
985  case BuiltinType::Id: \
986  return Importer.getToContext().Id##Ty;
987 #include "clang/Basic/OpenCLExtensionTypes.def"
988 #define SVE_TYPE(Name, Id, SingletonId) \
989  case BuiltinType::Id: \
990  return Importer.getToContext().SingletonId;
991 #include "clang/Basic/AArch64SVEACLETypes.def"
992 #define SHARED_SINGLETON_TYPE(Expansion)
993 #define BUILTIN_TYPE(Id, SingletonId) \
994  case BuiltinType::Id: return Importer.getToContext().SingletonId;
995 #include "clang/AST/BuiltinTypes.def"
996 
997  // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
998  // context supports C++.
999 
1000  // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1001  // context supports ObjC.
1002 
1003  case BuiltinType::Char_U:
1004  // The context we're importing from has an unsigned 'char'. If we're
1005  // importing into a context with a signed 'char', translate to
1006  // 'unsigned char' instead.
1007  if (Importer.getToContext().getLangOpts().CharIsSigned)
1008  return Importer.getToContext().UnsignedCharTy;
1009 
1010  return Importer.getToContext().CharTy;
1011 
1012  case BuiltinType::Char_S:
1013  // The context we're importing from has an unsigned 'char'. If we're
1014  // importing into a context with a signed 'char', translate to
1015  // 'unsigned char' instead.
1016  if (!Importer.getToContext().getLangOpts().CharIsSigned)
1017  return Importer.getToContext().SignedCharTy;
1018 
1019  return Importer.getToContext().CharTy;
1020 
1021  case BuiltinType::WChar_S:
1022  case BuiltinType::WChar_U:
1023  // FIXME: If not in C++, shall we translate to the C equivalent of
1024  // wchar_t?
1025  return Importer.getToContext().WCharTy;
1026  }
1027 
1028  llvm_unreachable("Invalid BuiltinType Kind!");
1029 }
1030 
1032  ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType());
1033  if (!ToOriginalTypeOrErr)
1034  return ToOriginalTypeOrErr.takeError();
1035 
1036  return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr);
1037 }
1038 
1040  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1041  if (!ToElementTypeOrErr)
1042  return ToElementTypeOrErr.takeError();
1043 
1044  return Importer.getToContext().getComplexType(*ToElementTypeOrErr);
1045 }
1046 
1048  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1049  if (!ToPointeeTypeOrErr)
1050  return ToPointeeTypeOrErr.takeError();
1051 
1052  return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr);
1053 }
1054 
1056  // FIXME: Check for blocks support in "to" context.
1057  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1058  if (!ToPointeeTypeOrErr)
1059  return ToPointeeTypeOrErr.takeError();
1060 
1061  return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr);
1062 }
1063 
1066  // FIXME: Check for C++ support in "to" context.
1067  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1068  if (!ToPointeeTypeOrErr)
1069  return ToPointeeTypeOrErr.takeError();
1070 
1071  return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr);
1072 }
1073 
1076  // FIXME: Check for C++0x support in "to" context.
1077  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1078  if (!ToPointeeTypeOrErr)
1079  return ToPointeeTypeOrErr.takeError();
1080 
1081  return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr);
1082 }
1083 
1086  // FIXME: Check for C++ support in "to" context.
1087  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1088  if (!ToPointeeTypeOrErr)
1089  return ToPointeeTypeOrErr.takeError();
1090 
1091  ExpectedType ClassTypeOrErr = import(QualType(T->getClass(), 0));
1092  if (!ClassTypeOrErr)
1093  return ClassTypeOrErr.takeError();
1094 
1095  return Importer.getToContext().getMemberPointerType(
1096  *ToPointeeTypeOrErr, (*ClassTypeOrErr).getTypePtr());
1097 }
1098 
1101  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1102  if (!ToElementTypeOrErr)
1103  return ToElementTypeOrErr.takeError();
1104 
1105  return Importer.getToContext().getConstantArrayType(*ToElementTypeOrErr,
1106  T->getSize(),
1107  T->getSizeModifier(),
1109 }
1110 
1113  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1114  if (!ToElementTypeOrErr)
1115  return ToElementTypeOrErr.takeError();
1116 
1117  return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr,
1118  T->getSizeModifier(),
1120 }
1121 
1124  QualType ToElementType;
1125  Expr *ToSizeExpr;
1126  SourceRange ToBracketsRange;
1127  if (auto Imp = importSeq(
1128  T->getElementType(), T->getSizeExpr(), T->getBracketsRange()))
1129  std::tie(ToElementType, ToSizeExpr, ToBracketsRange) = *Imp;
1130  else
1131  return Imp.takeError();
1132 
1133  return Importer.getToContext().getVariableArrayType(
1134  ToElementType, ToSizeExpr, T->getSizeModifier(),
1135  T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1136 }
1137 
1139  const DependentSizedArrayType *T) {
1140  QualType ToElementType;
1141  Expr *ToSizeExpr;
1142  SourceRange ToBracketsRange;
1143  if (auto Imp = importSeq(
1144  T->getElementType(), T->getSizeExpr(), T->getBracketsRange()))
1145  std::tie(ToElementType, ToSizeExpr, ToBracketsRange) = *Imp;
1146  else
1147  return Imp.takeError();
1148  // SizeExpr may be null if size is not specified directly.
1149  // For example, 'int a[]'.
1150 
1151  return Importer.getToContext().getDependentSizedArrayType(
1152  ToElementType, ToSizeExpr, T->getSizeModifier(),
1153  T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1154 }
1155 
1157  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1158  if (!ToElementTypeOrErr)
1159  return ToElementTypeOrErr.takeError();
1160 
1161  return Importer.getToContext().getVectorType(*ToElementTypeOrErr,
1162  T->getNumElements(),
1163  T->getVectorKind());
1164 }
1165 
1167  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1168  if (!ToElementTypeOrErr)
1169  return ToElementTypeOrErr.takeError();
1170 
1171  return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr,
1172  T->getNumElements());
1173 }
1174 
1177  // FIXME: What happens if we're importing a function without a prototype
1178  // into C++? Should we make it variadic?
1179  ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1180  if (!ToReturnTypeOrErr)
1181  return ToReturnTypeOrErr.takeError();
1182 
1183  return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
1184  T->getExtInfo());
1185 }
1186 
1189  ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1190  if (!ToReturnTypeOrErr)
1191  return ToReturnTypeOrErr.takeError();
1192 
1193  // Import argument types
1194  SmallVector<QualType, 4> ArgTypes;
1195  for (const auto &A : T->param_types()) {
1196  ExpectedType TyOrErr = import(A);
1197  if (!TyOrErr)
1198  return TyOrErr.takeError();
1199  ArgTypes.push_back(*TyOrErr);
1200  }
1201 
1202  // Import exception types
1203  SmallVector<QualType, 4> ExceptionTypes;
1204  for (const auto &E : T->exceptions()) {
1205  ExpectedType TyOrErr = import(E);
1206  if (!TyOrErr)
1207  return TyOrErr.takeError();
1208  ExceptionTypes.push_back(*TyOrErr);
1209  }
1210 
1213 
1214  auto Imp = importSeq(
1215  FromEPI.ExceptionSpec.NoexceptExpr,
1216  FromEPI.ExceptionSpec.SourceDecl,
1217  FromEPI.ExceptionSpec.SourceTemplate);
1218  if (!Imp)
1219  return Imp.takeError();
1220 
1221  ToEPI.ExtInfo = FromEPI.ExtInfo;
1222  ToEPI.Variadic = FromEPI.Variadic;
1223  ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1224  ToEPI.TypeQuals = FromEPI.TypeQuals;
1225  ToEPI.RefQualifier = FromEPI.RefQualifier;
1226  ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1227  ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1228  std::tie(
1230  ToEPI.ExceptionSpec.SourceDecl,
1231  ToEPI.ExceptionSpec.SourceTemplate) = *Imp;
1232 
1233  return Importer.getToContext().getFunctionType(
1234  *ToReturnTypeOrErr, ArgTypes, ToEPI);
1235 }
1236 
1238  const UnresolvedUsingType *T) {
1240  Decl *ToPrevD;
1241  if (auto Imp = importSeq(T->getDecl(), T->getDecl()->getPreviousDecl()))
1242  std::tie(ToD, ToPrevD) = *Imp;
1243  else
1244  return Imp.takeError();
1245 
1246  return Importer.getToContext().getTypeDeclType(
1247  ToD, cast_or_null<TypeDecl>(ToPrevD));
1248 }
1249 
1251  ExpectedType ToInnerTypeOrErr = import(T->getInnerType());
1252  if (!ToInnerTypeOrErr)
1253  return ToInnerTypeOrErr.takeError();
1254 
1255  return Importer.getToContext().getParenType(*ToInnerTypeOrErr);
1256 }
1257 
1259  Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl());
1260  if (!ToDeclOrErr)
1261  return ToDeclOrErr.takeError();
1262 
1263  return Importer.getToContext().getTypeDeclType(*ToDeclOrErr);
1264 }
1265 
1267  ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1268  if (!ToExprOrErr)
1269  return ToExprOrErr.takeError();
1270 
1271  return Importer.getToContext().getTypeOfExprType(*ToExprOrErr);
1272 }
1273 
1275  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1276  if (!ToUnderlyingTypeOrErr)
1277  return ToUnderlyingTypeOrErr.takeError();
1278 
1279  return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr);
1280 }
1281 
1283  // FIXME: Make sure that the "to" context supports C++0x!
1284  ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1285  if (!ToExprOrErr)
1286  return ToExprOrErr.takeError();
1287 
1288  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1289  if (!ToUnderlyingTypeOrErr)
1290  return ToUnderlyingTypeOrErr.takeError();
1291 
1292  return Importer.getToContext().getDecltypeType(
1293  *ToExprOrErr, *ToUnderlyingTypeOrErr);
1294 }
1295 
1298  ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1299  if (!ToBaseTypeOrErr)
1300  return ToBaseTypeOrErr.takeError();
1301 
1302  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1303  if (!ToUnderlyingTypeOrErr)
1304  return ToUnderlyingTypeOrErr.takeError();
1305 
1306  return Importer.getToContext().getUnaryTransformType(
1307  *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind());
1308 }
1309 
1311  // FIXME: Make sure that the "to" context supports C++11!
1312  ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1313  if (!ToDeducedTypeOrErr)
1314  return ToDeducedTypeOrErr.takeError();
1315 
1316  return Importer.getToContext().getAutoType(*ToDeducedTypeOrErr,
1317  T->getKeyword(),
1318  /*IsDependent*/false);
1319 }
1320 
1322  const InjectedClassNameType *T) {
1323  Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl());
1324  if (!ToDeclOrErr)
1325  return ToDeclOrErr.takeError();
1326 
1327  ExpectedType ToInjTypeOrErr = import(T->getInjectedSpecializationType());
1328  if (!ToInjTypeOrErr)
1329  return ToInjTypeOrErr.takeError();
1330 
1331  // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
1332  // See comments in InjectedClassNameType definition for details
1333  // return Importer.getToContext().getInjectedClassNameType(D, InjType);
1334  enum {
1335  TypeAlignmentInBits = 4,
1337  };
1338 
1339  return QualType(new (Importer.getToContext(), TypeAlignment)
1340  InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0);
1341 }
1342 
1344  Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl());
1345  if (!ToDeclOrErr)
1346  return ToDeclOrErr.takeError();
1347 
1348  return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1349 }
1350 
1352  Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl());
1353  if (!ToDeclOrErr)
1354  return ToDeclOrErr.takeError();
1355 
1356  return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1357 }
1358 
1360  ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType());
1361  if (!ToModifiedTypeOrErr)
1362  return ToModifiedTypeOrErr.takeError();
1363  ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType());
1364  if (!ToEquivalentTypeOrErr)
1365  return ToEquivalentTypeOrErr.takeError();
1366 
1367  return Importer.getToContext().getAttributedType(T->getAttrKind(),
1368  *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr);
1369 }
1370 
1372  const TemplateTypeParmType *T) {
1373  Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl());
1374  if (!ToDeclOrErr)
1375  return ToDeclOrErr.takeError();
1376 
1377  return Importer.getToContext().getTemplateTypeParmType(
1378  T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr);
1379 }
1380 
1382  const SubstTemplateTypeParmType *T) {
1383  ExpectedType ReplacedOrErr = import(QualType(T->getReplacedParameter(), 0));
1384  if (!ReplacedOrErr)
1385  return ReplacedOrErr.takeError();
1386  const TemplateTypeParmType *Replaced =
1387  cast<TemplateTypeParmType>((*ReplacedOrErr).getTypePtr());
1388 
1389  ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType());
1390  if (!ToReplacementTypeOrErr)
1391  return ToReplacementTypeOrErr.takeError();
1392 
1393  return Importer.getToContext().getSubstTemplateTypeParmType(
1394  Replaced, (*ToReplacementTypeOrErr).getCanonicalType());
1395 }
1396 
1398  const TemplateSpecializationType *T) {
1399  auto ToTemplateOrErr = import(T->getTemplateName());
1400  if (!ToTemplateOrErr)
1401  return ToTemplateOrErr.takeError();
1402 
1403  SmallVector<TemplateArgument, 2> ToTemplateArgs;
1404  if (Error Err = ImportTemplateArguments(
1405  T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1406  return std::move(Err);
1407 
1408  QualType ToCanonType;
1409  if (!QualType(T, 0).isCanonical()) {
1410  QualType FromCanonType
1411  = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1412  if (ExpectedType TyOrErr = import(FromCanonType))
1413  ToCanonType = *TyOrErr;
1414  else
1415  return TyOrErr.takeError();
1416  }
1417  return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr,
1418  ToTemplateArgs,
1419  ToCanonType);
1420 }
1421 
1423  // Note: the qualifier in an ElaboratedType is optional.
1424  auto ToQualifierOrErr = import(T->getQualifier());
1425  if (!ToQualifierOrErr)
1426  return ToQualifierOrErr.takeError();
1427 
1428  ExpectedType ToNamedTypeOrErr = import(T->getNamedType());
1429  if (!ToNamedTypeOrErr)
1430  return ToNamedTypeOrErr.takeError();
1431 
1432  Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl());
1433  if (!ToOwnedTagDeclOrErr)
1434  return ToOwnedTagDeclOrErr.takeError();
1435 
1436  return Importer.getToContext().getElaboratedType(T->getKeyword(),
1437  *ToQualifierOrErr,
1438  *ToNamedTypeOrErr,
1439  *ToOwnedTagDeclOrErr);
1440 }
1441 
1444  ExpectedType ToPatternOrErr = import(T->getPattern());
1445  if (!ToPatternOrErr)
1446  return ToPatternOrErr.takeError();
1447 
1448  return Importer.getToContext().getPackExpansionType(*ToPatternOrErr,
1449  T->getNumExpansions());
1450 }
1451 
1454  auto ToQualifierOrErr = import(T->getQualifier());
1455  if (!ToQualifierOrErr)
1456  return ToQualifierOrErr.takeError();
1457 
1458  IdentifierInfo *ToName = Importer.Import(T->getIdentifier());
1459 
1461  ToPack.reserve(T->getNumArgs());
1462  if (Error Err = ImportTemplateArguments(
1463  T->getArgs(), T->getNumArgs(), ToPack))
1464  return std::move(Err);
1465 
1466  return Importer.getToContext().getDependentTemplateSpecializationType(
1467  T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
1468 }
1469 
1472  auto ToQualifierOrErr = import(T->getQualifier());
1473  if (!ToQualifierOrErr)
1474  return ToQualifierOrErr.takeError();
1475 
1476  IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1477 
1478  QualType Canon;
1479  if (T != T->getCanonicalTypeInternal().getTypePtr()) {
1480  if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
1481  Canon = (*TyOrErr).getCanonicalType();
1482  else
1483  return TyOrErr.takeError();
1484  }
1485 
1486  return Importer.getToContext().getDependentNameType(T->getKeyword(),
1487  *ToQualifierOrErr,
1488  Name, Canon);
1489 }
1490 
1493  Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl());
1494  if (!ToDeclOrErr)
1495  return ToDeclOrErr.takeError();
1496 
1497  return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr);
1498 }
1499 
1501  ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1502  if (!ToBaseTypeOrErr)
1503  return ToBaseTypeOrErr.takeError();
1504 
1505  SmallVector<QualType, 4> TypeArgs;
1506  for (auto TypeArg : T->getTypeArgsAsWritten()) {
1507  if (ExpectedType TyOrErr = import(TypeArg))
1508  TypeArgs.push_back(*TyOrErr);
1509  else
1510  return TyOrErr.takeError();
1511  }
1512 
1514  for (auto *P : T->quals()) {
1515  if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
1516  Protocols.push_back(*ProtocolOrErr);
1517  else
1518  return ProtocolOrErr.takeError();
1519 
1520  }
1521 
1522  return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs,
1523  Protocols,
1524  T->isKindOfTypeAsWritten());
1525 }
1526 
1529  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1530  if (!ToPointeeTypeOrErr)
1531  return ToPointeeTypeOrErr.takeError();
1532 
1533  return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
1534 }
1535 
1536 //----------------------------------------------------------------------------
1537 // Import Declarations
1538 //----------------------------------------------------------------------------
1540  NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
1541  DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
1542  // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1543  // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1544  DeclContext *OrigDC = D->getDeclContext();
1545  FunctionDecl *FunDecl;
1546  if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
1547  FunDecl->hasBody()) {
1548  auto getLeafPointeeType = [](const Type *T) {
1549  while (T->isPointerType() || T->isArrayType()) {
1550  T = T->getPointeeOrArrayElementType();
1551  }
1552  return T;
1553  };
1554  for (const ParmVarDecl *P : FunDecl->parameters()) {
1555  const Type *LeafT =
1556  getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1557  auto *RT = dyn_cast<RecordType>(LeafT);
1558  if (RT && RT->getDecl() == D) {
1559  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1560  << D->getDeclKindName();
1561  return make_error<ImportError>(ImportError::UnsupportedConstruct);
1562  }
1563  }
1564  }
1565 
1566  // Import the context of this declaration.
1567  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
1568  return Err;
1569 
1570  // Import the name of this declaration.
1571  if (Error Err = importInto(Name, D->getDeclName()))
1572  return Err;
1573 
1574  // Import the location of this declaration.
1575  if (Error Err = importInto(Loc, D->getLocation()))
1576  return Err;
1577 
1578  ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1579  if (ToD)
1580  if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1581  return Err;
1582 
1583  return Error::success();
1584 }
1585 
1587  if (!FromD)
1588  return Error::success();
1589 
1590  if (!ToD)
1591  if (Error Err = importInto(ToD, FromD))
1592  return Err;
1593 
1594  if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1595  if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) {
1596  if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
1597  !ToRecord->getDefinition()) {
1598  if (Error Err = ImportDefinition(FromRecord, ToRecord))
1599  return Err;
1600  }
1601  }
1602  return Error::success();
1603  }
1604 
1605  if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1606  if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) {
1607  if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1608  if (Error Err = ImportDefinition(FromEnum, ToEnum))
1609  return Err;
1610  }
1611  }
1612  return Error::success();
1613  }
1614 
1615  return Error::success();
1616 }
1617 
1618 Error
1620  const DeclarationNameInfo &From, DeclarationNameInfo& To) {
1621  // NOTE: To.Name and To.Loc are already imported.
1622  // We only have to import To.LocInfo.
1623  switch (To.getName().getNameKind()) {
1630  return Error::success();
1631 
1633  if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange()))
1634  To.setCXXOperatorNameRange(*ToRangeOrErr);
1635  else
1636  return ToRangeOrErr.takeError();
1637  return Error::success();
1638  }
1640  if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc()))
1641  To.setCXXLiteralOperatorNameLoc(*LocOrErr);
1642  else
1643  return LocOrErr.takeError();
1644  return Error::success();
1645  }
1649  if (auto ToTInfoOrErr = import(From.getNamedTypeInfo()))
1650  To.setNamedTypeInfo(*ToTInfoOrErr);
1651  else
1652  return ToTInfoOrErr.takeError();
1653  return Error::success();
1654  }
1655  }
1656  llvm_unreachable("Unknown name kind.");
1657 }
1658 
1659 Error
1661  if (Importer.isMinimalImport() && !ForceImport) {
1662  auto ToDCOrErr = Importer.ImportContext(FromDC);
1663  return ToDCOrErr.takeError();
1664  }
1665 
1666  // We use strict error handling in case of records and enums, but not
1667  // with e.g. namespaces.
1668  //
1669  // FIXME Clients of the ASTImporter should be able to choose an
1670  // appropriate error handling strategy for their needs. For instance,
1671  // they may not want to mark an entire namespace as erroneous merely
1672  // because there is an ODR error with two typedefs. As another example,
1673  // the client may allow EnumConstantDecls with same names but with
1674  // different values in two distinct translation units.
1675  bool AccumulateChildErrors = isa<TagDecl>(FromDC);
1676 
1677  Error ChildErrors = Error::success();
1678  for (auto *From : FromDC->decls()) {
1679  ExpectedDecl ImportedOrErr = import(From);
1680  if (!ImportedOrErr) {
1681  if (AccumulateChildErrors)
1682  ChildErrors =
1683  joinErrors(std::move(ChildErrors), ImportedOrErr.takeError());
1684  else
1685  consumeError(ImportedOrErr.takeError());
1686  }
1687  }
1688 
1689  // We reorder declarations in RecordDecls because they may have another order
1690  // in the "to" context than they have in the "from" context. This may happen
1691  // e.g when we import a class like this:
1692  // struct declToImport {
1693  // int a = c + b;
1694  // int b = 1;
1695  // int c = 2;
1696  // };
1697  // During the import of `a` we import first the dependencies in sequence,
1698  // thus the order would be `c`, `b`, `a`. We will get the normal order by
1699  // first removing the already imported members and then adding them in the
1700  // order as they apper in the "from" context.
1701  //
1702  // Keeping field order is vital because it determines structure layout.
1703  //
1704  // Here and below, we cannot call field_begin() method and its callers on
1705  // ToDC if it has an external storage. Calling field_begin() will
1706  // automatically load all the fields by calling
1707  // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would
1708  // call ASTImporter::Import(). This is because the ExternalASTSource
1709  // interface in LLDB is implemented by the means of the ASTImporter. However,
1710  // calling an import at this point would result in an uncontrolled import, we
1711  // must avoid that.
1712  const auto *FromRD = dyn_cast<RecordDecl>(FromDC);
1713  if (!FromRD)
1714  return ChildErrors;
1715 
1716  auto ToDCOrErr = Importer.ImportContext(FromDC);
1717  if (!ToDCOrErr) {
1718  consumeError(std::move(ChildErrors));
1719  return ToDCOrErr.takeError();
1720  }
1721 
1722  DeclContext *ToDC = *ToDCOrErr;
1723  // Remove all declarations, which may be in wrong order in the
1724  // lexical DeclContext and then add them in the proper order.
1725  for (auto *D : FromRD->decls()) {
1726  if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<FriendDecl>(D)) {
1727  assert(D && "DC contains a null decl");
1728  Decl *ToD = Importer.GetAlreadyImportedOrNull(D);
1729  // Remove only the decls which we successfully imported.
1730  if (ToD) {
1731  assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD));
1732  // Remove the decl from its wrong place in the linked list.
1733  ToDC->removeDecl(ToD);
1734  // Add the decl to the end of the linked list.
1735  // This time it will be at the proper place because the enclosing for
1736  // loop iterates in the original (good) order of the decls.
1737  ToDC->addDeclInternal(ToD);
1738  }
1739  }
1740  }
1741 
1742  return ChildErrors;
1743 }
1744 
1746  Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
1747  auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext());
1748  if (!ToDCOrErr)
1749  return ToDCOrErr.takeError();
1750  ToDC = *ToDCOrErr;
1751 
1752  if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
1753  auto ToLexicalDCOrErr = Importer.ImportContext(
1754  FromD->getLexicalDeclContext());
1755  if (!ToLexicalDCOrErr)
1756  return ToLexicalDCOrErr.takeError();
1757  ToLexicalDC = *ToLexicalDCOrErr;
1758  } else
1759  ToLexicalDC = ToDC;
1760 
1761  return Error::success();
1762 }
1763 
1765  const CXXRecordDecl *From, CXXRecordDecl *To) {
1766  assert(From->isCompleteDefinition() && To->getDefinition() == To &&
1767  "Import implicit methods to or from non-definition");
1768 
1769  for (CXXMethodDecl *FromM : From->methods())
1770  if (FromM->isImplicit()) {
1771  Expected<CXXMethodDecl *> ToMOrErr = import(FromM);
1772  if (!ToMOrErr)
1773  return ToMOrErr.takeError();
1774  }
1775 
1776  return Error::success();
1777 }
1778 
1780  ASTImporter &Importer) {
1781  if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
1782  if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef))
1783  To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr));
1784  else
1785  return ToTypedefOrErr.takeError();
1786  }
1787  return Error::success();
1788 }
1789 
1792  auto DefinitionCompleter = [To]() {
1793  // There are cases in LLDB when we first import a class without its
1794  // members. The class will have DefinitionData, but no members. Then,
1795  // importDefinition is called from LLDB, which tries to get the members, so
1796  // when we get here, the class already has the DefinitionData set, so we
1797  // must unset the CompleteDefinition here to be able to complete again the
1798  // definition.
1799  To->setCompleteDefinition(false);
1800  To->completeDefinition();
1801  };
1802 
1803  if (To->getDefinition() || To->isBeingDefined()) {
1804  if (Kind == IDK_Everything ||
1805  // In case of lambdas, the class already has a definition ptr set, but
1806  // the contained decls are not imported yet. Also, isBeingDefined was
1807  // set in CXXRecordDecl::CreateLambda. We must import the contained
1808  // decls here and finish the definition.
1809  (To->isLambda() && shouldForceImportDeclContext(Kind))) {
1810  Error Result = ImportDeclContext(From, /*ForceImport=*/true);
1811  // Finish the definition of the lambda, set isBeingDefined to false.
1812  if (To->isLambda())
1813  DefinitionCompleter();
1814  return Result;
1815  }
1816 
1817  return Error::success();
1818  }
1819 
1820  To->startDefinition();
1821  // Complete the definition even if error is returned.
1822  // The RecordDecl may be already part of the AST so it is better to
1823  // have it in complete state even if something is wrong with it.
1824  auto DefinitionCompleterScopeExit =
1825  llvm::make_scope_exit(DefinitionCompleter);
1826 
1827  if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
1828  return Err;
1829 
1830  // Add base classes.
1831  auto *ToCXX = dyn_cast<CXXRecordDecl>(To);
1832  auto *FromCXX = dyn_cast<CXXRecordDecl>(From);
1833  if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
1834 
1835  struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1836  struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
1837  ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
1838  ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
1839  ToData.Aggregate = FromData.Aggregate;
1840  ToData.PlainOldData = FromData.PlainOldData;
1841  ToData.Empty = FromData.Empty;
1842  ToData.Polymorphic = FromData.Polymorphic;
1843  ToData.Abstract = FromData.Abstract;
1844  ToData.IsStandardLayout = FromData.IsStandardLayout;
1845  ToData.IsCXX11StandardLayout = FromData.IsCXX11StandardLayout;
1846  ToData.HasBasesWithFields = FromData.HasBasesWithFields;
1847  ToData.HasBasesWithNonStaticDataMembers =
1848  FromData.HasBasesWithNonStaticDataMembers;
1849  ToData.HasPrivateFields = FromData.HasPrivateFields;
1850  ToData.HasProtectedFields = FromData.HasProtectedFields;
1851  ToData.HasPublicFields = FromData.HasPublicFields;
1852  ToData.HasMutableFields = FromData.HasMutableFields;
1853  ToData.HasVariantMembers = FromData.HasVariantMembers;
1854  ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
1855  ToData.HasInClassInitializer = FromData.HasInClassInitializer;
1856  ToData.HasUninitializedReferenceMember
1857  = FromData.HasUninitializedReferenceMember;
1858  ToData.HasUninitializedFields = FromData.HasUninitializedFields;
1859  ToData.HasInheritedConstructor = FromData.HasInheritedConstructor;
1860  ToData.HasInheritedAssignment = FromData.HasInheritedAssignment;
1861  ToData.NeedOverloadResolutionForCopyConstructor
1862  = FromData.NeedOverloadResolutionForCopyConstructor;
1863  ToData.NeedOverloadResolutionForMoveConstructor
1864  = FromData.NeedOverloadResolutionForMoveConstructor;
1865  ToData.NeedOverloadResolutionForMoveAssignment
1866  = FromData.NeedOverloadResolutionForMoveAssignment;
1867  ToData.NeedOverloadResolutionForDestructor
1868  = FromData.NeedOverloadResolutionForDestructor;
1869  ToData.DefaultedCopyConstructorIsDeleted
1870  = FromData.DefaultedCopyConstructorIsDeleted;
1871  ToData.DefaultedMoveConstructorIsDeleted
1872  = FromData.DefaultedMoveConstructorIsDeleted;
1873  ToData.DefaultedMoveAssignmentIsDeleted
1874  = FromData.DefaultedMoveAssignmentIsDeleted;
1875  ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
1876  ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
1877  ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
1878  ToData.HasConstexprNonCopyMoveConstructor
1879  = FromData.HasConstexprNonCopyMoveConstructor;
1880  ToData.HasDefaultedDefaultConstructor
1881  = FromData.HasDefaultedDefaultConstructor;
1882  ToData.DefaultedDefaultConstructorIsConstexpr
1883  = FromData.DefaultedDefaultConstructorIsConstexpr;
1884  ToData.HasConstexprDefaultConstructor
1885  = FromData.HasConstexprDefaultConstructor;
1886  ToData.HasNonLiteralTypeFieldsOrBases
1887  = FromData.HasNonLiteralTypeFieldsOrBases;
1888  // ComputedVisibleConversions not imported.
1889  ToData.UserProvidedDefaultConstructor
1890  = FromData.UserProvidedDefaultConstructor;
1891  ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
1892  ToData.ImplicitCopyConstructorCanHaveConstParamForVBase
1893  = FromData.ImplicitCopyConstructorCanHaveConstParamForVBase;
1894  ToData.ImplicitCopyConstructorCanHaveConstParamForNonVBase
1895  = FromData.ImplicitCopyConstructorCanHaveConstParamForNonVBase;
1896  ToData.ImplicitCopyAssignmentHasConstParam
1897  = FromData.ImplicitCopyAssignmentHasConstParam;
1898  ToData.HasDeclaredCopyConstructorWithConstParam
1899  = FromData.HasDeclaredCopyConstructorWithConstParam;
1900  ToData.HasDeclaredCopyAssignmentWithConstParam
1901  = FromData.HasDeclaredCopyAssignmentWithConstParam;
1902 
1903  // Copy over the data stored in RecordDeclBits
1904  ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
1905 
1907  for (const auto &Base1 : FromCXX->bases()) {
1908  ExpectedType TyOrErr = import(Base1.getType());
1909  if (!TyOrErr)
1910  return TyOrErr.takeError();
1911 
1912  SourceLocation EllipsisLoc;
1913  if (Base1.isPackExpansion()) {
1914  if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc()))
1915  EllipsisLoc = *LocOrErr;
1916  else
1917  return LocOrErr.takeError();
1918  }
1919 
1920  // Ensure that we have a definition for the base.
1921  if (Error Err =
1922  ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
1923  return Err;
1924 
1925  auto RangeOrErr = import(Base1.getSourceRange());
1926  if (!RangeOrErr)
1927  return RangeOrErr.takeError();
1928 
1929  auto TSIOrErr = import(Base1.getTypeSourceInfo());
1930  if (!TSIOrErr)
1931  return TSIOrErr.takeError();
1932 
1933  Bases.push_back(
1934  new (Importer.getToContext()) CXXBaseSpecifier(
1935  *RangeOrErr,
1936  Base1.isVirtual(),
1937  Base1.isBaseOfClass(),
1938  Base1.getAccessSpecifierAsWritten(),
1939  *TSIOrErr,
1940  EllipsisLoc));
1941  }
1942  if (!Bases.empty())
1943  ToCXX->setBases(Bases.data(), Bases.size());
1944  }
1945 
1946  if (shouldForceImportDeclContext(Kind))
1947  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
1948  return Err;
1949 
1950  return Error::success();
1951 }
1952 
1954  if (To->getAnyInitializer())
1955  return Error::success();
1956 
1957  Expr *FromInit = From->getInit();
1958  if (!FromInit)
1959  return Error::success();
1960 
1961  ExpectedExpr ToInitOrErr = import(FromInit);
1962  if (!ToInitOrErr)
1963  return ToInitOrErr.takeError();
1964 
1965  To->setInit(*ToInitOrErr);
1966  if (From->isInitKnownICE()) {
1967  EvaluatedStmt *Eval = To->ensureEvaluatedStmt();
1968  Eval->CheckedICE = true;
1969  Eval->IsICE = From->isInitICE();
1970  }
1971 
1972  // FIXME: Other bits to merge?
1973  return Error::success();
1974 }
1975 
1978  if (To->getDefinition() || To->isBeingDefined()) {
1979  if (Kind == IDK_Everything)
1980  return ImportDeclContext(From, /*ForceImport=*/true);
1981  return Error::success();
1982  }
1983 
1984  To->startDefinition();
1985 
1986  if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
1987  return Err;
1988 
1989  ExpectedType ToTypeOrErr =
1990  import(Importer.getFromContext().getTypeDeclType(From));
1991  if (!ToTypeOrErr)
1992  return ToTypeOrErr.takeError();
1993 
1994  ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType());
1995  if (!ToPromotionTypeOrErr)
1996  return ToPromotionTypeOrErr.takeError();
1997 
1998  if (shouldForceImportDeclContext(Kind))
1999  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2000  return Err;
2001 
2002  // FIXME: we might need to merge the number of positive or negative bits
2003  // if the enumerator lists don't match.
2004  To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr,
2005  From->getNumPositiveBits(),
2006  From->getNumNegativeBits());
2007  return Error::success();
2008 }
2009 
2011  const TemplateArgument *FromArgs, unsigned NumFromArgs,
2013  for (unsigned I = 0; I != NumFromArgs; ++I) {
2014  if (auto ToOrErr = import(FromArgs[I]))
2015  ToArgs.push_back(*ToOrErr);
2016  else
2017  return ToOrErr.takeError();
2018  }
2019 
2020  return Error::success();
2021 }
2022 
2023 // FIXME: Do not forget to remove this and use only 'import'.
2026  return import(From);
2027 }
2028 
2029 template <typename InContainerTy>
2031  const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
2032  for (const auto &FromLoc : Container) {
2033  if (auto ToLocOrErr = import(FromLoc))
2034  ToTAInfo.addArgument(*ToLocOrErr);
2035  else
2036  return ToLocOrErr.takeError();
2037  }
2038  return Error::success();
2039 }
2040 
2045 }
2046 
2047 bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) {
2049  Importer.getFromContext(), Importer.getToContext(),
2050  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2051  false, Complain);
2052  return Ctx.IsEquivalent(From, To);
2053 }
2054 
2056  RecordDecl *ToRecord, bool Complain) {
2057  // Eliminate a potential failure point where we attempt to re-import
2058  // something we're trying to import while completing ToRecord.
2059  Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2060  if (ToOrigin) {
2061  auto *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2062  if (ToOriginRecord)
2063  ToRecord = ToOriginRecord;
2064  }
2065 
2066  StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2067  ToRecord->getASTContext(),
2068  Importer.getNonEquivalentDecls(),
2069  getStructuralEquivalenceKind(Importer),
2070  false, Complain);
2071  return Ctx.IsEquivalent(FromRecord, ToRecord);
2072 }
2073 
2075  bool Complain) {
2077  Importer.getFromContext(), Importer.getToContext(),
2078  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2079  false, Complain);
2080  return Ctx.IsEquivalent(FromVar, ToVar);
2081 }
2082 
2084  // Eliminate a potential failure point where we attempt to re-import
2085  // something we're trying to import while completing ToEnum.
2086  if (Decl *ToOrigin = Importer.GetOriginalDecl(ToEnum))
2087  if (auto *ToOriginEnum = dyn_cast<EnumDecl>(ToOrigin))
2088  ToEnum = ToOriginEnum;
2089 
2091  Importer.getFromContext(), Importer.getToContext(),
2092  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer));
2093  return Ctx.IsEquivalent(FromEnum, ToEnum);
2094 }
2095 
2097  FunctionTemplateDecl *To) {
2099  Importer.getFromContext(), Importer.getToContext(),
2100  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2101  false, false);
2102  return Ctx.IsEquivalent(From, To);
2103 }
2104 
2107  Importer.getFromContext(), Importer.getToContext(),
2108  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2109  false, false);
2110  return Ctx.IsEquivalent(From, To);
2111 }
2112 
2114  EnumConstantDecl *ToEC) {
2115  const llvm::APSInt &FromVal = FromEC->getInitVal();
2116  const llvm::APSInt &ToVal = ToEC->getInitVal();
2117 
2118  return FromVal.isSigned() == ToVal.isSigned() &&
2119  FromVal.getBitWidth() == ToVal.getBitWidth() &&
2120  FromVal == ToVal;
2121 }
2122 
2124  ClassTemplateDecl *To) {
2125  StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2126  Importer.getToContext(),
2127  Importer.getNonEquivalentDecls(),
2128  getStructuralEquivalenceKind(Importer));
2129  return Ctx.IsEquivalent(From, To);
2130 }
2131 
2133  VarTemplateDecl *To) {
2134  StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2135  Importer.getToContext(),
2136  Importer.getNonEquivalentDecls(),
2137  getStructuralEquivalenceKind(Importer));
2138  return Ctx.IsEquivalent(From, To);
2139 }
2140 
2142  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2143  << D->getDeclKindName();
2144  return make_error<ImportError>(ImportError::UnsupportedConstruct);
2145 }
2146 
2148  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2149  << D->getDeclKindName();
2150  return make_error<ImportError>(ImportError::UnsupportedConstruct);
2151 }
2152 
2154  // Import the context of this declaration.
2155  DeclContext *DC, *LexicalDC;
2156  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
2157  return std::move(Err);
2158 
2159  // Import the location of this declaration.
2160  ExpectedSLoc LocOrErr = import(D->getLocation());
2161  if (!LocOrErr)
2162  return LocOrErr.takeError();
2163 
2164  EmptyDecl *ToD;
2165  if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr))
2166  return ToD;
2167 
2168  ToD->setLexicalDeclContext(LexicalDC);
2169  LexicalDC->addDeclInternal(ToD);
2170  return ToD;
2171 }
2172 
2174  TranslationUnitDecl *ToD =
2175  Importer.getToContext().getTranslationUnitDecl();
2176 
2177  Importer.MapImported(D, ToD);
2178 
2179  return ToD;
2180 }
2181 
2183  ExpectedSLoc LocOrErr = import(D->getLocation());
2184  if (!LocOrErr)
2185  return LocOrErr.takeError();
2186  auto ColonLocOrErr = import(D->getColonLoc());
2187  if (!ColonLocOrErr)
2188  return ColonLocOrErr.takeError();
2189 
2190  // Import the context of this declaration.
2191  auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2192  if (!DCOrErr)
2193  return DCOrErr.takeError();
2194  DeclContext *DC = *DCOrErr;
2195 
2196  AccessSpecDecl *ToD;
2197  if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
2198  DC, *LocOrErr, *ColonLocOrErr))
2199  return ToD;
2200 
2201  // Lexical DeclContext and Semantic DeclContext
2202  // is always the same for the accessSpec.
2203  ToD->setLexicalDeclContext(DC);
2204  DC->addDeclInternal(ToD);
2205 
2206  return ToD;
2207 }
2208 
2210  auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2211  if (!DCOrErr)
2212  return DCOrErr.takeError();
2213  DeclContext *DC = *DCOrErr;
2214  DeclContext *LexicalDC = DC;
2215 
2216  SourceLocation ToLocation, ToRParenLoc;
2217  Expr *ToAssertExpr;
2218  StringLiteral *ToMessage;
2219  if (auto Imp = importSeq(
2220  D->getLocation(), D->getAssertExpr(), D->getMessage(), D->getRParenLoc()))
2221  std::tie(ToLocation, ToAssertExpr, ToMessage, ToRParenLoc) = *Imp;
2222  else
2223  return Imp.takeError();
2224 
2225  StaticAssertDecl *ToD;
2226  if (GetImportedOrCreateDecl(
2227  ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
2228  ToRParenLoc, D->isFailed()))
2229  return ToD;
2230 
2231  ToD->setLexicalDeclContext(LexicalDC);
2232  LexicalDC->addDeclInternal(ToD);
2233  return ToD;
2234 }
2235 
2237  // Import the major distinguishing characteristics of this namespace.
2238  DeclContext *DC, *LexicalDC;
2239  DeclarationName Name;
2240  SourceLocation Loc;
2241  NamedDecl *ToD;
2242  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2243  return std::move(Err);
2244  if (ToD)
2245  return ToD;
2246 
2247  NamespaceDecl *MergeWithNamespace = nullptr;
2248  if (!Name) {
2249  // This is an anonymous namespace. Adopt an existing anonymous
2250  // namespace if we can.
2251  // FIXME: Not testable.
2252  if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2253  MergeWithNamespace = TU->getAnonymousNamespace();
2254  else
2255  MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2256  } else {
2257  SmallVector<NamedDecl *, 4> ConflictingDecls;
2258  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2259  for (auto *FoundDecl : FoundDecls) {
2261  continue;
2262 
2263  if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
2264  MergeWithNamespace = FoundNS;
2265  ConflictingDecls.clear();
2266  break;
2267  }
2268 
2269  ConflictingDecls.push_back(FoundDecl);
2270  }
2271 
2272  if (!ConflictingDecls.empty()) {
2273  ExpectedName NameOrErr = Importer.HandleNameConflict(
2274  Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(),
2275  ConflictingDecls.size());
2276  if (NameOrErr)
2277  Name = NameOrErr.get();
2278  else
2279  return NameOrErr.takeError();
2280  }
2281  }
2282 
2283  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2284  if (!BeginLocOrErr)
2285  return BeginLocOrErr.takeError();
2286 
2287  // Create the "to" namespace, if needed.
2288  NamespaceDecl *ToNamespace = MergeWithNamespace;
2289  if (!ToNamespace) {
2290  if (GetImportedOrCreateDecl(
2291  ToNamespace, D, Importer.getToContext(), DC, D->isInline(),
2292  *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2293  /*PrevDecl=*/nullptr))
2294  return ToNamespace;
2295  ToNamespace->setLexicalDeclContext(LexicalDC);
2296  LexicalDC->addDeclInternal(ToNamespace);
2297 
2298  // If this is an anonymous namespace, register it as the anonymous
2299  // namespace within its context.
2300  if (!Name) {
2301  if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2302  TU->setAnonymousNamespace(ToNamespace);
2303  else
2304  cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2305  }
2306  }
2307  Importer.MapImported(D, ToNamespace);
2308 
2309  if (Error Err = ImportDeclContext(D))
2310  return std::move(Err);
2311 
2312  return ToNamespace;
2313 }
2314 
2316  // Import the major distinguishing characteristics of this namespace.
2317  DeclContext *DC, *LexicalDC;
2318  DeclarationName Name;
2319  SourceLocation Loc;
2320  NamedDecl *LookupD;
2321  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
2322  return std::move(Err);
2323  if (LookupD)
2324  return LookupD;
2325 
2326  // NOTE: No conflict resolution is done for namespace aliases now.
2327 
2328  SourceLocation ToNamespaceLoc, ToAliasLoc, ToTargetNameLoc;
2329  NestedNameSpecifierLoc ToQualifierLoc;
2330  NamespaceDecl *ToNamespace;
2331  if (auto Imp = importSeq(
2332  D->getNamespaceLoc(), D->getAliasLoc(), D->getQualifierLoc(),
2333  D->getTargetNameLoc(), D->getNamespace()))
2334  std::tie(
2335  ToNamespaceLoc, ToAliasLoc, ToQualifierLoc, ToTargetNameLoc,
2336  ToNamespace) = *Imp;
2337  else
2338  return Imp.takeError();
2339  IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
2340 
2341  NamespaceAliasDecl *ToD;
2342  if (GetImportedOrCreateDecl(
2343  ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc,
2344  ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace))
2345  return ToD;
2346 
2347  ToD->setLexicalDeclContext(LexicalDC);
2348  LexicalDC->addDeclInternal(ToD);
2349 
2350  return ToD;
2351 }
2352 
2355  // Import the major distinguishing characteristics of this typedef.
2356  DeclContext *DC, *LexicalDC;
2357  DeclarationName Name;
2358  SourceLocation Loc;
2359  NamedDecl *ToD;
2360  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2361  return std::move(Err);
2362  if (ToD)
2363  return ToD;
2364 
2365  // If this typedef is not in block scope, determine whether we've
2366  // seen a typedef with the same name (that we can merge with) or any
2367  // other entity by that name (which name lookup could conflict with).
2368  // Note: Repeated typedefs are not valid in C99:
2369  // 'typedef int T; typedef int T;' is invalid
2370  // We do not care about this now.
2371  if (!DC->isFunctionOrMethod()) {
2372  SmallVector<NamedDecl *, 4> ConflictingDecls;
2373  unsigned IDNS = Decl::IDNS_Ordinary;
2374  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2375  for (auto *FoundDecl : FoundDecls) {
2376  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2377  continue;
2378  if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2379  if (!hasSameVisibilityContext(FoundTypedef, D))
2380  continue;
2381 
2382  QualType FromUT = D->getUnderlyingType();
2383  QualType FoundUT = FoundTypedef->getUnderlyingType();
2384  if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
2385  // If the "From" context has a complete underlying type but we
2386  // already have a complete underlying type then return with that.
2387  if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
2388  return Importer.MapImported(D, FoundTypedef);
2389  // FIXME Handle redecl chain. When you do that make consistent changes
2390  // in ASTImporterLookupTable too.
2391  } else {
2392  ConflictingDecls.push_back(FoundDecl);
2393  }
2394  }
2395  }
2396 
2397  if (!ConflictingDecls.empty()) {
2398  ExpectedName NameOrErr = Importer.HandleNameConflict(
2399  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2400  if (NameOrErr)
2401  Name = NameOrErr.get();
2402  else
2403  return NameOrErr.takeError();
2404  }
2405  }
2406 
2407  QualType ToUnderlyingType;
2408  TypeSourceInfo *ToTypeSourceInfo;
2409  SourceLocation ToBeginLoc;
2410  if (auto Imp = importSeq(
2412  std::tie(ToUnderlyingType, ToTypeSourceInfo, ToBeginLoc) = *Imp;
2413  else
2414  return Imp.takeError();
2415 
2416  // Create the new typedef node.
2417  // FIXME: ToUnderlyingType is not used.
2418  TypedefNameDecl *ToTypedef;
2419  if (IsAlias) {
2420  if (GetImportedOrCreateDecl<TypeAliasDecl>(
2421  ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2422  Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2423  return ToTypedef;
2424  } else if (GetImportedOrCreateDecl<TypedefDecl>(
2425  ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2426  Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2427  return ToTypedef;
2428 
2429  ToTypedef->setAccess(D->getAccess());
2430  ToTypedef->setLexicalDeclContext(LexicalDC);
2431 
2432  // Templated declarations should not appear in DeclContext.
2433  TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
2434  if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
2435  LexicalDC->addDeclInternal(ToTypedef);
2436 
2437  return ToTypedef;
2438 }
2439 
2441  return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2442 }
2443 
2445  return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2446 }
2447 
2450  // Import the major distinguishing characteristics of this typedef.
2451  DeclContext *DC, *LexicalDC;
2452  DeclarationName Name;
2453  SourceLocation Loc;
2454  NamedDecl *FoundD;
2455  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
2456  return std::move(Err);
2457  if (FoundD)
2458  return FoundD;
2459 
2460  // If this typedef is not in block scope, determine whether we've
2461  // seen a typedef with the same name (that we can merge with) or any
2462  // other entity by that name (which name lookup could conflict with).
2463  if (!DC->isFunctionOrMethod()) {
2464  SmallVector<NamedDecl *, 4> ConflictingDecls;
2465  unsigned IDNS = Decl::IDNS_Ordinary;
2466  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2467  for (auto *FoundDecl : FoundDecls) {
2468  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2469  continue;
2470  if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl))
2471  return Importer.MapImported(D, FoundAlias);
2472  ConflictingDecls.push_back(FoundDecl);
2473  }
2474 
2475  if (!ConflictingDecls.empty()) {
2476  ExpectedName NameOrErr = Importer.HandleNameConflict(
2477  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2478  if (NameOrErr)
2479  Name = NameOrErr.get();
2480  else
2481  return NameOrErr.takeError();
2482  }
2483  }
2484 
2485  TemplateParameterList *ToTemplateParameters;
2486  TypeAliasDecl *ToTemplatedDecl;
2487  if (auto Imp = importSeq(D->getTemplateParameters(), D->getTemplatedDecl()))
2488  std::tie(ToTemplateParameters, ToTemplatedDecl) = *Imp;
2489  else
2490  return Imp.takeError();
2491 
2492  TypeAliasTemplateDecl *ToAlias;
2493  if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2494  Name, ToTemplateParameters, ToTemplatedDecl))
2495  return ToAlias;
2496 
2497  ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
2498 
2499  ToAlias->setAccess(D->getAccess());
2500  ToAlias->setLexicalDeclContext(LexicalDC);
2501  LexicalDC->addDeclInternal(ToAlias);
2502  return ToAlias;
2503 }
2504 
2506  // Import the major distinguishing characteristics of this label.
2507  DeclContext *DC, *LexicalDC;
2508  DeclarationName Name;
2509  SourceLocation Loc;
2510  NamedDecl *ToD;
2511  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2512  return std::move(Err);
2513  if (ToD)
2514  return ToD;
2515 
2516  assert(LexicalDC->isFunctionOrMethod());
2517 
2518  LabelDecl *ToLabel;
2519  if (D->isGnuLocal()) {
2520  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2521  if (!BeginLocOrErr)
2522  return BeginLocOrErr.takeError();
2523  if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2524  Name.getAsIdentifierInfo(), *BeginLocOrErr))
2525  return ToLabel;
2526 
2527  } else {
2528  if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2529  Name.getAsIdentifierInfo()))
2530  return ToLabel;
2531 
2532  }
2533 
2534  Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt());
2535  if (!ToStmtOrErr)
2536  return ToStmtOrErr.takeError();
2537 
2538  ToLabel->setStmt(*ToStmtOrErr);
2539  ToLabel->setLexicalDeclContext(LexicalDC);
2540  LexicalDC->addDeclInternal(ToLabel);
2541  return ToLabel;
2542 }
2543 
2545  // Import the major distinguishing characteristics of this enum.
2546  DeclContext *DC, *LexicalDC;
2547  DeclarationName Name;
2548  SourceLocation Loc;
2549  NamedDecl *ToD;
2550  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2551  return std::move(Err);
2552  if (ToD)
2553  return ToD;
2554 
2555  // Figure out what enum name we're looking for.
2556  unsigned IDNS = Decl::IDNS_Tag;
2557  DeclarationName SearchName = Name;
2558  if (!SearchName && D->getTypedefNameForAnonDecl()) {
2559  if (Error Err = importInto(
2560  SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2561  return std::move(Err);
2562  IDNS = Decl::IDNS_Ordinary;
2563  } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2564  IDNS |= Decl::IDNS_Ordinary;
2565 
2566  // We may already have an enum of the same name; try to find and match it.
2567  if (!DC->isFunctionOrMethod() && SearchName) {
2568  SmallVector<NamedDecl *, 4> ConflictingDecls;
2569  auto FoundDecls =
2570  Importer.findDeclsInToCtx(DC, SearchName);
2571  for (auto *FoundDecl : FoundDecls) {
2572  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2573  continue;
2574 
2575  if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2576  if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2577  FoundDecl = Tag->getDecl();
2578  }
2579 
2580  if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) {
2581  if (!hasSameVisibilityContext(FoundEnum, D))
2582  continue;
2583  if (IsStructuralMatch(D, FoundEnum))
2584  return Importer.MapImported(D, FoundEnum);
2585  ConflictingDecls.push_back(FoundDecl);
2586  }
2587  }
2588 
2589  if (!ConflictingDecls.empty()) {
2590  ExpectedName NameOrErr = Importer.HandleNameConflict(
2591  SearchName, DC, IDNS, ConflictingDecls.data(),
2592  ConflictingDecls.size());
2593  if (NameOrErr)
2594  Name = NameOrErr.get();
2595  else
2596  return NameOrErr.takeError();
2597  }
2598  }
2599 
2600  SourceLocation ToBeginLoc;
2601  NestedNameSpecifierLoc ToQualifierLoc;
2602  QualType ToIntegerType;
2603  if (auto Imp = importSeq(
2604  D->getBeginLoc(), D->getQualifierLoc(), D->getIntegerType()))
2605  std::tie(ToBeginLoc, ToQualifierLoc, ToIntegerType) = *Imp;
2606  else
2607  return Imp.takeError();
2608 
2609  // Create the enum declaration.
2610  EnumDecl *D2;
2611  if (GetImportedOrCreateDecl(
2612  D2, D, Importer.getToContext(), DC, ToBeginLoc,
2613  Loc, Name.getAsIdentifierInfo(), nullptr, D->isScoped(),
2614  D->isScopedUsingClassTag(), D->isFixed()))
2615  return D2;
2616 
2617  D2->setQualifierInfo(ToQualifierLoc);
2618  D2->setIntegerType(ToIntegerType);
2619  D2->setAccess(D->getAccess());
2620  D2->setLexicalDeclContext(LexicalDC);
2621  LexicalDC->addDeclInternal(D2);
2622 
2623  // Import the definition
2624  if (D->isCompleteDefinition())
2625  if (Error Err = ImportDefinition(D, D2))
2626  return std::move(Err);
2627 
2628  return D2;
2629 }
2630 
2632  bool IsFriendTemplate = false;
2633  if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2634  IsFriendTemplate =
2635  DCXX->getDescribedClassTemplate() &&
2636  DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
2638  }
2639 
2640  // Import the major distinguishing characteristics of this record.
2641  DeclContext *DC, *LexicalDC;
2642  DeclarationName Name;
2643  SourceLocation Loc;
2644  NamedDecl *ToD;
2645  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2646  return std::move(Err);
2647  if (ToD)
2648  return ToD;
2649 
2650  // Figure out what structure name we're looking for.
2651  unsigned IDNS = Decl::IDNS_Tag;
2652  DeclarationName SearchName = Name;
2653  if (!SearchName && D->getTypedefNameForAnonDecl()) {
2654  if (Error Err = importInto(
2655  SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2656  return std::move(Err);
2657  IDNS = Decl::IDNS_Ordinary;
2658  } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2660 
2661  // We may already have a record of the same name; try to find and match it.
2662  RecordDecl *PrevDecl = nullptr;
2663  if (!DC->isFunctionOrMethod() && !D->isLambda()) {
2664  SmallVector<NamedDecl *, 4> ConflictingDecls;
2665  auto FoundDecls =
2666  Importer.findDeclsInToCtx(DC, SearchName);
2667  if (!FoundDecls.empty()) {
2668  // We're going to have to compare D against potentially conflicting Decls,
2669  // so complete it.
2672  }
2673 
2674  for (auto *FoundDecl : FoundDecls) {
2675  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2676  continue;
2677 
2678  Decl *Found = FoundDecl;
2679  if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2680  if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2681  Found = Tag->getDecl();
2682  }
2683 
2684  if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2685  // Do not emit false positive diagnostic in case of unnamed
2686  // struct/union and in case of anonymous structs. Would be false
2687  // because there may be several anonymous/unnamed structs in a class.
2688  // E.g. these are both valid:
2689  // struct A { // unnamed structs
2690  // struct { struct A *next; } entry0;
2691  // struct { struct A *next; } entry1;
2692  // };
2693  // struct X { struct { int a; }; struct { int b; }; }; // anon structs
2694  if (!SearchName)
2695  if (!IsStructuralMatch(D, FoundRecord, false))
2696  continue;
2697 
2698  if (!hasSameVisibilityContext(FoundRecord, D))
2699  continue;
2700 
2701  if (IsStructuralMatch(D, FoundRecord)) {
2702  RecordDecl *FoundDef = FoundRecord->getDefinition();
2703  if (D->isThisDeclarationADefinition() && FoundDef) {
2704  // FIXME: Structural equivalence check should check for same
2705  // user-defined methods.
2706  Importer.MapImported(D, FoundDef);
2707  if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2708  auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
2709  assert(FoundCXX && "Record type mismatch");
2710 
2711  if (!Importer.isMinimalImport())
2712  // FoundDef may not have every implicit method that D has
2713  // because implicit methods are created only if they are used.
2714  if (Error Err = ImportImplicitMethods(DCXX, FoundCXX))
2715  return std::move(Err);
2716  }
2717  }
2718  PrevDecl = FoundRecord->getMostRecentDecl();
2719  break;
2720  }
2721  ConflictingDecls.push_back(FoundDecl);
2722  } // kind is RecordDecl
2723  } // for
2724 
2725  if (!ConflictingDecls.empty() && SearchName) {
2726  ExpectedName NameOrErr = Importer.HandleNameConflict(
2727  SearchName, DC, IDNS, ConflictingDecls.data(),
2728  ConflictingDecls.size());
2729  if (NameOrErr)
2730  Name = NameOrErr.get();
2731  else
2732  return NameOrErr.takeError();
2733  }
2734  }
2735 
2736  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2737  if (!BeginLocOrErr)
2738  return BeginLocOrErr.takeError();
2739 
2740  // Create the record declaration.
2741  RecordDecl *D2 = nullptr;
2742  CXXRecordDecl *D2CXX = nullptr;
2743  if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2744  if (DCXX->isLambda()) {
2745  auto TInfoOrErr = import(DCXX->getLambdaTypeInfo());
2746  if (!TInfoOrErr)
2747  return TInfoOrErr.takeError();
2748  if (GetImportedOrCreateSpecialDecl(
2749  D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
2750  DC, *TInfoOrErr, Loc, DCXX->isDependentLambda(),
2751  DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
2752  return D2CXX;
2753  ExpectedDecl CDeclOrErr = import(DCXX->getLambdaContextDecl());
2754  if (!CDeclOrErr)
2755  return CDeclOrErr.takeError();
2756  D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), *CDeclOrErr);
2757  } else if (DCXX->isInjectedClassName()) {
2758  // We have to be careful to do a similar dance to the one in
2759  // Sema::ActOnStartCXXMemberDeclarations
2760  const bool DelayTypeCreation = true;
2761  if (GetImportedOrCreateDecl(
2762  D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
2763  *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2764  cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation))
2765  return D2CXX;
2766  Importer.getToContext().getTypeDeclType(
2767  D2CXX, dyn_cast<CXXRecordDecl>(DC));
2768  } else {
2769  if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
2770  D->getTagKind(), DC, *BeginLocOrErr, Loc,
2771  Name.getAsIdentifierInfo(),
2772  cast_or_null<CXXRecordDecl>(PrevDecl)))
2773  return D2CXX;
2774  }
2775 
2776  D2 = D2CXX;
2777  D2->setAccess(D->getAccess());
2778  D2->setLexicalDeclContext(LexicalDC);
2779  if (!DCXX->getDescribedClassTemplate() || DCXX->isImplicit())
2780  LexicalDC->addDeclInternal(D2);
2781 
2782  if (LexicalDC != DC && D->isInIdentifierNamespace(Decl::IDNS_TagFriend))
2783  DC->makeDeclVisibleInContext(D2);
2784 
2785  if (ClassTemplateDecl *FromDescribed =
2786  DCXX->getDescribedClassTemplate()) {
2787  ClassTemplateDecl *ToDescribed;
2788  if (Error Err = importInto(ToDescribed, FromDescribed))
2789  return std::move(Err);
2790  D2CXX->setDescribedClassTemplate(ToDescribed);
2791  if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
2792  // In a record describing a template the type should be an
2793  // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
2794  // previously set type to the correct value here (ToDescribed is not
2795  // available at record create).
2796  // FIXME: The previous type is cleared but not removed from
2797  // ASTContext's internal storage.
2798  CXXRecordDecl *Injected = nullptr;
2799  for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
2800  auto *Record = dyn_cast<CXXRecordDecl>(Found);
2801  if (Record && Record->isInjectedClassName()) {
2802  Injected = Record;
2803  break;
2804  }
2805  }
2806  // Create an injected type for the whole redecl chain.
2807  SmallVector<Decl *, 2> Redecls =
2809  for (auto *R : Redecls) {
2810  auto *RI = cast<CXXRecordDecl>(R);
2811  RI->setTypeForDecl(nullptr);
2812  // Below we create a new injected type and assign that to the
2813  // canonical decl, subsequent declarations in the chain will reuse
2814  // that type.
2815  Importer.getToContext().getInjectedClassNameType(
2816  RI, ToDescribed->getInjectedClassNameSpecialization());
2817  }
2818  // Set the new type for the previous injected decl too.
2819  if (Injected) {
2820  Injected->setTypeForDecl(nullptr);
2821  Importer.getToContext().getTypeDeclType(Injected, D2CXX);
2822  }
2823  }
2824  } else if (MemberSpecializationInfo *MemberInfo =
2825  DCXX->getMemberSpecializationInfo()) {
2827  MemberInfo->getTemplateSpecializationKind();
2828  CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
2829 
2830  if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst))
2831  D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK);
2832  else
2833  return ToInstOrErr.takeError();
2834 
2835  if (ExpectedSLoc POIOrErr =
2836  import(MemberInfo->getPointOfInstantiation()))
2838  *POIOrErr);
2839  else
2840  return POIOrErr.takeError();
2841  }
2842 
2843  } else {
2844  if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
2845  D->getTagKind(), DC, *BeginLocOrErr, Loc,
2846  Name.getAsIdentifierInfo(), PrevDecl))
2847  return D2;
2848  D2->setLexicalDeclContext(LexicalDC);
2849  LexicalDC->addDeclInternal(D2);
2850  }
2851 
2852  if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
2853  D2->setQualifierInfo(*QualifierLocOrErr);
2854  else
2855  return QualifierLocOrErr.takeError();
2856 
2857  if (D->isAnonymousStructOrUnion())
2858  D2->setAnonymousStructOrUnion(true);
2859 
2860  if (D->isCompleteDefinition())
2861  if (Error Err = ImportDefinition(D, D2, IDK_Default))
2862  return std::move(Err);
2863 
2864  return D2;
2865 }
2866 
2868  // Import the major distinguishing characteristics of this enumerator.
2869  DeclContext *DC, *LexicalDC;
2870  DeclarationName Name;
2871  SourceLocation Loc;
2872  NamedDecl *ToD;
2873  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2874  return std::move(Err);
2875  if (ToD)
2876  return ToD;
2877 
2878  // Determine whether there are any other declarations with the same name and
2879  // in the same context.
2880  if (!LexicalDC->isFunctionOrMethod()) {
2881  SmallVector<NamedDecl *, 4> ConflictingDecls;
2882  unsigned IDNS = Decl::IDNS_Ordinary;
2883  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2884  for (auto *FoundDecl : FoundDecls) {
2885  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2886  continue;
2887 
2888  if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
2889  if (IsStructuralMatch(D, FoundEnumConstant))
2890  return Importer.MapImported(D, FoundEnumConstant);
2891  ConflictingDecls.push_back(FoundDecl);
2892  }
2893  }
2894 
2895  if (!ConflictingDecls.empty()) {
2896  ExpectedName NameOrErr = Importer.HandleNameConflict(
2897  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2898  if (NameOrErr)
2899  Name = NameOrErr.get();
2900  else
2901  return NameOrErr.takeError();
2902  }
2903  }
2904 
2905  ExpectedType TypeOrErr = import(D->getType());
2906  if (!TypeOrErr)
2907  return TypeOrErr.takeError();
2908 
2909  ExpectedExpr InitOrErr = import(D->getInitExpr());
2910  if (!InitOrErr)
2911  return InitOrErr.takeError();
2912 
2913  EnumConstantDecl *ToEnumerator;
2914  if (GetImportedOrCreateDecl(
2915  ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2916  Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal()))
2917  return ToEnumerator;
2918 
2919  ToEnumerator->setAccess(D->getAccess());
2920  ToEnumerator->setLexicalDeclContext(LexicalDC);
2921  LexicalDC->addDeclInternal(ToEnumerator);
2922  return ToEnumerator;
2923 }
2924 
2926  DeclaratorDecl *ToD) {
2927  unsigned int Num = FromD->getNumTemplateParameterLists();
2928  if (Num == 0)
2929  return Error::success();
2931  for (unsigned int I = 0; I < Num; ++I)
2932  if (Expected<TemplateParameterList *> ToTPListOrErr =
2933  import(FromD->getTemplateParameterList(I)))
2934  ToTPLists[I] = *ToTPListOrErr;
2935  else
2936  return ToTPListOrErr.takeError();
2937  ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists);
2938  return Error::success();
2939 }
2940 
2942  FunctionDecl *FromFD, FunctionDecl *ToFD) {
2943  switch (FromFD->getTemplatedKind()) {
2946  return Error::success();
2947 
2950 
2951  if (Expected<FunctionDecl *> InstFDOrErr =
2952  import(FromFD->getInstantiatedFromMemberFunction()))
2953  ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK);
2954  else
2955  return InstFDOrErr.takeError();
2956 
2957  if (ExpectedSLoc POIOrErr = import(
2960  else
2961  return POIOrErr.takeError();
2962 
2963  return Error::success();
2964  }
2965 
2967  auto FunctionAndArgsOrErr =
2968  ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
2969  if (!FunctionAndArgsOrErr)
2970  return FunctionAndArgsOrErr.takeError();
2971 
2973  Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr));
2974 
2975  auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
2976  TemplateArgumentListInfo ToTAInfo;
2977  const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
2978  if (FromTAArgsAsWritten)
2979  if (Error Err = ImportTemplateArgumentListInfo(
2980  *FromTAArgsAsWritten, ToTAInfo))
2981  return Err;
2982 
2983  ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation());
2984  if (!POIOrErr)
2985  return POIOrErr.takeError();
2986 
2987  if (Error Err = ImportTemplateParameterLists(FromFD, ToFD))
2988  return Err;
2989 
2990  TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
2991  ToFD->setFunctionTemplateSpecialization(
2992  std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
2993  TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
2994  return Error::success();
2995  }
2996 
2998  auto *FromInfo = FromFD->getDependentSpecializationInfo();
2999  UnresolvedSet<8> TemplDecls;
3000  unsigned NumTemplates = FromInfo->getNumTemplates();
3001  for (unsigned I = 0; I < NumTemplates; I++) {
3002  if (Expected<FunctionTemplateDecl *> ToFTDOrErr =
3003  import(FromInfo->getTemplate(I)))
3004  TemplDecls.addDecl(*ToFTDOrErr);
3005  else
3006  return ToFTDOrErr.takeError();
3007  }
3008 
3009  // Import TemplateArgumentListInfo.
3010  TemplateArgumentListInfo ToTAInfo;
3011  if (Error Err = ImportTemplateArgumentListInfo(
3012  FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(),
3013  llvm::makeArrayRef(
3014  FromInfo->getTemplateArgs(), FromInfo->getNumTemplateArgs()),
3015  ToTAInfo))
3016  return Err;
3017 
3018  ToFD->setDependentTemplateSpecialization(Importer.getToContext(),
3019  TemplDecls, ToTAInfo);
3020  return Error::success();
3021  }
3022  }
3023  llvm_unreachable("All cases should be covered!");
3024 }
3025 
3028  auto FunctionAndArgsOrErr =
3029  ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
3030  if (!FunctionAndArgsOrErr)
3031  return FunctionAndArgsOrErr.takeError();
3032 
3033  FunctionTemplateDecl *Template;
3034  TemplateArgsTy ToTemplArgs;
3035  std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr;
3036  void *InsertPos = nullptr;
3037  auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos);
3038  return FoundSpec;
3039 }
3040 
3042  FunctionDecl *ToFD) {
3043  if (Stmt *FromBody = FromFD->getBody()) {
3044  if (ExpectedStmt ToBodyOrErr = import(FromBody))
3045  ToFD->setBody(*ToBodyOrErr);
3046  else
3047  return ToBodyOrErr.takeError();
3048  }
3049  return Error::success();
3050 }
3051 
3053 
3055  auto RedeclIt = Redecls.begin();
3056  // Import the first part of the decl chain. I.e. import all previous
3057  // declarations starting from the canonical decl.
3058  for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3059  ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3060  if (!ToRedeclOrErr)
3061  return ToRedeclOrErr.takeError();
3062  }
3063  assert(*RedeclIt == D);
3064 
3065  // Import the major distinguishing characteristics of this function.
3066  DeclContext *DC, *LexicalDC;
3067  DeclarationName Name;
3068  SourceLocation Loc;
3069  NamedDecl *ToD;
3070  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3071  return std::move(Err);
3072  if (ToD)
3073  return ToD;
3074 
3075  FunctionDecl *FoundByLookup = nullptr;
3077 
3078  // If this is a function template specialization, then try to find the same
3079  // existing specialization in the "to" context. The lookup below will not
3080  // find any specialization, but would find the primary template; thus, we
3081  // have to skip normal lookup in case of specializations.
3082  // FIXME handle member function templates (TK_MemberSpecialization) similarly?
3083  if (D->getTemplatedKind() ==
3085  auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D);
3086  if (!FoundFunctionOrErr)
3087  return FoundFunctionOrErr.takeError();
3088  if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
3089  if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3090  return Def;
3091  FoundByLookup = FoundFunction;
3092  }
3093  }
3094  // Try to find a function in our own ("to") context with the same name, same
3095  // type, and in the same context as the function we're importing.
3096  else if (!LexicalDC->isFunctionOrMethod()) {
3097  SmallVector<NamedDecl *, 4> ConflictingDecls;
3099  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3100  for (auto *FoundDecl : FoundDecls) {
3101  if (!FoundDecl->isInIdentifierNamespace(IDNS))
3102  continue;
3103 
3104  if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
3105  if (!hasSameVisibilityContext(FoundFunction, D))
3106  continue;
3107 
3108  if (IsStructuralMatch(D, FoundFunction)) {
3109  if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3110  return Def;
3111  FoundByLookup = FoundFunction;
3112  break;
3113  }
3114  // FIXME: Check for overloading more carefully, e.g., by boosting
3115  // Sema::IsOverload out to the AST library.
3116 
3117  // Function overloading is okay in C++.
3118  if (Importer.getToContext().getLangOpts().CPlusPlus)
3119  continue;
3120 
3121  // Complain about inconsistent function types.
3122  Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent)
3123  << Name << D->getType() << FoundFunction->getType();
3124  Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here)
3125  << FoundFunction->getType();
3126  ConflictingDecls.push_back(FoundDecl);
3127  }
3128  }
3129 
3130  if (!ConflictingDecls.empty()) {
3131  ExpectedName NameOrErr = Importer.HandleNameConflict(
3132  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3133  if (NameOrErr)
3134  Name = NameOrErr.get();
3135  else
3136  return NameOrErr.takeError();
3137  }
3138  }
3139 
3140  // We do not allow more than one in-class declaration of a function. This is
3141  // because AST clients like VTableBuilder asserts on this. VTableBuilder
3142  // assumes there is only one in-class declaration. Building a redecl
3143  // chain would result in more than one in-class declaration for
3144  // overrides (even if they are part of the same redecl chain inside the
3145  // derived class.)
3146  if (FoundByLookup) {
3147  if (isa<CXXMethodDecl>(FoundByLookup)) {
3148  if (D->getLexicalDeclContext() == D->getDeclContext()) {
3149  if (!D->doesThisDeclarationHaveABody()) {
3150  if (FunctionTemplateDecl *DescribedD =
3152  // Handle a "templated" function together with its described
3153  // template. This avoids need for a similar check at import of the
3154  // described template.
3155  assert(FoundByLookup->getDescribedFunctionTemplate() &&
3156  "Templated function mapped to non-templated?");
3157  Importer.MapImported(DescribedD,
3158  FoundByLookup->getDescribedFunctionTemplate());
3159  }
3160  return Importer.MapImported(D, FoundByLookup);
3161  } else {
3162  // Let's continue and build up the redecl chain in this case.
3163  // FIXME Merge the functions into one decl.
3164  }
3165  }
3166  }
3167  }
3168 
3169  DeclarationNameInfo NameInfo(Name, Loc);
3170  // Import additional name location/type info.
3171  if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
3172  return std::move(Err);
3173 
3174  QualType FromTy = D->getType();
3175  bool usedDifferentExceptionSpec = false;
3176 
3177  if (const auto *FromFPT = D->getType()->getAs<FunctionProtoType>()) {
3178  FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3179  // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3180  // FunctionDecl that we are importing the FunctionProtoType for.
3181  // To avoid an infinite recursion when importing, create the FunctionDecl
3182  // with a simplified function type and update it afterwards.
3183  if (FromEPI.ExceptionSpec.SourceDecl ||
3184  FromEPI.ExceptionSpec.SourceTemplate ||
3185  FromEPI.ExceptionSpec.NoexceptExpr) {
3187  FromTy = Importer.getFromContext().getFunctionType(
3188  FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
3189  usedDifferentExceptionSpec = true;
3190  }
3191  }
3192 
3193  QualType T;
3194  TypeSourceInfo *TInfo;
3195  SourceLocation ToInnerLocStart, ToEndLoc;
3196  NestedNameSpecifierLoc ToQualifierLoc;
3197  if (auto Imp = importSeq(
3198  FromTy, D->getTypeSourceInfo(), D->getInnerLocStart(),
3199  D->getQualifierLoc(), D->getEndLoc()))
3200  std::tie(T, TInfo, ToInnerLocStart, ToQualifierLoc, ToEndLoc) = *Imp;
3201  else
3202  return Imp.takeError();
3203 
3204  // Import the function parameters.
3205  SmallVector<ParmVarDecl *, 8> Parameters;
3206  for (auto P : D->parameters()) {
3207  if (Expected<ParmVarDecl *> ToPOrErr = import(P))
3208  Parameters.push_back(*ToPOrErr);
3209  else
3210  return ToPOrErr.takeError();
3211  }
3212 
3213  // Create the imported function.
3214  FunctionDecl *ToFunction = nullptr;
3215  if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3216  Expr *ExplicitExpr = nullptr;
3217  if (FromConstructor->getExplicitSpecifier().getExpr()) {
3218  auto Imp = importSeq(FromConstructor->getExplicitSpecifier().getExpr());
3219  if (!Imp)
3220  return Imp.takeError();
3221  std::tie(ExplicitExpr) = *Imp;
3222  }
3223  if (GetImportedOrCreateDecl<CXXConstructorDecl>(
3224  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3225  ToInnerLocStart, NameInfo, T, TInfo,
3227  ExplicitExpr,
3228  FromConstructor->getExplicitSpecifier().getKind()),
3229  D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind()))
3230  return ToFunction;
3231  } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) {
3232 
3233  auto Imp =
3234  importSeq(const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()),
3235  FromDtor->getOperatorDeleteThisArg());
3236 
3237  if (!Imp)
3238  return Imp.takeError();
3239 
3240  FunctionDecl *ToOperatorDelete;
3241  Expr *ToThisArg;
3242  std::tie(ToOperatorDelete, ToThisArg) = *Imp;
3243 
3244  if (GetImportedOrCreateDecl<CXXDestructorDecl>(
3245  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3246  ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
3247  D->isImplicit()))
3248  return ToFunction;
3249 
3250  CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction);
3251 
3252  ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg);
3253  } else if (CXXConversionDecl *FromConversion =
3254  dyn_cast<CXXConversionDecl>(D)) {
3255  Expr *ExplicitExpr = nullptr;
3256  if (FromConversion->getExplicitSpecifier().getExpr()) {
3257  auto Imp = importSeq(FromConversion->getExplicitSpecifier().getExpr());
3258  if (!Imp)
3259  return Imp.takeError();
3260  std::tie(ExplicitExpr) = *Imp;
3261  }
3262  if (GetImportedOrCreateDecl<CXXConversionDecl>(
3263  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3264  ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
3265  ExplicitSpecifier(ExplicitExpr,
3266  FromConversion->getExplicitSpecifier().getKind()),
3268  return ToFunction;
3269  } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3270  if (GetImportedOrCreateDecl<CXXMethodDecl>(
3271  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3272  ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
3273  Method->isInlineSpecified(), D->getConstexprKind(),
3274  SourceLocation()))
3275  return ToFunction;
3276  } else {
3277  if (GetImportedOrCreateDecl(
3278  ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart,
3279  NameInfo, T, TInfo, D->getStorageClass(), D->isInlineSpecified(),
3281  return ToFunction;
3282  }
3283 
3284  // Connect the redecl chain.
3285  if (FoundByLookup) {
3286  auto *Recent = const_cast<FunctionDecl *>(
3287  FoundByLookup->getMostRecentDecl());
3288  ToFunction->setPreviousDecl(Recent);
3289  // FIXME Probably we should merge exception specifications. E.g. In the
3290  // "To" context the existing function may have exception specification with
3291  // noexcept-unevaluated, while the newly imported function may have an
3292  // evaluated noexcept. A call to adjustExceptionSpec() on the imported
3293  // decl and its redeclarations may be required.
3294  }
3295 
3296  ToFunction->setQualifierInfo(ToQualifierLoc);
3297  ToFunction->setAccess(D->getAccess());
3298  ToFunction->setLexicalDeclContext(LexicalDC);
3299  ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3300  ToFunction->setTrivial(D->isTrivial());
3301  ToFunction->setPure(D->isPure());
3302  ToFunction->setDefaulted(D->isDefaulted());
3304  ToFunction->setDeletedAsWritten(D->isDeletedAsWritten());
3305  ToFunction->setRangeEnd(ToEndLoc);
3306 
3307  // Set the parameters.
3308  for (auto *Param : Parameters) {
3309  Param->setOwningFunction(ToFunction);
3310  ToFunction->addDeclInternal(Param);
3311  }
3312  ToFunction->setParams(Parameters);
3313 
3314  // We need to complete creation of FunctionProtoTypeLoc manually with setting
3315  // params it refers to.
3316  if (TInfo) {
3317  if (auto ProtoLoc =
3319  for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
3320  ProtoLoc.setParam(I, Parameters[I]);
3321  }
3322  }
3323 
3324  if (usedDifferentExceptionSpec) {
3325  // Update FunctionProtoType::ExtProtoInfo.
3326  if (ExpectedType TyOrErr = import(D->getType()))
3327  ToFunction->setType(*TyOrErr);
3328  else
3329  return TyOrErr.takeError();
3330  }
3331 
3332  // Import the describing template function, if any.
3333  if (FromFT) {
3334  auto ToFTOrErr = import(FromFT);
3335  if (!ToFTOrErr)
3336  return ToFTOrErr.takeError();
3337  }
3338 
3339  // Import Ctor initializers.
3340  if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3341  if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
3342  SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
3343  // Import first, then allocate memory and copy if there was no error.
3344  if (Error Err = ImportContainerChecked(
3345  FromConstructor->inits(), CtorInitializers))
3346  return std::move(Err);
3347  auto **Memory =
3348  new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
3349  std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
3350  auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
3351  ToCtor->setCtorInitializers(Memory);
3352  ToCtor->setNumCtorInitializers(NumInitializers);
3353  }
3354  }
3355 
3356  if (D->doesThisDeclarationHaveABody()) {
3357  Error Err = ImportFunctionDeclBody(D, ToFunction);
3358 
3359  if (Err)
3360  return std::move(Err);
3361  }
3362 
3363  // FIXME: Other bits to merge?
3364 
3365  // If it is a template, import all related things.
3366  if (Error Err = ImportTemplateInformation(D, ToFunction))
3367  return std::move(Err);
3368 
3370 
3371  // TODO Can we generalize this approach to other AST nodes as well?
3372  if (D->getDeclContext()->containsDeclAndLoad(D))
3373  DC->addDeclInternal(ToFunction);
3374  if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
3375  LexicalDC->addDeclInternal(ToFunction);
3376 
3377  // Friend declaration's lexical context is the befriending class, but the
3378  // semantic context is the enclosing scope of the befriending class.
3379  // We want the friend functions to be found in the semantic context by lookup.
3380  // FIXME should we handle this generically in VisitFriendDecl?
3381  // In Other cases when LexicalDC != DC we don't want it to be added,
3382  // e.g out-of-class definitions like void B::f() {} .
3383  if (LexicalDC != DC && IsFriend) {
3384  DC->makeDeclVisibleInContext(ToFunction);
3385  }
3386 
3387  if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
3388  if (Error Err = ImportOverriddenMethods(cast<CXXMethodDecl>(ToFunction),
3389  FromCXXMethod))
3390  return std::move(Err);
3391 
3392  // Import the rest of the chain. I.e. import all subsequent declarations.
3393  for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3394  ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3395  if (!ToRedeclOrErr)
3396  return ToRedeclOrErr.takeError();
3397  }
3398 
3399  return ToFunction;
3400 }
3401 
3403  return VisitFunctionDecl(D);
3404 }
3405 
3407  return VisitCXXMethodDecl(D);
3408 }
3409 
3411  return VisitCXXMethodDecl(D);
3412 }
3413 
3415  return VisitCXXMethodDecl(D);
3416 }
3417 
3419  // Import the major distinguishing characteristics of a variable.
3420  DeclContext *DC, *LexicalDC;
3421  DeclarationName Name;
3422  SourceLocation Loc;
3423  NamedDecl *ToD;
3424  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3425  return std::move(Err);
3426  if (ToD)
3427  return ToD;
3428 
3429  // Determine whether we've already imported this field.
3430  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3431  for (auto *FoundDecl : FoundDecls) {
3432  if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
3433  // For anonymous fields, match up by index.
3434  if (!Name &&
3436  ASTImporter::getFieldIndex(FoundField))
3437  continue;
3438 
3439  if (Importer.IsStructurallyEquivalent(D->getType(),
3440  FoundField->getType())) {
3441  Importer.MapImported(D, FoundField);
3442  // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
3443  // initializer of a FieldDecl might not had been instantiated in the
3444  // "To" context. However, the "From" context might instantiated that,
3445  // thus we have to merge that.
3446  if (Expr *FromInitializer = D->getInClassInitializer()) {
3447  // We don't have yet the initializer set.
3448  if (FoundField->hasInClassInitializer() &&
3449  !FoundField->getInClassInitializer()) {
3450  if (ExpectedExpr ToInitializerOrErr = import(FromInitializer))
3451  FoundField->setInClassInitializer(*ToInitializerOrErr);
3452  else {
3453  // We can't return error here,
3454  // since we already mapped D as imported.
3455  // FIXME: warning message?
3456  consumeError(ToInitializerOrErr.takeError());
3457  return FoundField;
3458  }
3459  }
3460  }
3461  return FoundField;
3462  }
3463 
3464  // FIXME: Why is this case not handled with calling HandleNameConflict?
3465  Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3466  << Name << D->getType() << FoundField->getType();
3467  Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3468  << FoundField->getType();
3469 
3470  return make_error<ImportError>(ImportError::NameConflict);
3471  }
3472  }
3473 
3474  QualType ToType;
3475  TypeSourceInfo *ToTInfo;
3476  Expr *ToBitWidth;
3477  SourceLocation ToInnerLocStart;
3478  Expr *ToInitializer;
3479  if (auto Imp = importSeq(
3480  D->getType(), D->getTypeSourceInfo(), D->getBitWidth(),
3482  std::tie(
3483  ToType, ToTInfo, ToBitWidth, ToInnerLocStart, ToInitializer) = *Imp;
3484  else
3485  return Imp.takeError();
3486 
3487  FieldDecl *ToField;
3488  if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
3489  ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3490  ToType, ToTInfo, ToBitWidth, D->isMutable(),
3491  D->getInClassInitStyle()))
3492  return ToField;
3493 
3494  ToField->setAccess(D->getAccess());
3495  ToField->setLexicalDeclContext(LexicalDC);
3496  if (ToInitializer)
3497  ToField->setInClassInitializer(ToInitializer);
3498  ToField->setImplicit(D->isImplicit());
3499  LexicalDC->addDeclInternal(ToField);
3500  return ToField;
3501 }
3502 
3504  // Import the major distinguishing characteristics of a variable.
3505  DeclContext *DC, *LexicalDC;
3506  DeclarationName Name;
3507  SourceLocation Loc;
3508  NamedDecl *ToD;
3509  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3510  return std::move(Err);
3511  if (ToD)
3512  return ToD;
3513 
3514  // Determine whether we've already imported this field.
3515  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3516  for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3517  if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3518  // For anonymous indirect fields, match up by index.
3519  if (!Name &&
3521  ASTImporter::getFieldIndex(FoundField))
3522  continue;
3523 
3524  if (Importer.IsStructurallyEquivalent(D->getType(),
3525  FoundField->getType(),
3526  !Name.isEmpty())) {
3527  Importer.MapImported(D, FoundField);
3528  return FoundField;
3529  }
3530 
3531  // If there are more anonymous fields to check, continue.
3532  if (!Name && I < N-1)
3533  continue;
3534 
3535  // FIXME: Why is this case not handled with calling HandleNameConflict?
3536  Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3537  << Name << D->getType() << FoundField->getType();
3538  Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3539  << FoundField->getType();
3540 
3541  return make_error<ImportError>(ImportError::NameConflict);
3542  }
3543  }
3544 
3545  // Import the type.
3546  auto TypeOrErr = import(D->getType());
3547  if (!TypeOrErr)
3548  return TypeOrErr.takeError();
3549 
3550  auto **NamedChain =
3551  new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
3552 
3553  unsigned i = 0;
3554  for (auto *PI : D->chain())
3555  if (Expected<NamedDecl *> ToD = import(PI))
3556  NamedChain[i++] = *ToD;
3557  else
3558  return ToD.takeError();
3559 
3560  llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
3561  IndirectFieldDecl *ToIndirectField;
3562  if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
3563  Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
3564  // FIXME here we leak `NamedChain` which is allocated before
3565  return ToIndirectField;
3566 
3567  ToIndirectField->setAccess(D->getAccess());
3568  ToIndirectField->setLexicalDeclContext(LexicalDC);
3569  LexicalDC->addDeclInternal(ToIndirectField);
3570  return ToIndirectField;
3571 }
3572 
3574  // Import the major distinguishing characteristics of a declaration.
3575  DeclContext *DC, *LexicalDC;
3576  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
3577  return std::move(Err);
3578 
3579  // Determine whether we've already imported this decl.
3580  // FriendDecl is not a NamedDecl so we cannot use lookup.
3581  auto *RD = cast<CXXRecordDecl>(DC);
3582  FriendDecl *ImportedFriend = RD->getFirstFriend();
3583 
3584  while (ImportedFriend) {
3585  if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
3586  if (IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(),
3587  /*Complain=*/false))
3588  return Importer.MapImported(D, ImportedFriend);
3589 
3590  } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
3591  if (Importer.IsStructurallyEquivalent(
3592  D->getFriendType()->getType(),
3593  ImportedFriend->getFriendType()->getType(), true))
3594  return Importer.MapImported(D, ImportedFriend);
3595  }
3596  ImportedFriend = ImportedFriend->getNextFriend();
3597  }
3598 
3599  // Not found. Create it.
3601  if (NamedDecl *FriendD = D->getFriendDecl()) {
3602  NamedDecl *ToFriendD;
3603  if (Error Err = importInto(ToFriendD, FriendD))
3604  return std::move(Err);
3605 
3606  if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
3607  !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
3608  ToFriendD->setObjectOfFriendDecl(false);
3609 
3610  ToFU = ToFriendD;
3611  } else { // The friend is a type, not a decl.
3612  if (auto TSIOrErr = import(D->getFriendType()))
3613  ToFU = *TSIOrErr;
3614  else
3615  return TSIOrErr.takeError();
3616  }
3617 
3618  SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
3619  auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
3620  for (unsigned I = 0; I < D->NumTPLists; I++) {
3621  if (auto ListOrErr = import(FromTPLists[I]))
3622  ToTPLists[I] = *ListOrErr;
3623  else
3624  return ListOrErr.takeError();
3625  }
3626 
3627  auto LocationOrErr = import(D->getLocation());
3628  if (!LocationOrErr)
3629  return LocationOrErr.takeError();
3630  auto FriendLocOrErr = import(D->getFriendLoc());
3631  if (!FriendLocOrErr)
3632  return FriendLocOrErr.takeError();
3633 
3634  FriendDecl *FrD;
3635  if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
3636  *LocationOrErr, ToFU,
3637  *FriendLocOrErr, ToTPLists))
3638  return FrD;
3639 
3640  FrD->setAccess(D->getAccess());
3641  FrD->setLexicalDeclContext(LexicalDC);
3642  LexicalDC->addDeclInternal(FrD);
3643  return FrD;
3644 }
3645 
3647  // Import the major distinguishing characteristics of an ivar.
3648  DeclContext *DC, *LexicalDC;
3649  DeclarationName Name;
3650  SourceLocation Loc;
3651  NamedDecl *ToD;
3652  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3653  return std::move(Err);
3654  if (ToD)
3655  return ToD;
3656 
3657  // Determine whether we've already imported this ivar
3658  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3659  for (auto *FoundDecl : FoundDecls) {
3660  if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
3661  if (Importer.IsStructurallyEquivalent(D->getType(),
3662  FoundIvar->getType())) {
3663  Importer.MapImported(D, FoundIvar);
3664  return FoundIvar;
3665  }
3666 
3667  Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent)
3668  << Name << D->getType() << FoundIvar->getType();
3669  Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3670  << FoundIvar->getType();
3671 
3672  return make_error<ImportError>(ImportError::NameConflict);
3673  }
3674  }
3675 
3676  QualType ToType;
3677  TypeSourceInfo *ToTypeSourceInfo;
3678  Expr *ToBitWidth;
3679  SourceLocation ToInnerLocStart;
3680  if (auto Imp = importSeq(
3681  D->getType(), D->getTypeSourceInfo(), D->getBitWidth(), D->getInnerLocStart()))
3682  std::tie(ToType, ToTypeSourceInfo, ToBitWidth, ToInnerLocStart) = *Imp;
3683  else
3684  return Imp.takeError();
3685 
3686  ObjCIvarDecl *ToIvar;
3687  if (GetImportedOrCreateDecl(
3688  ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
3689  ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3690  ToType, ToTypeSourceInfo,
3691  D->getAccessControl(),ToBitWidth, D->getSynthesize()))
3692  return ToIvar;
3693 
3694  ToIvar->setLexicalDeclContext(LexicalDC);
3695  LexicalDC->addDeclInternal(ToIvar);
3696  return ToIvar;
3697 }
3698 
3700 
3702  auto RedeclIt = Redecls.begin();
3703  // Import the first part of the decl chain. I.e. import all previous
3704  // declarations starting from the canonical decl.
3705  for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3706  ExpectedDecl RedeclOrErr = import(*RedeclIt);
3707  if (!RedeclOrErr)
3708  return RedeclOrErr.takeError();
3709  }
3710  assert(*RedeclIt == D);
3711 
3712  // Import the major distinguishing characteristics of a variable.
3713  DeclContext *DC, *LexicalDC;
3714  DeclarationName Name;
3715  SourceLocation Loc;
3716  NamedDecl *ToD;
3717  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3718  return std::move(Err);
3719  if (ToD)
3720  return ToD;
3721 
3722  // Try to find a variable in our own ("to") context with the same name and
3723  // in the same context as the variable we're importing.
3724  VarDecl *FoundByLookup = nullptr;
3725  if (D->isFileVarDecl()) {
3726  SmallVector<NamedDecl *, 4> ConflictingDecls;
3727  unsigned IDNS = Decl::IDNS_Ordinary;
3728  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3729  for (auto *FoundDecl : FoundDecls) {
3730  if (!FoundDecl->isInIdentifierNamespace(IDNS))
3731  continue;
3732 
3733  if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
3734  if (!hasSameVisibilityContext(FoundVar, D))
3735  continue;
3736  if (Importer.IsStructurallyEquivalent(D->getType(),
3737  FoundVar->getType())) {
3738 
3739  // The VarDecl in the "From" context has a definition, but in the
3740  // "To" context we already have a definition.
3741  VarDecl *FoundDef = FoundVar->getDefinition();
3742  if (D->isThisDeclarationADefinition() && FoundDef)
3743  // FIXME Check for ODR error if the two definitions have
3744  // different initializers?
3745  return Importer.MapImported(D, FoundDef);
3746 
3747  // The VarDecl in the "From" context has an initializer, but in the
3748  // "To" context we already have an initializer.
3749  const VarDecl *FoundDInit = nullptr;
3750  if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
3751  // FIXME Diagnose ODR error if the two initializers are different?
3752  return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
3753 
3754  FoundByLookup = FoundVar;
3755  break;
3756  }
3757 
3758  const ArrayType *FoundArray
3759  = Importer.getToContext().getAsArrayType(FoundVar->getType());
3760  const ArrayType *TArray
3761  = Importer.getToContext().getAsArrayType(D->getType());
3762  if (FoundArray && TArray) {
3763  if (isa<IncompleteArrayType>(FoundArray) &&
3764  isa<ConstantArrayType>(TArray)) {
3765  // Import the type.
3766  if (auto TyOrErr = import(D->getType()))
3767  FoundVar->setType(*TyOrErr);
3768  else
3769  return TyOrErr.takeError();
3770 
3771  FoundByLookup = FoundVar;
3772  break;
3773  } else if (isa<IncompleteArrayType>(TArray) &&
3774  isa<ConstantArrayType>(FoundArray)) {
3775  FoundByLookup = FoundVar;
3776  break;
3777  }
3778  }
3779 
3780  Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent)
3781  << Name << D->getType() << FoundVar->getType();
3782  Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3783  << FoundVar->getType();
3784  ConflictingDecls.push_back(FoundDecl);
3785  }
3786  }
3787 
3788  if (!ConflictingDecls.empty()) {
3789  ExpectedName NameOrErr = Importer.HandleNameConflict(
3790  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3791  if (NameOrErr)
3792  Name = NameOrErr.get();
3793  else
3794  return NameOrErr.takeError();
3795  }
3796  }
3797 
3798  QualType ToType;
3799  TypeSourceInfo *ToTypeSourceInfo;
3800  SourceLocation ToInnerLocStart;
3801  NestedNameSpecifierLoc ToQualifierLoc;
3802  if (auto Imp = importSeq(
3803  D->getType(), D->getTypeSourceInfo(), D->getInnerLocStart(),
3804  D->getQualifierLoc()))
3805  std::tie(ToType, ToTypeSourceInfo, ToInnerLocStart, ToQualifierLoc) = *Imp;
3806  else
3807  return Imp.takeError();
3808 
3809  // Create the imported variable.
3810  VarDecl *ToVar;
3811  if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
3812  ToInnerLocStart, Loc,
3813  Name.getAsIdentifierInfo(),
3814  ToType, ToTypeSourceInfo,
3815  D->getStorageClass()))
3816  return ToVar;
3817 
3818  ToVar->setQualifierInfo(ToQualifierLoc);
3819  ToVar->setAccess(D->getAccess());
3820  ToVar->setLexicalDeclContext(LexicalDC);
3821 
3822  if (FoundByLookup) {
3823  auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
3824  ToVar->setPreviousDecl(Recent);
3825  }
3826 
3827  if (Error Err = ImportInitializer(D, ToVar))
3828  return std::move(Err);
3829 
3830  if (D->isConstexpr())
3831  ToVar->setConstexpr(true);
3832 
3833  if (D->getDeclContext()->containsDeclAndLoad(D))
3834  DC->addDeclInternal(ToVar);
3835  if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
3836  LexicalDC->addDeclInternal(ToVar);
3837 
3838  // Import the rest of the chain. I.e. import all subsequent declarations.
3839  for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3840  ExpectedDecl RedeclOrErr = import(*RedeclIt);
3841  if (!RedeclOrErr)
3842  return RedeclOrErr.takeError();
3843  }
3844 
3845  return ToVar;
3846 }
3847 
3849  // Parameters are created in the translation unit's context, then moved
3850  // into the function declaration's context afterward.
3851  DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3852 
3853  DeclarationName ToDeclName;
3854  SourceLocation ToLocation;
3855  QualType ToType;
3856  if (auto Imp = importSeq(D->getDeclName(), D->getLocation(), D->getType()))
3857  std::tie(ToDeclName, ToLocation, ToType) = *Imp;
3858  else
3859  return Imp.takeError();
3860 
3861  // Create the imported parameter.
3862  ImplicitParamDecl *ToParm = nullptr;
3863  if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
3864  ToLocation, ToDeclName.getAsIdentifierInfo(),
3865  ToType, D->getParameterKind()))
3866  return ToParm;
3867  return ToParm;
3868 }
3869 
3871  const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
3872  ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg());
3873  ToParam->setKNRPromoted(FromParam->isKNRPromoted());
3874 
3875  if (FromParam->hasUninstantiatedDefaultArg()) {
3876  if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg()))
3877  ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
3878  else
3879  return ToDefArgOrErr.takeError();
3880  } else if (FromParam->hasUnparsedDefaultArg()) {
3881  ToParam->setUnparsedDefaultArg();
3882  } else if (FromParam->hasDefaultArg()) {
3883  if (auto ToDefArgOrErr = import(FromParam->getDefaultArg()))
3884  ToParam->setDefaultArg(*ToDefArgOrErr);
3885  else
3886  return ToDefArgOrErr.takeError();
3887  }
3888 
3889  return Error::success();
3890 }
3891 
3893  // Parameters are created in the translation unit's context, then moved
3894  // into the function declaration's context afterward.
3895  DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3896 
3897  DeclarationName ToDeclName;
3898  SourceLocation ToLocation, ToInnerLocStart;
3899  QualType ToType;
3900  TypeSourceInfo *ToTypeSourceInfo;
3901  if (auto Imp = importSeq(
3902  D->getDeclName(), D->getLocation(), D->getType(), D->getInnerLocStart(),
3903  D->getTypeSourceInfo()))
3904  std::tie(
3905  ToDeclName, ToLocation, ToType, ToInnerLocStart,
3906  ToTypeSourceInfo) = *Imp;
3907  else
3908  return Imp.takeError();
3909 
3910  ParmVarDecl *ToParm;
3911  if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
3912  ToInnerLocStart, ToLocation,
3913  ToDeclName.getAsIdentifierInfo(), ToType,
3914  ToTypeSourceInfo, D->getStorageClass(),
3915  /*DefaultArg*/ nullptr))
3916  return ToParm;
3917 
3918  // Set the default argument. It should be no problem if it was already done.
3919  // Do not import the default expression before GetImportedOrCreateDecl call
3920  // to avoid possible infinite import loop because circular dependency.
3921  if (Error Err = ImportDefaultArgOfParmVarDecl(D, ToParm))
3922  return std::move(Err);
3923 
3924  if (D->isObjCMethodParameter()) {
3927  } else {
3928  ToParm->setScopeInfo(D->getFunctionScopeDepth(),
3929  D->getFunctionScopeIndex());
3930  }
3931 
3932  return ToParm;
3933 }
3934 
3936  // Import the major distinguishing characteristics of a method.
3937  DeclContext *DC, *LexicalDC;
3938  DeclarationName Name;
3939  SourceLocation Loc;
3940  NamedDecl *ToD;
3941  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3942  return std::move(Err);
3943  if (ToD)
3944  return ToD;
3945 
3946  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3947  for (auto *FoundDecl : FoundDecls) {
3948  if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
3949  if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3950  continue;
3951 
3952  // Check return types.
3953  if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3954  FoundMethod->getReturnType())) {
3955  Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent)
3956  << D->isInstanceMethod() << Name << D->getReturnType()
3957  << FoundMethod->getReturnType();
3958  Importer.ToDiag(FoundMethod->getLocation(),
3959  diag::note_odr_objc_method_here)
3960  << D->isInstanceMethod() << Name;
3961 
3962  return make_error<ImportError>(ImportError::NameConflict);
3963  }
3964 
3965  // Check the number of parameters.
3966  if (D->param_size() != FoundMethod->param_size()) {
3967  Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent)
3968  << D->isInstanceMethod() << Name
3969  << D->param_size() << FoundMethod->param_size();
3970  Importer.ToDiag(FoundMethod->getLocation(),
3971  diag::note_odr_objc_method_here)
3972  << D->isInstanceMethod() << Name;
3973 
3974  return make_error<ImportError>(ImportError::NameConflict);
3975  }
3976 
3977  // Check parameter types.
3979  PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3980  P != PEnd; ++P, ++FoundP) {
3981  if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3982  (*FoundP)->getType())) {
3983  Importer.FromDiag((*P)->getLocation(),
3984  diag::warn_odr_objc_method_param_type_inconsistent)
3985  << D->isInstanceMethod() << Name
3986  << (*P)->getType() << (*FoundP)->getType();
3987  Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3988  << (*FoundP)->getType();
3989 
3990  return make_error<ImportError>(ImportError::NameConflict);
3991  }
3992  }
3993 
3994  // Check variadic/non-variadic.
3995  // Check the number of parameters.
3996  if (D->isVariadic() != FoundMethod->isVariadic()) {
3997  Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent)
3998  << D->isInstanceMethod() << Name;
3999  Importer.ToDiag(FoundMethod->getLocation(),
4000  diag::note_odr_objc_method_here)
4001  << D->isInstanceMethod() << Name;
4002 
4003  return make_error<ImportError>(ImportError::NameConflict);
4004  }
4005 
4006  // FIXME: Any other bits we need to merge?
4007  return Importer.MapImported(D, FoundMethod);
4008  }
4009  }
4010 
4011  SourceLocation ToEndLoc;
4012  QualType ToReturnType;
4013  TypeSourceInfo *ToReturnTypeSourceInfo;
4014  if (auto Imp = importSeq(
4016  std::tie(ToEndLoc, ToReturnType, ToReturnTypeSourceInfo) = *Imp;
4017  else
4018  return Imp.takeError();
4019 
4020  ObjCMethodDecl *ToMethod;
4021  if (GetImportedOrCreateDecl(
4022  ToMethod, D, Importer.getToContext(), Loc,
4023  ToEndLoc, Name.getObjCSelector(), ToReturnType,
4024  ToReturnTypeSourceInfo, DC, D->isInstanceMethod(), D->isVariadic(),
4025  D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
4027  return ToMethod;
4028 
4029  // FIXME: When we decide to merge method definitions, we'll need to
4030  // deal with implicit parameters.
4031 
4032  // Import the parameters
4034  for (auto *FromP : D->parameters()) {
4035  if (Expected<ParmVarDecl *> ToPOrErr = import(FromP))
4036  ToParams.push_back(*ToPOrErr);
4037  else
4038  return ToPOrErr.takeError();
4039  }
4040 
4041  // Set the parameters.
4042  for (auto *ToParam : ToParams) {
4043  ToParam->setOwningFunction(ToMethod);
4044  ToMethod->addDeclInternal(ToParam);
4045  }
4046 
4047  SmallVector<SourceLocation, 12> FromSelLocs;
4048  D->getSelectorLocs(FromSelLocs);
4049  SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
4050  if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs))
4051  return std::move(Err);
4052 
4053  ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs);
4054 
4055  ToMethod->setLexicalDeclContext(LexicalDC);
4056  LexicalDC->addDeclInternal(ToMethod);
4057  return ToMethod;
4058 }
4059 
4061  // Import the major distinguishing characteristics of a category.
4062  DeclContext *DC, *LexicalDC;
4063  DeclarationName Name;
4064  SourceLocation Loc;
4065  NamedDecl *ToD;
4066  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4067  return std::move(Err);
4068  if (ToD)
4069  return ToD;
4070 
4071  SourceLocation ToVarianceLoc, ToLocation, ToColonLoc;
4072  TypeSourceInfo *ToTypeSourceInfo;
4073  if (auto Imp = importSeq(
4074  D->getVarianceLoc(), D->getLocation(), D->getColonLoc(),
4075  D->getTypeSourceInfo()))
4076  std::tie(ToVarianceLoc, ToLocation, ToColonLoc, ToTypeSourceInfo) = *Imp;
4077  else
4078  return Imp.takeError();
4079 
4081  if (GetImportedOrCreateDecl(
4082  Result, D, Importer.getToContext(), DC, D->getVariance(),
4083  ToVarianceLoc, D->getIndex(),
4084  ToLocation, Name.getAsIdentifierInfo(),
4085  ToColonLoc, ToTypeSourceInfo))
4086  return Result;
4087 
4088  Result->setLexicalDeclContext(LexicalDC);
4089  return Result;
4090 }
4091 
4093  // Import the major distinguishing characteristics of a category.
4094  DeclContext *DC, *LexicalDC;
4095  DeclarationName Name;
4096  SourceLocation Loc;
4097  NamedDecl *ToD;
4098  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4099  return std::move(Err);
4100  if (ToD)
4101  return ToD;
4102 
4103  ObjCInterfaceDecl *ToInterface;
4104  if (Error Err = importInto(ToInterface, D->getClassInterface()))
4105  return std::move(Err);
4106 
4107  // Determine if we've already encountered this category.
4108  ObjCCategoryDecl *MergeWithCategory
4109  = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
4110  ObjCCategoryDecl *ToCategory = MergeWithCategory;
4111  if (!ToCategory) {
4112  SourceLocation ToAtStartLoc, ToCategoryNameLoc;
4113  SourceLocation ToIvarLBraceLoc, ToIvarRBraceLoc;
4114  if (auto Imp = importSeq(
4115  D->getAtStartLoc(), D->getCategoryNameLoc(),
4116  D->getIvarLBraceLoc(), D->getIvarRBraceLoc()))
4117  std::tie(
4118  ToAtStartLoc, ToCategoryNameLoc,
4119  ToIvarLBraceLoc, ToIvarRBraceLoc) = *Imp;
4120  else
4121  return Imp.takeError();
4122 
4123  if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
4124  ToAtStartLoc, Loc,
4125  ToCategoryNameLoc,
4126  Name.getAsIdentifierInfo(), ToInterface,
4127  /*TypeParamList=*/nullptr,
4128  ToIvarLBraceLoc,
4129  ToIvarRBraceLoc))
4130  return ToCategory;
4131 
4132  ToCategory->setLexicalDeclContext(LexicalDC);
4133  LexicalDC->addDeclInternal(ToCategory);
4134  // Import the type parameter list after MapImported, to avoid
4135  // loops when bringing in their DeclContext.
4136  if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList()))
4137  ToCategory->setTypeParamList(*PListOrErr);
4138  else
4139  return PListOrErr.takeError();
4140 
4141  // Import protocols
4143  SmallVector<SourceLocation, 4> ProtocolLocs;
4145  = D->protocol_loc_begin();
4147  FromProtoEnd = D->protocol_end();
4148  FromProto != FromProtoEnd;
4149  ++FromProto, ++FromProtoLoc) {
4150  if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4151  Protocols.push_back(*ToProtoOrErr);
4152  else
4153  return ToProtoOrErr.takeError();
4154 
4155  if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4156  ProtocolLocs.push_back(*ToProtoLocOrErr);
4157  else
4158  return ToProtoLocOrErr.takeError();
4159  }
4160 
4161  // FIXME: If we're merging, make sure that the protocol list is the same.
4162  ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
4163  ProtocolLocs.data(), Importer.getToContext());
4164 
4165  } else {
4166  Importer.MapImported(D, ToCategory);
4167  }
4168 
4169  // Import all of the members of this category.
4170  if (Error Err = ImportDeclContext(D))
4171  return std::move(Err);
4172 
4173  // If we have an implementation, import it as well.
4174  if (D->getImplementation()) {
4175  if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
4176  import(D->getImplementation()))
4177  ToCategory->setImplementation(*ToImplOrErr);
4178  else
4179  return ToImplOrErr.takeError();
4180  }
4181 
4182  return ToCategory;
4183 }
4184 
4187  if (To->getDefinition()) {
4188  if (shouldForceImportDeclContext(Kind))
4189  if (Error Err = ImportDeclContext(From))
4190  return Err;
4191  return Error::success();
4192  }
4193 
4194  // Start the protocol definition
4195  To->startDefinition();
4196 
4197  // Import protocols
4199  SmallVector<SourceLocation, 4> ProtocolLocs;
4201  From->protocol_loc_begin();
4202  for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
4203  FromProtoEnd = From->protocol_end();
4204  FromProto != FromProtoEnd;
4205  ++FromProto, ++FromProtoLoc) {
4206  if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4207  Protocols.push_back(*ToProtoOrErr);
4208  else
4209  return ToProtoOrErr.takeError();
4210 
4211  if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4212  ProtocolLocs.push_back(*ToProtoLocOrErr);
4213  else
4214  return ToProtoLocOrErr.takeError();
4215 
4216  }
4217 
4218  // FIXME: If we're merging, make sure that the protocol list is the same.
4219  To->setProtocolList(Protocols.data(), Protocols.size(),
4220  ProtocolLocs.data(), Importer.getToContext());
4221 
4222  if (shouldForceImportDeclContext(Kind)) {
4223  // Import all of the members of this protocol.
4224  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4225  return Err;
4226  }
4227  return Error::success();
4228 }
4229 
4231  // If this protocol has a definition in the translation unit we're coming
4232  // from, but this particular declaration is not that definition, import the
4233  // definition and map to that.
4234  ObjCProtocolDecl *Definition = D->getDefinition();
4235  if (Definition && Definition != D) {
4236  if (ExpectedDecl ImportedDefOrErr = import(Definition))
4237  return Importer.MapImported(D, *ImportedDefOrErr);
4238  else
4239  return ImportedDefOrErr.takeError();
4240  }
4241 
4242  // Import the major distinguishing characteristics of a protocol.
4243  DeclContext *DC, *LexicalDC;
4244  DeclarationName Name;
4245  SourceLocation Loc;
4246  NamedDecl *ToD;
4247  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4248  return std::move(Err);
4249  if (ToD)
4250  return ToD;
4251 
4252  ObjCProtocolDecl *MergeWithProtocol = nullptr;
4253  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4254  for (auto *FoundDecl : FoundDecls) {
4256  continue;
4257 
4258  if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
4259  break;
4260  }
4261 
4262  ObjCProtocolDecl *ToProto = MergeWithProtocol;
4263  if (!ToProto) {
4264  auto ToAtBeginLocOrErr = import(D->getAtStartLoc());
4265  if (!ToAtBeginLocOrErr)
4266  return ToAtBeginLocOrErr.takeError();
4267 
4268  if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
4269  Name.getAsIdentifierInfo(), Loc,
4270  *ToAtBeginLocOrErr,
4271  /*PrevDecl=*/nullptr))
4272  return ToProto;
4273  ToProto->setLexicalDeclContext(LexicalDC);
4274  LexicalDC->addDeclInternal(ToProto);
4275  }
4276 
4277  Importer.MapImported(D, ToProto);
4278 
4280  if (Error Err = ImportDefinition(D, ToProto))
4281  return std::move(Err);
4282 
4283  return ToProto;
4284 }
4285 
4287  DeclContext *DC, *LexicalDC;
4288  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4289  return std::move(Err);
4290 
4291  ExpectedSLoc ExternLocOrErr = import(D->getExternLoc());
4292  if (!ExternLocOrErr)
4293  return ExternLocOrErr.takeError();
4294 
4295  ExpectedSLoc LangLocOrErr = import(D->getLocation());
4296  if (!LangLocOrErr)
4297  return LangLocOrErr.takeError();
4298 
4299  bool HasBraces = D->hasBraces();
4300 
4301  LinkageSpecDecl *ToLinkageSpec;
4302  if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
4303  *ExternLocOrErr, *LangLocOrErr,
4304  D->getLanguage(), HasBraces))
4305  return ToLinkageSpec;
4306 
4307  if (HasBraces) {
4308  ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
4309  if (!RBraceLocOrErr)
4310  return RBraceLocOrErr.takeError();
4311  ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
4312  }
4313 
4314  ToLinkageSpec->setLexicalDeclContext(LexicalDC);
4315  LexicalDC->addDeclInternal(ToLinkageSpec);
4316 
4317  return ToLinkageSpec;
4318 }
4319 
4321  DeclContext *DC, *LexicalDC;
4322  DeclarationName Name;
4323  SourceLocation Loc;
4324  NamedDecl *ToD = nullptr;
4325  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4326  return std::move(Err);
4327  if (ToD)
4328  return ToD;
4329 
4330  SourceLocation ToLoc, ToUsingLoc;
4331  NestedNameSpecifierLoc ToQualifierLoc;
4332  if (auto Imp = importSeq(
4333  D->getNameInfo().getLoc(), D->getUsingLoc(), D->getQualifierLoc()))
4334  std::tie(ToLoc, ToUsingLoc, ToQualifierLoc) = *Imp;
4335  else
4336  return Imp.takeError();
4337 
4338  DeclarationNameInfo NameInfo(Name, ToLoc);
4339  if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4340  return std::move(Err);
4341 
4342  UsingDecl *ToUsing;
4343  if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4344  ToUsingLoc, ToQualifierLoc, NameInfo,
4345  D->hasTypename()))
4346  return ToUsing;
4347 
4348  ToUsing->setLexicalDeclContext(LexicalDC);
4349  LexicalDC->addDeclInternal(ToUsing);
4350 
4351  if (NamedDecl *FromPattern =
4352  Importer.getFromContext().getInstantiatedFromUsingDecl(D)) {
4353  if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern))
4354  Importer.getToContext().setInstantiatedFromUsingDecl(
4355  ToUsing, *ToPatternOrErr);
4356  else
4357  return ToPatternOrErr.takeError();
4358  }
4359 
4360  for (UsingShadowDecl *FromShadow : D->shadows()) {
4361  if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow))
4362  ToUsing->addShadowDecl(*ToShadowOrErr);
4363  else
4364  // FIXME: We return error here but the definition is already created
4365  // and available with lookups. How to fix this?..
4366  return ToShadowOrErr.takeError();
4367  }
4368  return ToUsing;
4369 }
4370 
4372  DeclContext *DC, *LexicalDC;
4373  DeclarationName Name;
4374  SourceLocation Loc;
4375  NamedDecl *ToD = nullptr;
4376  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4377  return std::move(Err);
4378  if (ToD)
4379  return ToD;
4380 
4381  Expected<UsingDecl *> ToUsingOrErr = import(D->getUsingDecl());
4382  if (!ToUsingOrErr)
4383  return ToUsingOrErr.takeError();
4384 
4385  Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl());
4386  if (!ToTargetOrErr)
4387  return ToTargetOrErr.takeError();
4388 
4389  UsingShadowDecl *ToShadow;
4390  if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
4391  *ToUsingOrErr, *ToTargetOrErr))
4392  return ToShadow;
4393 
4394  ToShadow->setLexicalDeclContext(LexicalDC);
4395  ToShadow->setAccess(D->getAccess());
4396 
4397  if (UsingShadowDecl *FromPattern =
4398  Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) {
4399  if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern))
4400  Importer.getToContext().setInstantiatedFromUsingShadowDecl(
4401  ToShadow, *ToPatternOrErr);
4402  else
4403  // FIXME: We return error here but the definition is already created
4404  // and available with lookups. How to fix this?..
4405  return ToPatternOrErr.takeError();
4406  }
4407 
4408  LexicalDC->addDeclInternal(ToShadow);
4409 
4410  return ToShadow;
4411 }
4412 
4414  DeclContext *DC, *LexicalDC;
4415  DeclarationName Name;
4416  SourceLocation Loc;
4417  NamedDecl *ToD = nullptr;
4418  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4419  return std::move(Err);
4420  if (ToD)
4421  return ToD;
4422 
4423  auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor());
4424  if (!ToComAncestorOrErr)
4425  return ToComAncestorOrErr.takeError();
4426 
4427  NamespaceDecl *ToNominatedNamespace;
4428  SourceLocation ToUsingLoc, ToNamespaceKeyLocation, ToIdentLocation;
4429  NestedNameSpecifierLoc ToQualifierLoc;
4430  if (auto Imp = importSeq(
4433  D->getIdentLocation()))
4434  std::tie(
4435  ToNominatedNamespace, ToUsingLoc, ToNamespaceKeyLocation,
4436  ToQualifierLoc, ToIdentLocation) = *Imp;
4437  else
4438  return Imp.takeError();
4439 
4440  UsingDirectiveDecl *ToUsingDir;
4441  if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
4442  ToUsingLoc,
4443  ToNamespaceKeyLocation,
4444  ToQualifierLoc,
4445  ToIdentLocation,
4446  ToNominatedNamespace, *ToComAncestorOrErr))
4447  return ToUsingDir;
4448 
4449  ToUsingDir->setLexicalDeclContext(LexicalDC);
4450  LexicalDC->addDeclInternal(ToUsingDir);
4451 
4452  return ToUsingDir;
4453 }
4454 
4457  DeclContext *DC, *LexicalDC;
4458  DeclarationName Name;
4459  SourceLocation Loc;
4460  NamedDecl *ToD = nullptr;
4461  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4462  return std::move(Err);
4463  if (ToD)
4464  return ToD;
4465 
4466  SourceLocation ToLoc, ToUsingLoc, ToEllipsisLoc;
4467  NestedNameSpecifierLoc ToQualifierLoc;
4468  if (auto Imp = importSeq(
4469  D->getNameInfo().getLoc(), D->getUsingLoc(), D->getQualifierLoc(),
4470  D->getEllipsisLoc()))
4471  std::tie(ToLoc, ToUsingLoc, ToQualifierLoc, ToEllipsisLoc) = *Imp;
4472  else
4473  return Imp.takeError();
4474 
4475  DeclarationNameInfo NameInfo(Name, ToLoc);
4476  if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4477  return std::move(Err);
4478 
4479  UnresolvedUsingValueDecl *ToUsingValue;
4480  if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
4481  ToUsingLoc, ToQualifierLoc, NameInfo,
4482  ToEllipsisLoc))
4483  return ToUsingValue;
4484 
4485  ToUsingValue->setAccess(D->getAccess());
4486  ToUsingValue->setLexicalDeclContext(LexicalDC);
4487  LexicalDC->addDeclInternal(ToUsingValue);
4488 
4489  return ToUsingValue;
4490 }
4491 
4494  DeclContext *DC, *LexicalDC;
4495  DeclarationName Name;
4496  SourceLocation Loc;
4497  NamedDecl *ToD = nullptr;
4498  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4499  return std::move(Err);
4500  if (ToD)
4501  return ToD;
4502 
4503  SourceLocation ToUsingLoc, ToTypenameLoc, ToEllipsisLoc;
4504  NestedNameSpecifierLoc ToQualifierLoc;
4505  if (auto Imp = importSeq(
4506  D->getUsingLoc(), D->getTypenameLoc(), D->getQualifierLoc(),
4507  D->getEllipsisLoc()))
4508  std::tie(ToUsingLoc, ToTypenameLoc, ToQualifierLoc, ToEllipsisLoc) = *Imp;
4509  else
4510  return Imp.takeError();
4511 
4512  UnresolvedUsingTypenameDecl *ToUsing;
4513  if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4514  ToUsingLoc, ToTypenameLoc,
4515  ToQualifierLoc, Loc, Name, ToEllipsisLoc))
4516  return ToUsing;
4517 
4518  ToUsing->setAccess(D->getAccess());
4519  ToUsing->setLexicalDeclContext(LexicalDC);
4520  LexicalDC->addDeclInternal(ToUsing);
4521 
4522  return ToUsing;
4523 }
4524 
4525 
4528  if (To->getDefinition()) {
4529  // Check consistency of superclass.
4530  ObjCInterfaceDecl *FromSuper = From->getSuperClass();
4531  if (FromSuper) {
4532  if (auto FromSuperOrErr = import(FromSuper))
4533  FromSuper = *FromSuperOrErr;
4534  else
4535  return FromSuperOrErr.takeError();
4536  }
4537 
4538  ObjCInterfaceDecl *ToSuper = To->getSuperClass();
4539  if ((bool)FromSuper != (bool)ToSuper ||
4540  (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
4541  Importer.ToDiag(To->getLocation(),
4542  diag::warn_odr_objc_superclass_inconsistent)
4543  << To->getDeclName();
4544  if (ToSuper)
4545  Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
4546  << To->getSuperClass()->getDeclName();
4547  else
4548  Importer.ToDiag(To->getLocation(),
4549  diag::note_odr_objc_missing_superclass);
4550  if (From->getSuperClass())
4551  Importer.FromDiag(From->getSuperClassLoc(),
4552  diag::note_odr_objc_superclass)
4553  << From->getSuperClass()->getDeclName();
4554  else
4555  Importer.FromDiag(From->getLocation(),
4556  diag::note_odr_objc_missing_superclass);
4557  }
4558 
4559  if (shouldForceImportDeclContext(Kind))
4560  if (Error Err = ImportDeclContext(From))
4561  return Err;
4562  return Error::success();
4563  }
4564 
4565  // Start the definition.
4566  To->startDefinition();
4567 
4568  // If this class has a superclass, import it.
4569  if (From->getSuperClass()) {
4570  if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo()))
4571  To->setSuperClass(*SuperTInfoOrErr);
4572  else
4573  return SuperTInfoOrErr.takeError();
4574  }
4575 
4576  // Import protocols
4578  SmallVector<SourceLocation, 4> ProtocolLocs;
4580  From->protocol_loc_begin();
4581 
4582  for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
4583  FromProtoEnd = From->protocol_end();
4584  FromProto != FromProtoEnd;
4585  ++FromProto, ++FromProtoLoc) {
4586  if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4587  Protocols.push_back(*ToProtoOrErr);
4588  else
4589  return ToProtoOrErr.takeError();
4590 
4591  if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4592  ProtocolLocs.push_back(*ToProtoLocOrErr);
4593  else
4594  return ToProtoLocOrErr.takeError();
4595 
4596  }
4597 
4598  // FIXME: If we're merging, make sure that the protocol list is the same.
4599  To->setProtocolList(Protocols.data(), Protocols.size(),
4600  ProtocolLocs.data(), Importer.getToContext());
4601 
4602  // Import categories. When the categories themselves are imported, they'll
4603  // hook themselves into this interface.
4604  for (auto *Cat : From->known_categories()) {
4605  auto ToCatOrErr = import(Cat);
4606  if (!ToCatOrErr)
4607  return ToCatOrErr.takeError();
4608  }
4609 
4610  // If we have an @implementation, import it as well.
4611  if (From->getImplementation()) {
4612  if (Expected<ObjCImplementationDecl *> ToImplOrErr =
4613  import(From->getImplementation()))
4614  To->setImplementation(*ToImplOrErr);
4615  else
4616  return ToImplOrErr.takeError();
4617  }
4618 
4619  if (shouldForceImportDeclContext(Kind)) {
4620  // Import all of the members of this class.
4621  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4622  return Err;
4623  }
4624  return Error::success();
4625 }
4626 
4629  if (!list)
4630  return nullptr;
4631 
4633  for (auto *fromTypeParam : *list) {
4634  if (auto toTypeParamOrErr = import(fromTypeParam))
4635  toTypeParams.push_back(*toTypeParamOrErr);
4636  else
4637  return toTypeParamOrErr.takeError();
4638  }
4639 
4640  auto LAngleLocOrErr = import(list->getLAngleLoc());
4641  if (!LAngleLocOrErr)
4642  return LAngleLocOrErr.takeError();
4643 
4644  auto RAngleLocOrErr = import(list->getRAngleLoc());
4645  if (!RAngleLocOrErr)
4646  return RAngleLocOrErr.takeError();
4647 
4648  return ObjCTypeParamList::create(Importer.getToContext(),
4649  *LAngleLocOrErr,
4650  toTypeParams,
4651  *RAngleLocOrErr);
4652 }
4653 
4655  // If this class has a definition in the translation unit we're coming from,
4656  // but this particular declaration is not that definition, import the
4657  // definition and map to that.
4658  ObjCInterfaceDecl *Definition = D->getDefinition();
4659  if (Definition && Definition != D) {
4660  if (ExpectedDecl ImportedDefOrErr = import(Definition))
4661  return Importer.MapImported(D, *ImportedDefOrErr);
4662  else
4663  return ImportedDefOrErr.takeError();
4664  }
4665 
4666  // Import the major distinguishing characteristics of an @interface.
4667  DeclContext *DC, *LexicalDC;
4668  DeclarationName Name;
4669  SourceLocation Loc;
4670  NamedDecl *ToD;
4671  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4672  return std::move(Err);
4673  if (ToD)
4674  return ToD;
4675 
4676  // Look for an existing interface with the same name.
4677  ObjCInterfaceDecl *MergeWithIface = nullptr;
4678  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4679  for (auto *FoundDecl : FoundDecls) {
4681  continue;
4682 
4683  if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
4684  break;
4685  }
4686 
4687  // Create an interface declaration, if one does not already exist.
4688  ObjCInterfaceDecl *ToIface = MergeWithIface;
4689  if (!ToIface) {
4690  ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc());
4691  if (!AtBeginLocOrErr)
4692  return AtBeginLocOrErr.takeError();
4693 
4694  if (GetImportedOrCreateDecl(
4695  ToIface, D, Importer.getToContext(), DC,
4696  *AtBeginLocOrErr, Name.getAsIdentifierInfo(),
4697  /*TypeParamList=*/nullptr,
4698  /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
4699  return ToIface;
4700  ToIface->setLexicalDeclContext(LexicalDC);
4701  LexicalDC->addDeclInternal(ToIface);
4702  }
4703  Importer.MapImported(D, ToIface);
4704  // Import the type parameter list after MapImported, to avoid
4705  // loops when bringing in their DeclContext.
4706  if (auto ToPListOrErr =
4707  ImportObjCTypeParamList(D->getTypeParamListAsWritten()))
4708  ToIface->setTypeParamList(*ToPListOrErr);
4709  else
4710  return ToPListOrErr.takeError();
4711 
4713  if (Error Err = ImportDefinition(D, ToIface))
4714  return std::move(Err);
4715 
4716  return ToIface;
4717 }
4718 
4722  if (Error Err = importInto(Category, D->getCategoryDecl()))
4723  return std::move(Err);
4724 
4725  ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
4726  if (!ToImpl) {
4727  DeclContext *DC, *LexicalDC;
4728  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4729  return std::move(Err);
4730 
4731  SourceLocation ToLocation, ToAtStartLoc, ToCategoryNameLoc;
4732  if (auto Imp = importSeq(
4733  D->getLocation(), D->getAtStartLoc(), D->getCategoryNameLoc()))
4734  std::tie(ToLocation, ToAtStartLoc, ToCategoryNameLoc) = *Imp;
4735  else
4736  return Imp.takeError();
4737 
4738  if (GetImportedOrCreateDecl(
4739  ToImpl, D, Importer.getToContext(), DC,
4740  Importer.Import(D->getIdentifier()), Category->getClassInterface(),
4741  ToLocation, ToAtStartLoc, ToCategoryNameLoc))
4742  return ToImpl;
4743 
4744  ToImpl->setLexicalDeclContext(LexicalDC);
4745  LexicalDC->addDeclInternal(ToImpl);
4746  Category->setImplementation(ToImpl);
4747  }
4748 
4749  Importer.MapImported(D, ToImpl);
4750  if (Error Err = ImportDeclContext(D))
4751  return std::move(Err);
4752 
4753  return ToImpl;
4754 }
4755 
4758  // Find the corresponding interface.
4759  ObjCInterfaceDecl *Iface;
4760  if (Error Err = importInto(Iface, D->getClassInterface()))
4761  return std::move(Err);
4762 
4763  // Import the superclass, if any.
4764  ObjCInterfaceDecl *Super;
4765  if (Error Err = importInto(Super, D->getSuperClass()))
4766  return std::move(Err);
4767 
4768  ObjCImplementationDecl *Impl = Iface->getImplementation();
4769  if (!Impl) {
4770  // We haven't imported an implementation yet. Create a new @implementation
4771  // now.
4772  DeclContext *DC, *LexicalDC;
4773  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4774  return std::move(Err);
4775 
4776  SourceLocation ToLocation, ToAtStartLoc, ToSuperClassLoc;
4777  SourceLocation ToIvarLBraceLoc, ToIvarRBraceLoc;
4778  if (auto Imp = importSeq(
4779  D->getLocation(), D->getAtStartLoc(), D->getSuperClassLoc(),
4780  D->getIvarLBraceLoc(), D->getIvarRBraceLoc()))
4781  std::tie(
4782  ToLocation, ToAtStartLoc, ToSuperClassLoc,
4783  ToIvarLBraceLoc, ToIvarRBraceLoc) = *Imp;
4784  else
4785  return Imp.takeError();
4786 
4787  if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
4788  DC, Iface, Super,
4789  ToLocation,
4790  ToAtStartLoc,
4791  ToSuperClassLoc,
4792  ToIvarLBraceLoc,
4793  ToIvarRBraceLoc))
4794  return Impl;
4795 
4796  Impl->setLexicalDeclContext(LexicalDC);
4797 
4798  // Associate the implementation with the class it implements.
4799  Iface->setImplementation(Impl);
4800  Importer.MapImported(D, Iface->getImplementation());
4801  } else {
4802  Importer.MapImported(D, Iface->getImplementation());
4803 
4804  // Verify that the existing @implementation has the same superclass.
4805  if ((Super && !Impl->getSuperClass()) ||
4806  (!Super && Impl->getSuperClass()) ||
4807  (Super && Impl->getSuperClass() &&
4809  Impl->getSuperClass()))) {
4810  Importer.ToDiag(Impl->getLocation(),
4811  diag::warn_odr_objc_superclass_inconsistent)
4812  << Iface->getDeclName();
4813  // FIXME: It would be nice to have the location of the superclass
4814  // below.
4815  if (Impl->getSuperClass())
4816  Importer.ToDiag(Impl->getLocation(),
4817  diag::note_odr_objc_superclass)
4818  << Impl->getSuperClass()->getDeclName();
4819  else
4820  Importer.ToDiag(Impl->getLocation(),
4821  diag::note_odr_objc_missing_superclass);
4822  if (D->getSuperClass())
4823  Importer.FromDiag(D->getLocation(),
4824  diag::note_odr_objc_superclass)
4825  << D->getSuperClass()->getDeclName();
4826  else
4827  Importer.FromDiag(D->getLocation(),
4828  diag::note_odr_objc_missing_superclass);
4829 
4830  return make_error<ImportError>(ImportError::NameConflict);
4831  }
4832  }
4833 
4834  // Import all of the members of this @implementation.
4835  if (Error Err = ImportDeclContext(D))
4836  return std::move(Err);
4837 
4838  return Impl;
4839 }
4840 
4842  // Import the major distinguishing characteristics of an @property.
4843  DeclContext *DC, *LexicalDC;
4844  DeclarationName Name;
4845  SourceLocation Loc;
4846  NamedDecl *ToD;
4847  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4848  return std::move(Err);
4849  if (ToD)
4850  return ToD;
4851 
4852  // Check whether we have already imported this property.
4853  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4854  for (auto *FoundDecl : FoundDecls) {
4855  if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) {
4856  // Check property types.
4857  if (!Importer.IsStructurallyEquivalent(D->getType(),
4858  FoundProp->getType())) {
4859  Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent)
4860  << Name << D->getType() << FoundProp->getType();
4861  Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
4862  << FoundProp->getType();
4863 
4864  return make_error<ImportError>(ImportError::NameConflict);
4865  }
4866 
4867  // FIXME: Check property attributes, getters, setters, etc.?
4868 
4869  // Consider these properties to be equivalent.
4870  Importer.MapImported(D, FoundProp);
4871  return FoundProp;
4872  }
4873  }
4874 
4875  QualType ToType;
4876  TypeSourceInfo *ToTypeSourceInfo;
4877  SourceLocation ToAtLoc, ToLParenLoc;
4878  if (auto Imp = importSeq(
4879  D->getType(), D->getTypeSourceInfo(), D->getAtLoc(), D->getLParenLoc()))
4880  std::tie(ToType, ToTypeSourceInfo, ToAtLoc, ToLParenLoc) = *Imp;
4881  else
4882  return Imp.takeError();
4883 
4884  // Create the new property.
4885  ObjCPropertyDecl *ToProperty;
4886  if (GetImportedOrCreateDecl(
4887  ToProperty, D, Importer.getToContext(), DC, Loc,
4888  Name.getAsIdentifierInfo(), ToAtLoc,
4889  ToLParenLoc, ToType,
4890  ToTypeSourceInfo, D->getPropertyImplementation()))
4891  return ToProperty;
4892 
4893  Selector ToGetterName, ToSetterName;
4894  SourceLocation ToGetterNameLoc, ToSetterNameLoc;
4895  ObjCMethodDecl *ToGetterMethodDecl, *ToSetterMethodDecl;
4896  ObjCIvarDecl *ToPropertyIvarDecl;
4897  if (auto Imp = importSeq(
4898  D->getGetterName(), D->getSetterName(),
4901  D->getPropertyIvarDecl()))
4902  std::tie(
4903  ToGetterName, ToSetterName,
4904  ToGetterNameLoc, ToSetterNameLoc,
4905  ToGetterMethodDecl, ToSetterMethodDecl,
4906  ToPropertyIvarDecl) = *Imp;
4907  else
4908  return Imp.takeError();
4909 
4910  ToProperty->setLexicalDeclContext(LexicalDC);
4911  LexicalDC->addDeclInternal(ToProperty);
4912 
4913  ToProperty->setPropertyAttributes(D->getPropertyAttributes());
4914  ToProperty->setPropertyAttributesAsWritten(
4916  ToProperty->setGetterName(ToGetterName, ToGetterNameLoc);
4917  ToProperty->setSetterName(ToSetterName, ToSetterNameLoc);
4918  ToProperty->setGetterMethodDecl(ToGetterMethodDecl);
4919  ToProperty->setSetterMethodDecl(ToSetterMethodDecl);
4920  ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl);
4921  return ToProperty;
4922 }
4923 
4927  if (Error Err = importInto(Property, D->getPropertyDecl()))
4928  return std::move(Err);
4929 
4930  DeclContext *DC, *LexicalDC;
4931  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4932  return std::move(Err);
4933 
4934  auto *InImpl = cast<ObjCImplDecl>(LexicalDC);
4935 
4936  // Import the ivar (for an @synthesize).
4937  ObjCIvarDecl *Ivar = nullptr;
4938  if (Error Err = importInto(Ivar, D->getPropertyIvarDecl()))
4939  return std::move(Err);
4940 
4941  ObjCPropertyImplDecl *ToImpl
4942  = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
4943  Property->getQueryKind());
4944  if (!ToImpl) {
4945  SourceLocation ToBeginLoc, ToLocation, ToPropertyIvarDeclLoc;
4946  if (auto Imp = importSeq(
4948  std::tie(ToBeginLoc, ToLocation, ToPropertyIvarDeclLoc) = *Imp;
4949  else
4950  return Imp.takeError();
4951 
4952  if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC,
4953  ToBeginLoc,
4954  ToLocation, Property,
4955  D->getPropertyImplementation(), Ivar,
4956  ToPropertyIvarDeclLoc))
4957  return ToImpl;
4958 
4959  ToImpl->setLexicalDeclContext(LexicalDC);
4960  LexicalDC->addDeclInternal(ToImpl);
4961  } else {
4962  // Check that we have the same kind of property implementation (@synthesize
4963  // vs. @dynamic).
4964  if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
4965  Importer.ToDiag(ToImpl->getLocation(),
4966  diag::warn_odr_objc_property_impl_kind_inconsistent)
4967  << Property->getDeclName()
4968  << (ToImpl->getPropertyImplementation()
4970  Importer.FromDiag(D->getLocation(),
4971  diag::note_odr_objc_property_impl_kind)
4972  << D->getPropertyDecl()->getDeclName()
4974 
4975  return make_error<ImportError>(ImportError::NameConflict);
4976  }
4977 
4978  // For @synthesize, check that we have the same
4980  Ivar != ToImpl->getPropertyIvarDecl()) {
4981  Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
4982  diag::warn_odr_objc_synthesize_ivar_inconsistent)
4983  << Property->getDeclName()
4984  << ToImpl->getPropertyIvarDecl()->getDeclName()
4985  << Ivar->getDeclName();
4986  Importer.FromDiag(D->getPropertyIvarDeclLoc(),
4987  diag::note_odr_objc_synthesize_ivar_here)
4988  << D->getPropertyIvarDecl()->getDeclName();
4989 
4990  return make_error<ImportError>(ImportError::NameConflict);
4991  }
4992 
4993  // Merge the existing implementation with the new implementation.
4994  Importer.MapImported(D, ToImpl);
4995  }
4996 
4997  return ToImpl;
4998 }
4999 
5002  // For template arguments, we adopt the translation unit as our declaration
5003  // context. This context will be fixed when the actual template declaration
5004  // is created.
5005 
5006  // FIXME: Import default argument.
5007 
5008  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5009  if (!BeginLocOrErr)
5010  return BeginLocOrErr.takeError();
5011 
5012  ExpectedSLoc LocationOrErr = import(D->getLocation());
5013  if (!LocationOrErr)
5014  return LocationOrErr.takeError();
5015 
5016  TemplateTypeParmDecl *ToD = nullptr;
5017  (void)GetImportedOrCreateDecl(
5018  ToD, D, Importer.getToContext(),
5019  Importer.getToContext().getTranslationUnitDecl(),
5020  *BeginLocOrErr, *LocationOrErr,
5021  D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()),
5023  return ToD;
5024 }
5025 
5028  DeclarationName ToDeclName;
5029  SourceLocation ToLocation, ToInnerLocStart;
5030  QualType ToType;
5031  TypeSourceInfo *ToTypeSourceInfo;
5032  if (auto Imp = importSeq(
5033  D->getDeclName(), D->getLocation(), D->getType(), D->getTypeSourceInfo(),
5034  D->getInnerLocStart()))
5035  std::tie(
5036  ToDeclName, ToLocation, ToType, ToTypeSourceInfo,
5037  ToInnerLocStart) = *Imp;
5038  else
5039  return Imp.takeError();
5040 
5041  // FIXME: Import default argument.
5042 
5043  NonTypeTemplateParmDecl *ToD = nullptr;
5044  (void)GetImportedOrCreateDecl(
5045  ToD, D, Importer.getToContext(),
5046  Importer.getToContext().getTranslationUnitDecl(),
5047  ToInnerLocStart, ToLocation, D->getDepth(),
5048  D->getPosition(), ToDeclName.getAsIdentifierInfo(), ToType,
5049  D->isParameterPack(), ToTypeSourceInfo);
5050  return ToD;
5051 }
5052 
5055  // Import the name of this declaration.
5056  auto NameOrErr = import(D->getDeclName());
5057  if (!NameOrErr)
5058  return NameOrErr.takeError();
5059 
5060  // Import the location of this declaration.
5061  ExpectedSLoc LocationOrErr = import(D->getLocation());
5062  if (!LocationOrErr)
5063  return LocationOrErr.takeError();
5064 
5065  // Import template parameters.
5066  auto TemplateParamsOrErr = import(D->getTemplateParameters());
5067  if (!TemplateParamsOrErr)
5068  return TemplateParamsOrErr.takeError();
5069 
5070  // FIXME: Import default argument.
5071 
5072  TemplateTemplateParmDecl *ToD = nullptr;
5073  (void)GetImportedOrCreateDecl(
5074  ToD, D, Importer.getToContext(),
5075  Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr,
5076  D->getDepth(), D->getPosition(), D->isParameterPack(),
5077  (*NameOrErr).getAsIdentifierInfo(),
5078  *TemplateParamsOrErr);
5079  return ToD;
5080 }
5081 
5082 // Returns the definition for a (forward) declaration of a TemplateDecl, if
5083 // it has any definition in the redecl chain.
5084 template <typename T> static auto getTemplateDefinition(T *D) -> T * {
5085  assert(D->getTemplatedDecl() && "Should be called on templates only");
5086  auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
5087  if (!ToTemplatedDef)
5088  return nullptr;
5089  auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate();
5090  return cast_or_null<T>(TemplateWithDef);
5091 }
5092 
5094  bool IsFriend = D->getFriendObjectKind() != Decl::FOK_None;
5095 
5096  // Import the major distinguishing characteristics of this class template.
5097  DeclContext *DC, *LexicalDC;
5098  DeclarationName Name;
5099  SourceLocation Loc;
5100  NamedDecl *ToD;
5101  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5102  return std::move(Err);
5103  if (ToD)
5104  return ToD;
5105 
5106  ClassTemplateDecl *FoundByLookup = nullptr;
5107 
5108  // We may already have a template of the same name; try to find and match it.
5109  if (!DC->isFunctionOrMethod()) {
5110  SmallVector<NamedDecl *, 4> ConflictingDecls;
5111  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5112  for (auto *FoundDecl : FoundDecls) {
5115  continue;
5116 
5117  Decl *Found = FoundDecl;
5118  auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found);
5119  if (FoundTemplate) {
5120 
5121  if (IsStructuralMatch(D, FoundTemplate)) {
5122  ClassTemplateDecl *TemplateWithDef =
5123  getTemplateDefinition(FoundTemplate);
5124  if (D->isThisDeclarationADefinition() && TemplateWithDef)
5125  return Importer.MapImported(D, TemplateWithDef);
5126  if (!FoundByLookup)
5127  FoundByLookup = FoundTemplate;
5128  // Search in all matches because there may be multiple decl chains,
5129  // see ASTTests test ImportExistingFriendClassTemplateDef.
5130  continue;
5131  }
5132  ConflictingDecls.push_back(FoundDecl);
5133  }
5134  }
5135 
5136  if (!ConflictingDecls.empty()) {
5137  ExpectedName NameOrErr = Importer.HandleNameConflict(
5138  Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
5139  ConflictingDecls.size());
5140  if (NameOrErr)
5141  Name = NameOrErr.get();
5142  else
5143  return NameOrErr.takeError();
5144  }
5145  }
5146 
5147  CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
5148 
5149  // Create the declaration that is being templated.
5150  CXXRecordDecl *ToTemplated;
5151  if (Error Err = importInto(ToTemplated, FromTemplated))
5152  return std::move(Err);
5153 
5154  // Create the class template declaration itself.
5155  auto TemplateParamsOrErr = import(D->getTemplateParameters());
5156  if (!TemplateParamsOrErr)
5157  return TemplateParamsOrErr.takeError();
5158 
5159  ClassTemplateDecl *D2;
5160  if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name,
5161  *TemplateParamsOrErr, ToTemplated))
5162  return D2;
5163 
5164  ToTemplated->setDescribedClassTemplate(D2);
5165 
5166  D2->setAccess(D->getAccess());
5167  D2->setLexicalDeclContext(LexicalDC);
5168 
5169  if (D->getDeclContext()->containsDeclAndLoad(D))
5170  DC->addDeclInternal(D2);
5171  if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
5172  LexicalDC->addDeclInternal(D2);
5173 
5174  if (FoundByLookup) {
5175  auto *Recent =
5176  const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5177 
5178  // It is possible that during the import of the class template definition
5179  // we start the import of a fwd friend decl of the very same class template
5180  // and we add the fwd friend decl to the lookup table. But the ToTemplated
5181  // had been created earlier and by that time the lookup could not find
5182  // anything existing, so it has no previous decl. Later, (still during the
5183  // import of the fwd friend decl) we start to import the definition again
5184  // and this time the lookup finds the previous fwd friend class template.
5185  // In this case we must set up the previous decl for the templated decl.
5186  if (!ToTemplated->getPreviousDecl()) {
5187  assert(FoundByLookup->getTemplatedDecl() &&
5188  "Found decl must have its templated decl set");
5189  CXXRecordDecl *PrevTemplated =
5190  FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5191  if (ToTemplated != PrevTemplated)
5192  ToTemplated->setPreviousDecl(PrevTemplated);
5193  }
5194 
5195  D2->setPreviousDecl(Recent);
5196  }
5197 
5198  if (LexicalDC != DC && IsFriend)
5199  DC->makeDeclVisibleInContext(D2);
5200 
5201  if (FromTemplated->isCompleteDefinition() &&
5202  !ToTemplated->isCompleteDefinition()) {
5203  // FIXME: Import definition!
5204  }
5205 
5206  return D2;
5207 }
5208 
5211  ClassTemplateDecl *ClassTemplate;
5212  if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate()))
5213  return std::move(Err);
5214 
5215  // Import the context of this declaration.
5216  DeclContext *DC, *LexicalDC;
5217  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5218  return std::move(Err);
5219 
5220  // Import template arguments.
5221  SmallVector<TemplateArgument, 2> TemplateArgs;
5222  if (Error Err = ImportTemplateArguments(
5223  D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5224  return std::move(Err);
5225 
5226  // Try to find an existing specialization with these template arguments.
5227  void *InsertPos = nullptr;
5228  ClassTemplateSpecializationDecl *PrevDecl = nullptr;
5231  if (PartialSpec)
5232  PrevDecl =
5233  ClassTemplate->findPartialSpecialization(TemplateArgs, InsertPos);
5234  else
5235  PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
5236 
5237  if (PrevDecl) {
5238  if (IsStructuralMatch(D, PrevDecl)) {
5239  if (D->isThisDeclarationADefinition() && PrevDecl->getDefinition()) {
5240  Importer.MapImported(D, PrevDecl->getDefinition());
5241  // Import those default field initializers which have been
5242  // instantiated in the "From" context, but not in the "To" context.
5243  for (auto *FromField : D->fields()) {
5244  auto ToOrErr = import(FromField);
5245  if (!ToOrErr)
5246  return ToOrErr.takeError();
5247  }
5248 
5249  // Import those methods which have been instantiated in the
5250  // "From" context, but not in the "To" context.
5251  for (CXXMethodDecl *FromM : D->methods()) {
5252  auto ToOrErr = import(FromM);
5253  if (!ToOrErr)
5254  return ToOrErr.takeError();
5255  }
5256 
5257  // TODO Import instantiated default arguments.
5258  // TODO Import instantiated exception specifications.
5259  //
5260  // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint
5261  // what else could be fused during an AST merge.
5262  return PrevDecl;
5263  }
5264  } else { // ODR violation.
5265  // FIXME HandleNameConflict
5266  return make_error<ImportError>(ImportError::NameConflict);
5267  }
5268  }
5269 
5270  // Import the location of this declaration.
5271  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5272  if (!BeginLocOrErr)
5273  return BeginLocOrErr.takeError();
5274  ExpectedSLoc IdLocOrErr = import(D->getLocation());
5275  if (!IdLocOrErr)
5276  return IdLocOrErr.takeError();
5277 
5278  // Create the specialization.
5279  ClassTemplateSpecializationDecl *D2 = nullptr;
5280  if (PartialSpec) {
5281  // Import TemplateArgumentListInfo.
5282  TemplateArgumentListInfo ToTAInfo;
5283  const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
5284  if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo))
5285  return std::move(Err);
5286 
5287  QualType CanonInjType;
5288  if (Error Err = importInto(
5289  CanonInjType, PartialSpec->getInjectedSpecializationType()))
5290  return std::move(Err);
5291  CanonInjType = CanonInjType.getCanonicalType();
5292 
5293  auto ToTPListOrErr = import(PartialSpec->getTemplateParameters());
5294  if (!ToTPListOrErr)
5295  return ToTPListOrErr.takeError();
5296 
5297  if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
5298  D2, D, Importer.getToContext(), D->getTagKind(), DC,
5299  *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr, ClassTemplate,
5300  llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()),
5301  ToTAInfo, CanonInjType,
5302  cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl)))
5303  return D2;
5304 
5305  // Update InsertPos, because preceding import calls may have invalidated
5306  // it by adding new specializations.
5307  if (!ClassTemplate->findPartialSpecialization(TemplateArgs, InsertPos))
5308  // Add this partial specialization to the class template.
5309  ClassTemplate->AddPartialSpecialization(
5310  cast<ClassTemplatePartialSpecializationDecl>(D2), InsertPos);
5311 
5312  } else { // Not a partial specialization.
5313  if (GetImportedOrCreateDecl(
5314  D2, D, Importer.getToContext(), D->getTagKind(), DC,
5315  *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs,
5316  PrevDecl))
5317  return D2;
5318 
5319  // Update InsertPos, because preceding import calls may have invalidated
5320  // it by adding new specializations.
5321  if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos))
5322  // Add this specialization to the class template.
5323  ClassTemplate->AddSpecialization(D2, InsertPos);
5324  }
5325 
5327 
5328  // Set the context of this specialization/instantiation.
5329  D2->setLexicalDeclContext(LexicalDC);
5330 
5331  // Add to the DC only if it was an explicit specialization/instantiation.
5333  LexicalDC->addDeclInternal(D2);
5334  }
5335 
5336  // Import the qualifier, if any.
5337  if (auto LocOrErr = import(D->getQualifierLoc()))
5338  D2->setQualifierInfo(*LocOrErr);
5339  else
5340  return LocOrErr.takeError();
5341 
5342  if (auto *TSI = D->getTypeAsWritten()) {
5343  if (auto TInfoOrErr = import(TSI))
5344  D2->setTypeAsWritten(*TInfoOrErr);
5345  else
5346  return TInfoOrErr.takeError();
5347 
5348  if (auto LocOrErr = import(D->getTemplateKeywordLoc()))
5349  D2->setTemplateKeywordLoc(*LocOrErr);
5350  else
5351  return LocOrErr.takeError();
5352 
5353  if (auto LocOrErr = import(D->getExternLoc()))
5354  D2->setExternLoc(*LocOrErr);
5355  else
5356  return LocOrErr.takeError();
5357  }
5358 
5359  if (D->getPointOfInstantiation().isValid()) {
5360  if (auto POIOrErr = import(D->getPointOfInstantiation()))
5361  D2->setPointOfInstantiation(*POIOrErr);
5362  else
5363  return POIOrErr.takeError();
5364  }
5365 
5367 
5368  if (D->isCompleteDefinition())
5369  if (Error Err = ImportDefinition(D, D2))
5370  return std::move(Err);
5371 
5372  return D2;
5373 }
5374 
5376  // If this variable has a definition in the translation unit we're coming
5377  // from,
5378  // but this particular declaration is not that definition, import the
5379  // definition and map to that.
5380  auto *Definition =
5381  cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
5382  if (Definition && Definition != D->getTemplatedDecl()) {
5383  if (ExpectedDecl ImportedDefOrErr = import(
5384  Definition->getDescribedVarTemplate()))
5385  return Importer.MapImported(D, *ImportedDefOrErr);
5386  else
5387  return ImportedDefOrErr.takeError();
5388  }
5389 
5390  // Import the major distinguishing characteristics of this variable template.
5391  DeclContext *DC, *LexicalDC;
5392  DeclarationName Name;
5393  SourceLocation Loc;
5394  NamedDecl *ToD;
5395  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5396  return std::move(Err);
5397  if (ToD)
5398  return ToD;
5399 
5400  // We may already have a template of the same name; try to find and match it.
5401  assert(!DC->isFunctionOrMethod() &&
5402  "Variable templates cannot be declared at function scope");
5403  SmallVector<NamedDecl *, 4> ConflictingDecls;
5404  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5405  for (auto *FoundDecl : FoundDecls) {
5407  continue;
5408 
5409  Decl *Found = FoundDecl;
5410  if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
5411  if (IsStructuralMatch(D, FoundTemplate)) {
5412  // The variable templates structurally match; call it the same template.
5413  Importer.MapImported(D->getTemplatedDecl(),
5414  FoundTemplate->getTemplatedDecl());
5415  return Importer.MapImported(D, FoundTemplate);
5416  }
5417  ConflictingDecls.push_back(FoundDecl);
5418  }
5419  }
5420 
5421  if (!ConflictingDecls.empty()) {
5422  ExpectedName NameOrErr = Importer.HandleNameConflict(
5423  Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
5424  ConflictingDecls.size());
5425  if (NameOrErr)
5426  Name = NameOrErr.get();
5427  else
5428  return NameOrErr.takeError();
5429  }
5430 
5431  VarDecl *DTemplated = D->getTemplatedDecl();
5432 
5433  // Import the type.
5434  // FIXME: Value not used?
5435  ExpectedType TypeOrErr = import(DTemplated->getType());
5436  if (!TypeOrErr)
5437  return TypeOrErr.takeError();
5438 
5439  // Create the declaration that is being templated.
5440  VarDecl *ToTemplated;
5441  if (Error Err = importInto(ToTemplated, DTemplated))
5442  return std::move(Err);
5443 
5444  // Create the variable template declaration itself.
5445  auto TemplateParamsOrErr = import(D->getTemplateParameters());
5446  if (!TemplateParamsOrErr)
5447  return TemplateParamsOrErr.takeError();
5448 
5449  VarTemplateDecl *ToVarTD;
5450  if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc,
5451  Name, *TemplateParamsOrErr, ToTemplated))
5452  return ToVarTD;
5453 
5454  ToTemplated->setDescribedVarTemplate(ToVarTD);
5455 
5456  ToVarTD->setAccess(D->getAccess());
5457  ToVarTD->setLexicalDeclContext(LexicalDC);
5458  LexicalDC->addDeclInternal(ToVarTD);
5459 
5460  if (DTemplated->isThisDeclarationADefinition() &&
5461  !ToTemplated->isThisDeclarationADefinition()) {
5462  // FIXME: Import definition!
5463  }
5464 
5465  return ToVarTD;
5466 }
5467 
5470  // If this record has a definition in the translation unit we're coming from,
5471  // but this particular declaration is not that definition, import the
5472  // definition and map to that.
5473  VarDecl *Definition = D->getDefinition();
5474  if (Definition && Definition != D) {
5475  if (ExpectedDecl ImportedDefOrErr = import(Definition))
5476  return Importer.MapImported(D, *ImportedDefOrErr);
5477  else
5478  return ImportedDefOrErr.takeError();
5479  }
5480 
5481  VarTemplateDecl *VarTemplate = nullptr;
5482  if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate()))
5483  return std::move(Err);
5484 
5485  // Import the context of this declaration.
5486  DeclContext *DC, *LexicalDC;
5487  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5488  return std::move(Err);
5489 
5490  // Import the location of this declaration.
5491  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5492  if (!BeginLocOrErr)
5493  return BeginLocOrErr.takeError();
5494 
5495  auto IdLocOrErr = import(D->getLocation());
5496  if (!IdLocOrErr)
5497  return IdLocOrErr.takeError();
5498 
5499  // Import template arguments.
5500  SmallVector<TemplateArgument, 2> TemplateArgs;
5501  if (Error Err = ImportTemplateArguments(
5502  D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5503  return std::move(Err);
5504 
5505  // Try to find an existing specialization with these template arguments.
5506  void *InsertPos = nullptr;
5508  TemplateArgs, InsertPos);
5509  if (D2) {
5510  // We already have a variable template specialization with these template
5511  // arguments.
5512 
5513  // FIXME: Check for specialization vs. instantiation errors.
5514 
5515  if (VarDecl *FoundDef = D2->getDefinition()) {
5516  if (!D->isThisDeclarationADefinition() ||
5517  IsStructuralMatch(D, FoundDef)) {
5518  // The record types structurally match, or the "from" translation
5519  // unit only had a forward declaration anyway; call it the same
5520  // variable.
5521  return Importer.MapImported(D, FoundDef);
5522  }
5523  }
5524  } else {
5525  // Import the type.
5526  QualType T;
5527  if (Error Err = importInto(T, D->getType()))
5528  return std::move(Err);
5529 
5530  auto TInfoOrErr = import(D->getTypeSourceInfo());
5531  if (!TInfoOrErr)
5532  return TInfoOrErr.takeError();
5533 
5534  TemplateArgumentListInfo ToTAInfo;
5535  if (Error Err = ImportTemplateArgumentListInfo(
5536  D->getTemplateArgsInfo(), ToTAInfo))
5537  return std::move(Err);
5538 
5539  using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
5540  // Create a new specialization.
5541  if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) {
5542  // Import TemplateArgumentListInfo
5543  TemplateArgumentListInfo ArgInfos;
5544  const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten();
5545  // NOTE: FromTAArgsAsWritten and template parameter list are non-null.
5546  if (Error Err = ImportTemplateArgumentListInfo(
5547  *FromTAArgsAsWritten, ArgInfos))
5548  return std::move(Err);
5549 
5550  auto ToTPListOrErr = import(FromPartial->getTemplateParameters());
5551  if (!ToTPListOrErr)
5552  return ToTPListOrErr.takeError();
5553 
5554  PartVarSpecDecl *ToPartial;
5555  if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC,
5556  *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr,
5557  VarTemplate, T, *TInfoOrErr,
5558  D->getStorageClass(), TemplateArgs, ArgInfos))
5559  return ToPartial;
5560 
5561  if (Expected<PartVarSpecDecl *> ToInstOrErr = import(
5562  FromPartial->getInstantiatedFromMember()))
5563  ToPartial->setInstantiatedFromMember(*ToInstOrErr);
5564  else
5565  return ToInstOrErr.takeError();
5566 
5567  if (FromPartial->isMemberSpecialization())
5568  ToPartial->setMemberSpecialization();
5569 
5570  D2 = ToPartial;
5571 
5572  } else { // Full specialization
5573  if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC,
5574  *BeginLocOrErr, *IdLocOrErr, VarTemplate,
5575  T, *TInfoOrErr,
5576  D->getStorageClass(), TemplateArgs))
5577  return D2;
5578  }
5579 
5580  if (D->getPointOfInstantiation().isValid()) {
5581  if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation()))
5582  D2->setPointOfInstantiation(*POIOrErr);
5583  else
5584  return POIOrErr.takeError();
5585  }
5586 
5588  D2->setTemplateArgsInfo(ToTAInfo);
5589 
5590  // Add this specialization to the class template.
5591  VarTemplate->AddSpecialization(D2, InsertPos);
5592 
5593  // Import the qualifier, if any.
5594  if (auto LocOrErr = import(D->getQualifierLoc()))
5595  D2->setQualifierInfo(*LocOrErr);
5596  else
5597  return LocOrErr.takeError();
5598 
5599  if (D->isConstexpr())
5600  D2->setConstexpr(true);
5601 
5602  // Add the specialization to this context.
5603  D2->setLexicalDeclContext(LexicalDC);
5604  LexicalDC->addDeclInternal(D2);
5605 
5606  D2->setAccess(D->getAccess());
5607  }
5608 
5609  if (Error Err = ImportInitializer(D, D2))
5610  return std::move(Err);
5611 
5612  return D2;
5613 }
5614 
5617  DeclContext *DC, *LexicalDC;
5618  DeclarationName Name;
5619  SourceLocation Loc;
5620  NamedDecl *ToD;
5621 
5622  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5623  return std::move(Err);
5624 
5625  if (ToD)
5626  return ToD;
5627 
5628  const FunctionTemplateDecl *FoundByLookup = nullptr;
5629 
5630  // Try to find a function in our own ("to") context with the same name, same
5631  // type, and in the same context as the function we're importing.
5632  // FIXME Split this into a separate function.
5633  if (!LexicalDC->isFunctionOrMethod()) {
5635  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5636  for (auto *FoundDecl : FoundDecls) {
5637  if (!FoundDecl->isInIdentifierNamespace(IDNS))
5638  continue;
5639 
5640  if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(FoundDecl)) {
5641  if (!hasSameVisibilityContext(FoundTemplate, D))
5642  continue;
5643  if (IsStructuralMatch(D, FoundTemplate)) {
5644  FunctionTemplateDecl *TemplateWithDef =
5645  getTemplateDefinition(FoundTemplate);
5646  if (D->isThisDeclarationADefinition() && TemplateWithDef)
5647  return Importer.MapImported(D, TemplateWithDef);
5648 
5649  FoundByLookup = FoundTemplate;
5650  break;
5651  // TODO: handle conflicting names
5652  }
5653  }
5654  }
5655  }
5656 
5657  auto ParamsOrErr = import(D->getTemplateParameters());
5658  if (!ParamsOrErr)
5659  return ParamsOrErr.takeError();
5660 
5661  FunctionDecl *TemplatedFD;
5662  if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl()))
5663  return std::move(Err);
5664 
5665  FunctionTemplateDecl *ToFunc;
5666  if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name,
5667  *ParamsOrErr, TemplatedFD))
5668  return ToFunc;
5669 
5670  TemplatedFD->setDescribedFunctionTemplate(ToFunc);
5671 
5672  ToFunc->setAccess(D->getAccess());
5673  ToFunc->setLexicalDeclContext(LexicalDC);
5674  LexicalDC->addDeclInternal(ToFunc);
5675 
5676  if (FoundByLookup) {
5677  auto *Recent =
5678  const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5679  if (!TemplatedFD->getPreviousDecl()) {
5680  assert(FoundByLookup->getTemplatedDecl() &&
5681  "Found decl must have its templated decl set");
5682  auto *PrevTemplated =
5683  FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5684  if (TemplatedFD != PrevTemplated)
5685  TemplatedFD->setPreviousDecl(PrevTemplated);
5686  }
5687  ToFunc->setPreviousDecl(Recent);
5688  }
5689 
5690  return ToFunc;
5691 }
5692 
5693 //----------------------------------------------------------------------------
5694 // Import Statements
5695 //----------------------------------------------------------------------------
5696 
5698  Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node)
5699  << S->getStmtClassName();
5700  return make_error<ImportError>(ImportError::UnsupportedConstruct);
5701 }
5702 
5703 
5705  if (Importer.returnWithErrorInTest())
5706  return make_error<ImportError>(ImportError::UnsupportedConstruct);
5708  for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5709  IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
5710  // ToII is nullptr when no symbolic name is given for output operand
5711  // see ParseStmtAsm::ParseAsmOperandsOpt
5712  Names.push_back(ToII);
5713  }
5714 
5715  for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
5716  IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
5717  // ToII is nullptr when no symbolic name is given for input operand
5718  // see ParseStmtAsm::ParseAsmOperandsOpt
5719  Names.push_back(ToII);
5720  }
5721 
5723  for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
5724  if (auto ClobberOrErr = import(S->getClobberStringLiteral(I)))
5725  Clobbers.push_back(*ClobberOrErr);
5726  else
5727  return ClobberOrErr.takeError();
5728 
5729  }
5730 
5731  SmallVector<StringLiteral *, 4> Constraints;
5732  for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5733  if (auto OutputOrErr = import(S->getOutputConstraintLiteral(I)))
5734  Constraints.push_back(*OutputOrErr);
5735  else
5736  return OutputOrErr.takeError();
5737  }
5738 
5739  for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
5740  if (auto InputOrErr = import(S->getInputConstraintLiteral(I)))
5741  Constraints.push_back(*InputOrErr);
5742  else
5743  return InputOrErr.takeError();
5744  }
5745 
5747  S->getNumLabels());
5748  if (Error Err = ImportContainerChecked(S->outputs(), Exprs))
5749  return std::move(Err);
5750 
5751  if (Error Err =
5752  ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
5753  return std::move(Err);
5754 
5755  if (Error Err = ImportArrayChecked(
5756  S->labels(), Exprs.begin() + S->getNumOutputs() + S->getNumInputs()))
5757  return std::move(Err);
5758 
5759  ExpectedSLoc AsmLocOrErr = import(S->getAsmLoc());
5760  if (!AsmLocOrErr)
5761  return AsmLocOrErr.takeError();
5762  auto AsmStrOrErr = import(S->getAsmString());
5763  if (!AsmStrOrErr)
5764  return AsmStrOrErr.takeError();
5765  ExpectedSLoc RParenLocOrErr = import(S->getRParenLoc());
5766  if (!RParenLocOrErr)
5767  return RParenLocOrErr.takeError();
5768 
5769  return new (Importer.getToContext()) GCCAsmStmt(
5770  Importer.getToContext(),
5771  *AsmLocOrErr,
5772  S->isSimple(),
5773  S->isVolatile(),
5774  S->getNumOutputs(),
5775  S->getNumInputs(),
5776  Names.data(),
5777  Constraints.data(),
5778  Exprs.data(),
5779