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  QualType ToElementType;
1102  const Expr *ToSizeExpr;
1103  if (auto Imp = importSeq(T->getElementType(), T->getSizeExpr()))
1104  std::tie(ToElementType, ToSizeExpr) = *Imp;
1105  else
1106  return Imp.takeError();
1107 
1108  return Importer.getToContext().getConstantArrayType(
1109  ToElementType, T->getSize(), ToSizeExpr, T->getSizeModifier(),
1111 }
1112 
1115  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1116  if (!ToElementTypeOrErr)
1117  return ToElementTypeOrErr.takeError();
1118 
1119  return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr,
1120  T->getSizeModifier(),
1122 }
1123 
1126  QualType ToElementType;
1127  Expr *ToSizeExpr;
1128  SourceRange ToBracketsRange;
1129  if (auto Imp = importSeq(
1130  T->getElementType(), T->getSizeExpr(), T->getBracketsRange()))
1131  std::tie(ToElementType, ToSizeExpr, ToBracketsRange) = *Imp;
1132  else
1133  return Imp.takeError();
1134 
1135  return Importer.getToContext().getVariableArrayType(
1136  ToElementType, ToSizeExpr, T->getSizeModifier(),
1137  T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1138 }
1139 
1141  const DependentSizedArrayType *T) {
1142  QualType ToElementType;
1143  Expr *ToSizeExpr;
1144  SourceRange ToBracketsRange;
1145  if (auto Imp = importSeq(
1146  T->getElementType(), T->getSizeExpr(), T->getBracketsRange()))
1147  std::tie(ToElementType, ToSizeExpr, ToBracketsRange) = *Imp;
1148  else
1149  return Imp.takeError();
1150  // SizeExpr may be null if size is not specified directly.
1151  // For example, 'int a[]'.
1152 
1153  return Importer.getToContext().getDependentSizedArrayType(
1154  ToElementType, ToSizeExpr, T->getSizeModifier(),
1155  T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1156 }
1157 
1159  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1160  if (!ToElementTypeOrErr)
1161  return ToElementTypeOrErr.takeError();
1162 
1163  return Importer.getToContext().getVectorType(*ToElementTypeOrErr,
1164  T->getNumElements(),
1165  T->getVectorKind());
1166 }
1167 
1169  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1170  if (!ToElementTypeOrErr)
1171  return ToElementTypeOrErr.takeError();
1172 
1173  return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr,
1174  T->getNumElements());
1175 }
1176 
1179  // FIXME: What happens if we're importing a function without a prototype
1180  // into C++? Should we make it variadic?
1181  ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1182  if (!ToReturnTypeOrErr)
1183  return ToReturnTypeOrErr.takeError();
1184 
1185  return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
1186  T->getExtInfo());
1187 }
1188 
1191  ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1192  if (!ToReturnTypeOrErr)
1193  return ToReturnTypeOrErr.takeError();
1194 
1195  // Import argument types
1196  SmallVector<QualType, 4> ArgTypes;
1197  for (const auto &A : T->param_types()) {
1198  ExpectedType TyOrErr = import(A);
1199  if (!TyOrErr)
1200  return TyOrErr.takeError();
1201  ArgTypes.push_back(*TyOrErr);
1202  }
1203 
1204  // Import exception types
1205  SmallVector<QualType, 4> ExceptionTypes;
1206  for (const auto &E : T->exceptions()) {
1207  ExpectedType TyOrErr = import(E);
1208  if (!TyOrErr)
1209  return TyOrErr.takeError();
1210  ExceptionTypes.push_back(*TyOrErr);
1211  }
1212 
1215 
1216  auto Imp = importSeq(
1217  FromEPI.ExceptionSpec.NoexceptExpr,
1218  FromEPI.ExceptionSpec.SourceDecl,
1219  FromEPI.ExceptionSpec.SourceTemplate);
1220  if (!Imp)
1221  return Imp.takeError();
1222 
1223  ToEPI.ExtInfo = FromEPI.ExtInfo;
1224  ToEPI.Variadic = FromEPI.Variadic;
1225  ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1226  ToEPI.TypeQuals = FromEPI.TypeQuals;
1227  ToEPI.RefQualifier = FromEPI.RefQualifier;
1228  ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1229  ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1230  std::tie(
1232  ToEPI.ExceptionSpec.SourceDecl,
1233  ToEPI.ExceptionSpec.SourceTemplate) = *Imp;
1234 
1235  return Importer.getToContext().getFunctionType(
1236  *ToReturnTypeOrErr, ArgTypes, ToEPI);
1237 }
1238 
1240  const UnresolvedUsingType *T) {
1242  Decl *ToPrevD;
1243  if (auto Imp = importSeq(T->getDecl(), T->getDecl()->getPreviousDecl()))
1244  std::tie(ToD, ToPrevD) = *Imp;
1245  else
1246  return Imp.takeError();
1247 
1248  return Importer.getToContext().getTypeDeclType(
1249  ToD, cast_or_null<TypeDecl>(ToPrevD));
1250 }
1251 
1253  ExpectedType ToInnerTypeOrErr = import(T->getInnerType());
1254  if (!ToInnerTypeOrErr)
1255  return ToInnerTypeOrErr.takeError();
1256 
1257  return Importer.getToContext().getParenType(*ToInnerTypeOrErr);
1258 }
1259 
1261  Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl());
1262  if (!ToDeclOrErr)
1263  return ToDeclOrErr.takeError();
1264 
1265  return Importer.getToContext().getTypeDeclType(*ToDeclOrErr);
1266 }
1267 
1269  ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1270  if (!ToExprOrErr)
1271  return ToExprOrErr.takeError();
1272 
1273  return Importer.getToContext().getTypeOfExprType(*ToExprOrErr);
1274 }
1275 
1277  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1278  if (!ToUnderlyingTypeOrErr)
1279  return ToUnderlyingTypeOrErr.takeError();
1280 
1281  return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr);
1282 }
1283 
1285  // FIXME: Make sure that the "to" context supports C++0x!
1286  ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1287  if (!ToExprOrErr)
1288  return ToExprOrErr.takeError();
1289 
1290  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1291  if (!ToUnderlyingTypeOrErr)
1292  return ToUnderlyingTypeOrErr.takeError();
1293 
1294  return Importer.getToContext().getDecltypeType(
1295  *ToExprOrErr, *ToUnderlyingTypeOrErr);
1296 }
1297 
1300  ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1301  if (!ToBaseTypeOrErr)
1302  return ToBaseTypeOrErr.takeError();
1303 
1304  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1305  if (!ToUnderlyingTypeOrErr)
1306  return ToUnderlyingTypeOrErr.takeError();
1307 
1308  return Importer.getToContext().getUnaryTransformType(
1309  *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind());
1310 }
1311 
1313  // FIXME: Make sure that the "to" context supports C++11!
1314  ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1315  if (!ToDeducedTypeOrErr)
1316  return ToDeducedTypeOrErr.takeError();
1317 
1318  return Importer.getToContext().getAutoType(*ToDeducedTypeOrErr,
1319  T->getKeyword(),
1320  /*IsDependent*/false);
1321 }
1322 
1324  const InjectedClassNameType *T) {
1325  Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl());
1326  if (!ToDeclOrErr)
1327  return ToDeclOrErr.takeError();
1328 
1329  ExpectedType ToInjTypeOrErr = import(T->getInjectedSpecializationType());
1330  if (!ToInjTypeOrErr)
1331  return ToInjTypeOrErr.takeError();
1332 
1333  // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
1334  // See comments in InjectedClassNameType definition for details
1335  // return Importer.getToContext().getInjectedClassNameType(D, InjType);
1336  enum {
1337  TypeAlignmentInBits = 4,
1339  };
1340 
1341  return QualType(new (Importer.getToContext(), TypeAlignment)
1342  InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0);
1343 }
1344 
1346  Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl());
1347  if (!ToDeclOrErr)
1348  return ToDeclOrErr.takeError();
1349 
1350  return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1351 }
1352 
1354  Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl());
1355  if (!ToDeclOrErr)
1356  return ToDeclOrErr.takeError();
1357 
1358  return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1359 }
1360 
1362  ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType());
1363  if (!ToModifiedTypeOrErr)
1364  return ToModifiedTypeOrErr.takeError();
1365  ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType());
1366  if (!ToEquivalentTypeOrErr)
1367  return ToEquivalentTypeOrErr.takeError();
1368 
1369  return Importer.getToContext().getAttributedType(T->getAttrKind(),
1370  *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr);
1371 }
1372 
1374  const TemplateTypeParmType *T) {
1375  Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl());
1376  if (!ToDeclOrErr)
1377  return ToDeclOrErr.takeError();
1378 
1379  return Importer.getToContext().getTemplateTypeParmType(
1380  T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr);
1381 }
1382 
1384  const SubstTemplateTypeParmType *T) {
1385  ExpectedType ReplacedOrErr = import(QualType(T->getReplacedParameter(), 0));
1386  if (!ReplacedOrErr)
1387  return ReplacedOrErr.takeError();
1388  const TemplateTypeParmType *Replaced =
1389  cast<TemplateTypeParmType>((*ReplacedOrErr).getTypePtr());
1390 
1391  ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType());
1392  if (!ToReplacementTypeOrErr)
1393  return ToReplacementTypeOrErr.takeError();
1394 
1395  return Importer.getToContext().getSubstTemplateTypeParmType(
1396  Replaced, (*ToReplacementTypeOrErr).getCanonicalType());
1397 }
1398 
1400  const TemplateSpecializationType *T) {
1401  auto ToTemplateOrErr = import(T->getTemplateName());
1402  if (!ToTemplateOrErr)
1403  return ToTemplateOrErr.takeError();
1404 
1405  SmallVector<TemplateArgument, 2> ToTemplateArgs;
1406  if (Error Err = ImportTemplateArguments(
1407  T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1408  return std::move(Err);
1409 
1410  QualType ToCanonType;
1411  if (!QualType(T, 0).isCanonical()) {
1412  QualType FromCanonType
1413  = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1414  if (ExpectedType TyOrErr = import(FromCanonType))
1415  ToCanonType = *TyOrErr;
1416  else
1417  return TyOrErr.takeError();
1418  }
1419  return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr,
1420  ToTemplateArgs,
1421  ToCanonType);
1422 }
1423 
1425  // Note: the qualifier in an ElaboratedType is optional.
1426  auto ToQualifierOrErr = import(T->getQualifier());
1427  if (!ToQualifierOrErr)
1428  return ToQualifierOrErr.takeError();
1429 
1430  ExpectedType ToNamedTypeOrErr = import(T->getNamedType());
1431  if (!ToNamedTypeOrErr)
1432  return ToNamedTypeOrErr.takeError();
1433 
1434  Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl());
1435  if (!ToOwnedTagDeclOrErr)
1436  return ToOwnedTagDeclOrErr.takeError();
1437 
1438  return Importer.getToContext().getElaboratedType(T->getKeyword(),
1439  *ToQualifierOrErr,
1440  *ToNamedTypeOrErr,
1441  *ToOwnedTagDeclOrErr);
1442 }
1443 
1446  ExpectedType ToPatternOrErr = import(T->getPattern());
1447  if (!ToPatternOrErr)
1448  return ToPatternOrErr.takeError();
1449 
1450  return Importer.getToContext().getPackExpansionType(*ToPatternOrErr,
1451  T->getNumExpansions());
1452 }
1453 
1456  auto ToQualifierOrErr = import(T->getQualifier());
1457  if (!ToQualifierOrErr)
1458  return ToQualifierOrErr.takeError();
1459 
1460  IdentifierInfo *ToName = Importer.Import(T->getIdentifier());
1461 
1463  ToPack.reserve(T->getNumArgs());
1464  if (Error Err = ImportTemplateArguments(
1465  T->getArgs(), T->getNumArgs(), ToPack))
1466  return std::move(Err);
1467 
1468  return Importer.getToContext().getDependentTemplateSpecializationType(
1469  T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
1470 }
1471 
1474  auto ToQualifierOrErr = import(T->getQualifier());
1475  if (!ToQualifierOrErr)
1476  return ToQualifierOrErr.takeError();
1477 
1478  IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1479 
1480  QualType Canon;
1481  if (T != T->getCanonicalTypeInternal().getTypePtr()) {
1482  if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
1483  Canon = (*TyOrErr).getCanonicalType();
1484  else
1485  return TyOrErr.takeError();
1486  }
1487 
1488  return Importer.getToContext().getDependentNameType(T->getKeyword(),
1489  *ToQualifierOrErr,
1490  Name, Canon);
1491 }
1492 
1495  Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl());
1496  if (!ToDeclOrErr)
1497  return ToDeclOrErr.takeError();
1498 
1499  return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr);
1500 }
1501 
1503  ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1504  if (!ToBaseTypeOrErr)
1505  return ToBaseTypeOrErr.takeError();
1506 
1507  SmallVector<QualType, 4> TypeArgs;
1508  for (auto TypeArg : T->getTypeArgsAsWritten()) {
1509  if (ExpectedType TyOrErr = import(TypeArg))
1510  TypeArgs.push_back(*TyOrErr);
1511  else
1512  return TyOrErr.takeError();
1513  }
1514 
1516  for (auto *P : T->quals()) {
1517  if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
1518  Protocols.push_back(*ProtocolOrErr);
1519  else
1520  return ProtocolOrErr.takeError();
1521 
1522  }
1523 
1524  return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs,
1525  Protocols,
1526  T->isKindOfTypeAsWritten());
1527 }
1528 
1531  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1532  if (!ToPointeeTypeOrErr)
1533  return ToPointeeTypeOrErr.takeError();
1534 
1535  return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
1536 }
1537 
1538 //----------------------------------------------------------------------------
1539 // Import Declarations
1540 //----------------------------------------------------------------------------
1542  NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
1543  DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
1544  // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1545  // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1546  DeclContext *OrigDC = D->getDeclContext();
1547  FunctionDecl *FunDecl;
1548  if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
1549  FunDecl->hasBody()) {
1550  auto getLeafPointeeType = [](const Type *T) {
1551  while (T->isPointerType() || T->isArrayType()) {
1552  T = T->getPointeeOrArrayElementType();
1553  }
1554  return T;
1555  };
1556  for (const ParmVarDecl *P : FunDecl->parameters()) {
1557  const Type *LeafT =
1558  getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1559  auto *RT = dyn_cast<RecordType>(LeafT);
1560  if (RT && RT->getDecl() == D) {
1561  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1562  << D->getDeclKindName();
1563  return make_error<ImportError>(ImportError::UnsupportedConstruct);
1564  }
1565  }
1566  }
1567 
1568  // Import the context of this declaration.
1569  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
1570  return Err;
1571 
1572  // Import the name of this declaration.
1573  if (Error Err = importInto(Name, D->getDeclName()))
1574  return Err;
1575 
1576  // Import the location of this declaration.
1577  if (Error Err = importInto(Loc, D->getLocation()))
1578  return Err;
1579 
1580  ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1581  if (ToD)
1582  if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1583  return Err;
1584 
1585  return Error::success();
1586 }
1587 
1589  if (!FromD)
1590  return Error::success();
1591 
1592  if (!ToD)
1593  if (Error Err = importInto(ToD, FromD))
1594  return Err;
1595 
1596  if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1597  if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) {
1598  if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
1599  !ToRecord->getDefinition()) {
1600  if (Error Err = ImportDefinition(FromRecord, ToRecord))
1601  return Err;
1602  }
1603  }
1604  return Error::success();
1605  }
1606 
1607  if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1608  if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) {
1609  if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1610  if (Error Err = ImportDefinition(FromEnum, ToEnum))
1611  return Err;
1612  }
1613  }
1614  return Error::success();
1615  }
1616 
1617  return Error::success();
1618 }
1619 
1620 Error
1622  const DeclarationNameInfo &From, DeclarationNameInfo& To) {
1623  // NOTE: To.Name and To.Loc are already imported.
1624  // We only have to import To.LocInfo.
1625  switch (To.getName().getNameKind()) {
1632  return Error::success();
1633 
1635  if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange()))
1636  To.setCXXOperatorNameRange(*ToRangeOrErr);
1637  else
1638  return ToRangeOrErr.takeError();
1639  return Error::success();
1640  }
1642  if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc()))
1643  To.setCXXLiteralOperatorNameLoc(*LocOrErr);
1644  else
1645  return LocOrErr.takeError();
1646  return Error::success();
1647  }
1651  if (auto ToTInfoOrErr = import(From.getNamedTypeInfo()))
1652  To.setNamedTypeInfo(*ToTInfoOrErr);
1653  else
1654  return ToTInfoOrErr.takeError();
1655  return Error::success();
1656  }
1657  }
1658  llvm_unreachable("Unknown name kind.");
1659 }
1660 
1661 Error
1663  if (Importer.isMinimalImport() && !ForceImport) {
1664  auto ToDCOrErr = Importer.ImportContext(FromDC);
1665  return ToDCOrErr.takeError();
1666  }
1667 
1668  // We use strict error handling in case of records and enums, but not
1669  // with e.g. namespaces.
1670  //
1671  // FIXME Clients of the ASTImporter should be able to choose an
1672  // appropriate error handling strategy for their needs. For instance,
1673  // they may not want to mark an entire namespace as erroneous merely
1674  // because there is an ODR error with two typedefs. As another example,
1675  // the client may allow EnumConstantDecls with same names but with
1676  // different values in two distinct translation units.
1677  bool AccumulateChildErrors = isa<TagDecl>(FromDC);
1678 
1679  Error ChildErrors = Error::success();
1680  for (auto *From : FromDC->decls()) {
1681  ExpectedDecl ImportedOrErr = import(From);
1682  if (!ImportedOrErr) {
1683  if (AccumulateChildErrors)
1684  ChildErrors =
1685  joinErrors(std::move(ChildErrors), ImportedOrErr.takeError());
1686  else
1687  consumeError(ImportedOrErr.takeError());
1688  }
1689  }
1690 
1691  // We reorder declarations in RecordDecls because they may have another order
1692  // in the "to" context than they have in the "from" context. This may happen
1693  // e.g when we import a class like this:
1694  // struct declToImport {
1695  // int a = c + b;
1696  // int b = 1;
1697  // int c = 2;
1698  // };
1699  // During the import of `a` we import first the dependencies in sequence,
1700  // thus the order would be `c`, `b`, `a`. We will get the normal order by
1701  // first removing the already imported members and then adding them in the
1702  // order as they apper in the "from" context.
1703  //
1704  // Keeping field order is vital because it determines structure layout.
1705  //
1706  // Here and below, we cannot call field_begin() method and its callers on
1707  // ToDC if it has an external storage. Calling field_begin() will
1708  // automatically load all the fields by calling
1709  // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would
1710  // call ASTImporter::Import(). This is because the ExternalASTSource
1711  // interface in LLDB is implemented by the means of the ASTImporter. However,
1712  // calling an import at this point would result in an uncontrolled import, we
1713  // must avoid that.
1714  const auto *FromRD = dyn_cast<RecordDecl>(FromDC);
1715  if (!FromRD)
1716  return ChildErrors;
1717 
1718  auto ToDCOrErr = Importer.ImportContext(FromDC);
1719  if (!ToDCOrErr) {
1720  consumeError(std::move(ChildErrors));
1721  return ToDCOrErr.takeError();
1722  }
1723 
1724  DeclContext *ToDC = *ToDCOrErr;
1725  // Remove all declarations, which may be in wrong order in the
1726  // lexical DeclContext and then add them in the proper order.
1727  for (auto *D : FromRD->decls()) {
1728  if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<FriendDecl>(D)) {
1729  assert(D && "DC contains a null decl");
1730  Decl *ToD = Importer.GetAlreadyImportedOrNull(D);
1731  // Remove only the decls which we successfully imported.
1732  if (ToD) {
1733  assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD));
1734  // Remove the decl from its wrong place in the linked list.
1735  ToDC->removeDecl(ToD);
1736  // Add the decl to the end of the linked list.
1737  // This time it will be at the proper place because the enclosing for
1738  // loop iterates in the original (good) order of the decls.
1739  ToDC->addDeclInternal(ToD);
1740  }
1741  }
1742  }
1743 
1744  return ChildErrors;
1745 }
1746 
1748  Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
1749  auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext());
1750  if (!ToDCOrErr)
1751  return ToDCOrErr.takeError();
1752  ToDC = *ToDCOrErr;
1753 
1754  if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
1755  auto ToLexicalDCOrErr = Importer.ImportContext(
1756  FromD->getLexicalDeclContext());
1757  if (!ToLexicalDCOrErr)
1758  return ToLexicalDCOrErr.takeError();
1759  ToLexicalDC = *ToLexicalDCOrErr;
1760  } else
1761  ToLexicalDC = ToDC;
1762 
1763  return Error::success();
1764 }
1765 
1767  const CXXRecordDecl *From, CXXRecordDecl *To) {
1768  assert(From->isCompleteDefinition() && To->getDefinition() == To &&
1769  "Import implicit methods to or from non-definition");
1770 
1771  for (CXXMethodDecl *FromM : From->methods())
1772  if (FromM->isImplicit()) {
1773  Expected<CXXMethodDecl *> ToMOrErr = import(FromM);
1774  if (!ToMOrErr)
1775  return ToMOrErr.takeError();
1776  }
1777 
1778  return Error::success();
1779 }
1780 
1782  ASTImporter &Importer) {
1783  if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
1784  if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef))
1785  To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr));
1786  else
1787  return ToTypedefOrErr.takeError();
1788  }
1789  return Error::success();
1790 }
1791 
1794  auto DefinitionCompleter = [To]() {
1795  // There are cases in LLDB when we first import a class without its
1796  // members. The class will have DefinitionData, but no members. Then,
1797  // importDefinition is called from LLDB, which tries to get the members, so
1798  // when we get here, the class already has the DefinitionData set, so we
1799  // must unset the CompleteDefinition here to be able to complete again the
1800  // definition.
1801  To->setCompleteDefinition(false);
1802  To->completeDefinition();
1803  };
1804 
1805  if (To->getDefinition() || To->isBeingDefined()) {
1806  if (Kind == IDK_Everything ||
1807  // In case of lambdas, the class already has a definition ptr set, but
1808  // the contained decls are not imported yet. Also, isBeingDefined was
1809  // set in CXXRecordDecl::CreateLambda. We must import the contained
1810  // decls here and finish the definition.
1811  (To->isLambda() && shouldForceImportDeclContext(Kind))) {
1812  Error Result = ImportDeclContext(From, /*ForceImport=*/true);
1813  // Finish the definition of the lambda, set isBeingDefined to false.
1814  if (To->isLambda())
1815  DefinitionCompleter();
1816  return Result;
1817  }
1818 
1819  return Error::success();
1820  }
1821 
1822  To->startDefinition();
1823  // Complete the definition even if error is returned.
1824  // The RecordDecl may be already part of the AST so it is better to
1825  // have it in complete state even if something is wrong with it.
1826  auto DefinitionCompleterScopeExit =
1827  llvm::make_scope_exit(DefinitionCompleter);
1828 
1829  if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
1830  return Err;
1831 
1832  // Add base classes.
1833  auto *ToCXX = dyn_cast<CXXRecordDecl>(To);
1834  auto *FromCXX = dyn_cast<CXXRecordDecl>(From);
1835  if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
1836 
1837  struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1838  struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
1839 
1840  #define FIELD(Name, Width, Merge) \
1841  ToData.Name = FromData.Name;
1842  #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1843 
1844  // Copy over the data stored in RecordDeclBits
1845  ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
1846 
1848  for (const auto &Base1 : FromCXX->bases()) {
1849  ExpectedType TyOrErr = import(Base1.getType());
1850  if (!TyOrErr)
1851  return TyOrErr.takeError();
1852 
1853  SourceLocation EllipsisLoc;
1854  if (Base1.isPackExpansion()) {
1855  if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc()))
1856  EllipsisLoc = *LocOrErr;
1857  else
1858  return LocOrErr.takeError();
1859  }
1860 
1861  // Ensure that we have a definition for the base.
1862  if (Error Err =
1863  ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
1864  return Err;
1865 
1866  auto RangeOrErr = import(Base1.getSourceRange());
1867  if (!RangeOrErr)
1868  return RangeOrErr.takeError();
1869 
1870  auto TSIOrErr = import(Base1.getTypeSourceInfo());
1871  if (!TSIOrErr)
1872  return TSIOrErr.takeError();
1873 
1874  Bases.push_back(
1875  new (Importer.getToContext()) CXXBaseSpecifier(
1876  *RangeOrErr,
1877  Base1.isVirtual(),
1878  Base1.isBaseOfClass(),
1879  Base1.getAccessSpecifierAsWritten(),
1880  *TSIOrErr,
1881  EllipsisLoc));
1882  }
1883  if (!Bases.empty())
1884  ToCXX->setBases(Bases.data(), Bases.size());
1885  }
1886 
1887  if (shouldForceImportDeclContext(Kind))
1888  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
1889  return Err;
1890 
1891  return Error::success();
1892 }
1893 
1895  if (To->getAnyInitializer())
1896  return Error::success();
1897 
1898  Expr *FromInit = From->getInit();
1899  if (!FromInit)
1900  return Error::success();
1901 
1902  ExpectedExpr ToInitOrErr = import(FromInit);
1903  if (!ToInitOrErr)
1904  return ToInitOrErr.takeError();
1905 
1906  To->setInit(*ToInitOrErr);
1907  if (From->isInitKnownICE()) {
1908  EvaluatedStmt *Eval = To->ensureEvaluatedStmt();
1909  Eval->CheckedICE = true;
1910  Eval->IsICE = From->isInitICE();
1911  }
1912 
1913  // FIXME: Other bits to merge?
1914  return Error::success();
1915 }
1916 
1919  if (To->getDefinition() || To->isBeingDefined()) {
1920  if (Kind == IDK_Everything)
1921  return ImportDeclContext(From, /*ForceImport=*/true);
1922  return Error::success();
1923  }
1924 
1925  To->startDefinition();
1926 
1927  if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
1928  return Err;
1929 
1930  ExpectedType ToTypeOrErr =
1931  import(Importer.getFromContext().getTypeDeclType(From));
1932  if (!ToTypeOrErr)
1933  return ToTypeOrErr.takeError();
1934 
1935  ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType());
1936  if (!ToPromotionTypeOrErr)
1937  return ToPromotionTypeOrErr.takeError();
1938 
1939  if (shouldForceImportDeclContext(Kind))
1940  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
1941  return Err;
1942 
1943  // FIXME: we might need to merge the number of positive or negative bits
1944  // if the enumerator lists don't match.
1945  To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr,
1946  From->getNumPositiveBits(),
1947  From->getNumNegativeBits());
1948  return Error::success();
1949 }
1950 
1952  const TemplateArgument *FromArgs, unsigned NumFromArgs,
1954  for (unsigned I = 0; I != NumFromArgs; ++I) {
1955  if (auto ToOrErr = import(FromArgs[I]))
1956  ToArgs.push_back(*ToOrErr);
1957  else
1958  return ToOrErr.takeError();
1959  }
1960 
1961  return Error::success();
1962 }
1963 
1964 // FIXME: Do not forget to remove this and use only 'import'.
1967  return import(From);
1968 }
1969 
1970 template <typename InContainerTy>
1972  const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
1973  for (const auto &FromLoc : Container) {
1974  if (auto ToLocOrErr = import(FromLoc))
1975  ToTAInfo.addArgument(*ToLocOrErr);
1976  else
1977  return ToLocOrErr.takeError();
1978  }
1979  return Error::success();
1980 }
1981 
1986 }
1987 
1988 bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) {
1990  Importer.getFromContext(), Importer.getToContext(),
1991  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1992  false, Complain);
1993  return Ctx.IsEquivalent(From, To);
1994 }
1995 
1997  RecordDecl *ToRecord, bool Complain) {
1998  // Eliminate a potential failure point where we attempt to re-import
1999  // something we're trying to import while completing ToRecord.
2000  Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2001  if (ToOrigin) {
2002  auto *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2003  if (ToOriginRecord)
2004  ToRecord = ToOriginRecord;
2005  }
2006 
2007  StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2008  ToRecord->getASTContext(),
2009  Importer.getNonEquivalentDecls(),
2010  getStructuralEquivalenceKind(Importer),
2011  false, Complain);
2012  return Ctx.IsEquivalent(FromRecord, ToRecord);
2013 }
2014 
2016  bool Complain) {
2018  Importer.getFromContext(), Importer.getToContext(),
2019  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2020  false, Complain);
2021  return Ctx.IsEquivalent(FromVar, ToVar);
2022 }
2023 
2025  // Eliminate a potential failure point where we attempt to re-import
2026  // something we're trying to import while completing ToEnum.
2027  if (Decl *ToOrigin = Importer.GetOriginalDecl(ToEnum))
2028  if (auto *ToOriginEnum = dyn_cast<EnumDecl>(ToOrigin))
2029  ToEnum = ToOriginEnum;
2030 
2032  Importer.getFromContext(), Importer.getToContext(),
2033  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer));
2034  return Ctx.IsEquivalent(FromEnum, ToEnum);
2035 }
2036 
2038  FunctionTemplateDecl *To) {
2040  Importer.getFromContext(), Importer.getToContext(),
2041  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2042  false, false);
2043  return Ctx.IsEquivalent(From, To);
2044 }
2045 
2048  Importer.getFromContext(), Importer.getToContext(),
2049  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2050  false, false);
2051  return Ctx.IsEquivalent(From, To);
2052 }
2053 
2055  EnumConstantDecl *ToEC) {
2056  const llvm::APSInt &FromVal = FromEC->getInitVal();
2057  const llvm::APSInt &ToVal = ToEC->getInitVal();
2058 
2059  return FromVal.isSigned() == ToVal.isSigned() &&
2060  FromVal.getBitWidth() == ToVal.getBitWidth() &&
2061  FromVal == ToVal;
2062 }
2063 
2065  ClassTemplateDecl *To) {
2066  StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2067  Importer.getToContext(),
2068  Importer.getNonEquivalentDecls(),
2069  getStructuralEquivalenceKind(Importer));
2070  return Ctx.IsEquivalent(From, To);
2071 }
2072 
2074  VarTemplateDecl *To) {
2075  StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2076  Importer.getToContext(),
2077  Importer.getNonEquivalentDecls(),
2078  getStructuralEquivalenceKind(Importer));
2079  return Ctx.IsEquivalent(From, To);
2080 }
2081 
2083  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2084  << D->getDeclKindName();
2085  return make_error<ImportError>(ImportError::UnsupportedConstruct);
2086 }
2087 
2089  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2090  << D->getDeclKindName();
2091  return make_error<ImportError>(ImportError::UnsupportedConstruct);
2092 }
2093 
2095  // Import the context of this declaration.
2096  DeclContext *DC, *LexicalDC;
2097  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
2098  return std::move(Err);
2099 
2100  // Import the location of this declaration.
2101  ExpectedSLoc LocOrErr = import(D->getLocation());
2102  if (!LocOrErr)
2103  return LocOrErr.takeError();
2104 
2105  EmptyDecl *ToD;
2106  if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr))
2107  return ToD;
2108 
2109  ToD->setLexicalDeclContext(LexicalDC);
2110  LexicalDC->addDeclInternal(ToD);
2111  return ToD;
2112 }
2113 
2115  TranslationUnitDecl *ToD =
2116  Importer.getToContext().getTranslationUnitDecl();
2117 
2118  Importer.MapImported(D, ToD);
2119 
2120  return ToD;
2121 }
2122 
2124  ExpectedSLoc LocOrErr = import(D->getLocation());
2125  if (!LocOrErr)
2126  return LocOrErr.takeError();
2127  auto ColonLocOrErr = import(D->getColonLoc());
2128  if (!ColonLocOrErr)
2129  return ColonLocOrErr.takeError();
2130 
2131  // Import the context of this declaration.
2132  auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2133  if (!DCOrErr)
2134  return DCOrErr.takeError();
2135  DeclContext *DC = *DCOrErr;
2136 
2137  AccessSpecDecl *ToD;
2138  if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
2139  DC, *LocOrErr, *ColonLocOrErr))
2140  return ToD;
2141 
2142  // Lexical DeclContext and Semantic DeclContext
2143  // is always the same for the accessSpec.
2144  ToD->setLexicalDeclContext(DC);
2145  DC->addDeclInternal(ToD);
2146 
2147  return ToD;
2148 }
2149 
2151  auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2152  if (!DCOrErr)
2153  return DCOrErr.takeError();
2154  DeclContext *DC = *DCOrErr;
2155  DeclContext *LexicalDC = DC;
2156 
2157  SourceLocation ToLocation, ToRParenLoc;
2158  Expr *ToAssertExpr;
2159  StringLiteral *ToMessage;
2160  if (auto Imp = importSeq(
2161  D->getLocation(), D->getAssertExpr(), D->getMessage(), D->getRParenLoc()))
2162  std::tie(ToLocation, ToAssertExpr, ToMessage, ToRParenLoc) = *Imp;
2163  else
2164  return Imp.takeError();
2165 
2166  StaticAssertDecl *ToD;
2167  if (GetImportedOrCreateDecl(
2168  ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
2169  ToRParenLoc, D->isFailed()))
2170  return ToD;
2171 
2172  ToD->setLexicalDeclContext(LexicalDC);
2173  LexicalDC->addDeclInternal(ToD);
2174  return ToD;
2175 }
2176 
2178  // Import the major distinguishing characteristics of this namespace.
2179  DeclContext *DC, *LexicalDC;
2180  DeclarationName Name;
2181  SourceLocation Loc;
2182  NamedDecl *ToD;
2183  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2184  return std::move(Err);
2185  if (ToD)
2186  return ToD;
2187 
2188  NamespaceDecl *MergeWithNamespace = nullptr;
2189  if (!Name) {
2190  // This is an anonymous namespace. Adopt an existing anonymous
2191  // namespace if we can.
2192  // FIXME: Not testable.
2193  if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2194  MergeWithNamespace = TU->getAnonymousNamespace();
2195  else
2196  MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2197  } else {
2198  SmallVector<NamedDecl *, 4> ConflictingDecls;
2199  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2200  for (auto *FoundDecl : FoundDecls) {
2202  continue;
2203 
2204  if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
2205  MergeWithNamespace = FoundNS;
2206  ConflictingDecls.clear();
2207  break;
2208  }
2209 
2210  ConflictingDecls.push_back(FoundDecl);
2211  }
2212 
2213  if (!ConflictingDecls.empty()) {
2214  ExpectedName NameOrErr = Importer.HandleNameConflict(
2215  Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(),
2216  ConflictingDecls.size());
2217  if (NameOrErr)
2218  Name = NameOrErr.get();
2219  else
2220  return NameOrErr.takeError();
2221  }
2222  }
2223 
2224  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2225  if (!BeginLocOrErr)
2226  return BeginLocOrErr.takeError();
2227 
2228  // Create the "to" namespace, if needed.
2229  NamespaceDecl *ToNamespace = MergeWithNamespace;
2230  if (!ToNamespace) {
2231  if (GetImportedOrCreateDecl(
2232  ToNamespace, D, Importer.getToContext(), DC, D->isInline(),
2233  *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2234  /*PrevDecl=*/nullptr))
2235  return ToNamespace;
2236  ToNamespace->setLexicalDeclContext(LexicalDC);
2237  LexicalDC->addDeclInternal(ToNamespace);
2238 
2239  // If this is an anonymous namespace, register it as the anonymous
2240  // namespace within its context.
2241  if (!Name) {
2242  if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2243  TU->setAnonymousNamespace(ToNamespace);
2244  else
2245  cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2246  }
2247  }
2248  Importer.MapImported(D, ToNamespace);
2249 
2250  if (Error Err = ImportDeclContext(D))
2251  return std::move(Err);
2252 
2253  return ToNamespace;
2254 }
2255 
2257  // Import the major distinguishing characteristics of this namespace.
2258  DeclContext *DC, *LexicalDC;
2259  DeclarationName Name;
2260  SourceLocation Loc;
2261  NamedDecl *LookupD;
2262  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
2263  return std::move(Err);
2264  if (LookupD)
2265  return LookupD;
2266 
2267  // NOTE: No conflict resolution is done for namespace aliases now.
2268 
2269  SourceLocation ToNamespaceLoc, ToAliasLoc, ToTargetNameLoc;
2270  NestedNameSpecifierLoc ToQualifierLoc;
2271  NamespaceDecl *ToNamespace;
2272  if (auto Imp = importSeq(
2273  D->getNamespaceLoc(), D->getAliasLoc(), D->getQualifierLoc(),
2274  D->getTargetNameLoc(), D->getNamespace()))
2275  std::tie(
2276  ToNamespaceLoc, ToAliasLoc, ToQualifierLoc, ToTargetNameLoc,
2277  ToNamespace) = *Imp;
2278  else
2279  return Imp.takeError();
2280  IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
2281 
2282  NamespaceAliasDecl *ToD;
2283  if (GetImportedOrCreateDecl(
2284  ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc,
2285  ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace))
2286  return ToD;
2287 
2288  ToD->setLexicalDeclContext(LexicalDC);
2289  LexicalDC->addDeclInternal(ToD);
2290 
2291  return ToD;
2292 }
2293 
2296  // Import the major distinguishing characteristics of this typedef.
2297  DeclContext *DC, *LexicalDC;
2298  DeclarationName Name;
2299  SourceLocation Loc;
2300  NamedDecl *ToD;
2301  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2302  return std::move(Err);
2303  if (ToD)
2304  return ToD;
2305 
2306  // If this typedef is not in block scope, determine whether we've
2307  // seen a typedef with the same name (that we can merge with) or any
2308  // other entity by that name (which name lookup could conflict with).
2309  // Note: Repeated typedefs are not valid in C99:
2310  // 'typedef int T; typedef int T;' is invalid
2311  // We do not care about this now.
2312  if (!DC->isFunctionOrMethod()) {
2313  SmallVector<NamedDecl *, 4> ConflictingDecls;
2314  unsigned IDNS = Decl::IDNS_Ordinary;
2315  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2316  for (auto *FoundDecl : FoundDecls) {
2317  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2318  continue;
2319  if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2320  if (!hasSameVisibilityContext(FoundTypedef, D))
2321  continue;
2322 
2323  QualType FromUT = D->getUnderlyingType();
2324  QualType FoundUT = FoundTypedef->getUnderlyingType();
2325  if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
2326  // If the "From" context has a complete underlying type but we
2327  // already have a complete underlying type then return with that.
2328  if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
2329  return Importer.MapImported(D, FoundTypedef);
2330  // FIXME Handle redecl chain. When you do that make consistent changes
2331  // in ASTImporterLookupTable too.
2332  } else {
2333  ConflictingDecls.push_back(FoundDecl);
2334  }
2335  }
2336  }
2337 
2338  if (!ConflictingDecls.empty()) {
2339  ExpectedName NameOrErr = Importer.HandleNameConflict(
2340  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2341  if (NameOrErr)
2342  Name = NameOrErr.get();
2343  else
2344  return NameOrErr.takeError();
2345  }
2346  }
2347 
2349  TypeSourceInfo *ToTypeSourceInfo;
2350  SourceLocation ToBeginLoc;
2351  if (auto Imp = importSeq(
2353  std::tie(ToUnderlyingType, ToTypeSourceInfo, ToBeginLoc) = *Imp;
2354  else
2355  return Imp.takeError();
2356 
2357  // Create the new typedef node.
2358  // FIXME: ToUnderlyingType is not used.
2359  TypedefNameDecl *ToTypedef;
2360  if (IsAlias) {
2361  if (GetImportedOrCreateDecl<TypeAliasDecl>(
2362  ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2363  Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2364  return ToTypedef;
2365  } else if (GetImportedOrCreateDecl<TypedefDecl>(
2366  ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2367  Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2368  return ToTypedef;
2369 
2370  ToTypedef->setAccess(D->getAccess());
2371  ToTypedef->setLexicalDeclContext(LexicalDC);
2372 
2373  // Templated declarations should not appear in DeclContext.
2374  TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
2375  if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
2376  LexicalDC->addDeclInternal(ToTypedef);
2377 
2378  return ToTypedef;
2379 }
2380 
2382  return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2383 }
2384 
2386  return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2387 }
2388 
2391  // Import the major distinguishing characteristics of this typedef.
2392  DeclContext *DC, *LexicalDC;
2393  DeclarationName Name;
2394  SourceLocation Loc;
2395  NamedDecl *FoundD;
2396  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
2397  return std::move(Err);
2398  if (FoundD)
2399  return FoundD;
2400 
2401  // If this typedef is not in block scope, determine whether we've
2402  // seen a typedef with the same name (that we can merge with) or any
2403  // other entity by that name (which name lookup could conflict with).
2404  if (!DC->isFunctionOrMethod()) {
2405  SmallVector<NamedDecl *, 4> ConflictingDecls;
2406  unsigned IDNS = Decl::IDNS_Ordinary;
2407  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2408  for (auto *FoundDecl : FoundDecls) {
2409  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2410  continue;
2411  if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl))
2412  return Importer.MapImported(D, FoundAlias);
2413  ConflictingDecls.push_back(FoundDecl);
2414  }
2415 
2416  if (!ConflictingDecls.empty()) {
2417  ExpectedName NameOrErr = Importer.HandleNameConflict(
2418  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2419  if (NameOrErr)
2420  Name = NameOrErr.get();
2421  else
2422  return NameOrErr.takeError();
2423  }
2424  }
2425 
2426  TemplateParameterList *ToTemplateParameters;
2427  TypeAliasDecl *ToTemplatedDecl;
2428  if (auto Imp = importSeq(D->getTemplateParameters(), D->getTemplatedDecl()))
2429  std::tie(ToTemplateParameters, ToTemplatedDecl) = *Imp;
2430  else
2431  return Imp.takeError();
2432 
2433  TypeAliasTemplateDecl *ToAlias;
2434  if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2435  Name, ToTemplateParameters, ToTemplatedDecl))
2436  return ToAlias;
2437 
2438  ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
2439 
2440  ToAlias->setAccess(D->getAccess());
2441  ToAlias->setLexicalDeclContext(LexicalDC);
2442  LexicalDC->addDeclInternal(ToAlias);
2443  return ToAlias;
2444 }
2445 
2447  // Import the major distinguishing characteristics of this label.
2448  DeclContext *DC, *LexicalDC;
2449  DeclarationName Name;
2450  SourceLocation Loc;
2451  NamedDecl *ToD;
2452  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2453  return std::move(Err);
2454  if (ToD)
2455  return ToD;
2456 
2457  assert(LexicalDC->isFunctionOrMethod());
2458 
2459  LabelDecl *ToLabel;
2460  if (D->isGnuLocal()) {
2461  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2462  if (!BeginLocOrErr)
2463  return BeginLocOrErr.takeError();
2464  if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2465  Name.getAsIdentifierInfo(), *BeginLocOrErr))
2466  return ToLabel;
2467 
2468  } else {
2469  if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2470  Name.getAsIdentifierInfo()))
2471  return ToLabel;
2472 
2473  }
2474 
2475  Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt());
2476  if (!ToStmtOrErr)
2477  return ToStmtOrErr.takeError();
2478 
2479  ToLabel->setStmt(*ToStmtOrErr);
2480  ToLabel->setLexicalDeclContext(LexicalDC);
2481  LexicalDC->addDeclInternal(ToLabel);
2482  return ToLabel;
2483 }
2484 
2486  // Import the major distinguishing characteristics of this enum.
2487  DeclContext *DC, *LexicalDC;
2488  DeclarationName Name;
2489  SourceLocation Loc;
2490  NamedDecl *ToD;
2491  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2492  return std::move(Err);
2493  if (ToD)
2494  return ToD;
2495 
2496  // Figure out what enum name we're looking for.
2497  unsigned IDNS = Decl::IDNS_Tag;
2498  DeclarationName SearchName = Name;
2499  if (!SearchName && D->getTypedefNameForAnonDecl()) {
2500  if (Error Err = importInto(
2501  SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2502  return std::move(Err);
2503  IDNS = Decl::IDNS_Ordinary;
2504  } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2505  IDNS |= Decl::IDNS_Ordinary;
2506 
2507  // We may already have an enum of the same name; try to find and match it.
2508  if (!DC->isFunctionOrMethod() && SearchName) {
2509  SmallVector<NamedDecl *, 4> ConflictingDecls;
2510  auto FoundDecls =
2511  Importer.findDeclsInToCtx(DC, SearchName);
2512  for (auto *FoundDecl : FoundDecls) {
2513  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2514  continue;
2515 
2516  if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2517  if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2518  FoundDecl = Tag->getDecl();
2519  }
2520 
2521  if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) {
2522  if (!hasSameVisibilityContext(FoundEnum, D))
2523  continue;
2524  if (IsStructuralMatch(D, FoundEnum))
2525  return Importer.MapImported(D, FoundEnum);
2526  ConflictingDecls.push_back(FoundDecl);
2527  }
2528  }
2529 
2530  if (!ConflictingDecls.empty()) {
2531  ExpectedName NameOrErr = Importer.HandleNameConflict(
2532  SearchName, DC, IDNS, ConflictingDecls.data(),
2533  ConflictingDecls.size());
2534  if (NameOrErr)
2535  Name = NameOrErr.get();
2536  else
2537  return NameOrErr.takeError();
2538  }
2539  }
2540 
2541  SourceLocation ToBeginLoc;
2542  NestedNameSpecifierLoc ToQualifierLoc;
2543  QualType ToIntegerType;
2544  if (auto Imp = importSeq(
2545  D->getBeginLoc(), D->getQualifierLoc(), D->getIntegerType()))
2546  std::tie(ToBeginLoc, ToQualifierLoc, ToIntegerType) = *Imp;
2547  else
2548  return Imp.takeError();
2549 
2550  // Create the enum declaration.
2551  EnumDecl *D2;
2552  if (GetImportedOrCreateDecl(
2553  D2, D, Importer.getToContext(), DC, ToBeginLoc,
2554  Loc, Name.getAsIdentifierInfo(), nullptr, D->isScoped(),
2555  D->isScopedUsingClassTag(), D->isFixed()))
2556  return D2;
2557 
2558  D2->setQualifierInfo(ToQualifierLoc);
2559  D2->setIntegerType(ToIntegerType);
2560  D2->setAccess(D->getAccess());
2561  D2->setLexicalDeclContext(LexicalDC);
2562  LexicalDC->addDeclInternal(D2);
2563 
2564  // Import the definition
2565  if (D->isCompleteDefinition())
2566  if (Error Err = ImportDefinition(D, D2))
2567  return std::move(Err);
2568 
2569  return D2;
2570 }
2571 
2573  bool IsFriendTemplate = false;
2574  if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2575  IsFriendTemplate =
2576  DCXX->getDescribedClassTemplate() &&
2577  DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
2579  }
2580 
2581  // Import the major distinguishing characteristics of this record.
2582  DeclContext *DC = nullptr, *LexicalDC = nullptr;
2583  DeclarationName Name;
2584  SourceLocation Loc;
2585  NamedDecl *ToD = nullptr;
2586  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2587  return std::move(Err);
2588  if (ToD)
2589  return ToD;
2590 
2591  // Figure out what structure name we're looking for.
2592  unsigned IDNS = Decl::IDNS_Tag;
2593  DeclarationName SearchName = Name;
2594  if (!SearchName && D->getTypedefNameForAnonDecl()) {
2595  if (Error Err = importInto(
2596  SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2597  return std::move(Err);
2598  IDNS = Decl::IDNS_Ordinary;
2599  } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2601 
2602  // We may already have a record of the same name; try to find and match it.
2603  RecordDecl *PrevDecl = nullptr;
2604  if (!DC->isFunctionOrMethod() && !D->isLambda()) {
2605  SmallVector<NamedDecl *, 4> ConflictingDecls;
2606  auto FoundDecls =
2607  Importer.findDeclsInToCtx(DC, SearchName);
2608  if (!FoundDecls.empty()) {
2609  // We're going to have to compare D against potentially conflicting Decls,
2610  // so complete it.
2613  }
2614 
2615  for (auto *FoundDecl : FoundDecls) {
2616  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2617  continue;
2618 
2619  Decl *Found = FoundDecl;
2620  if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2621  if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2622  Found = Tag->getDecl();
2623  }
2624 
2625  if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2626  // Do not emit false positive diagnostic in case of unnamed
2627  // struct/union and in case of anonymous structs. Would be false
2628  // because there may be several anonymous/unnamed structs in a class.
2629  // E.g. these are both valid:
2630  // struct A { // unnamed structs
2631  // struct { struct A *next; } entry0;
2632  // struct { struct A *next; } entry1;
2633  // };
2634  // struct X { struct { int a; }; struct { int b; }; }; // anon structs
2635  if (!SearchName)
2636  if (!IsStructuralMatch(D, FoundRecord, false))
2637  continue;
2638 
2639  if (!hasSameVisibilityContext(FoundRecord, D))
2640  continue;
2641 
2642  if (IsStructuralMatch(D, FoundRecord)) {
2643  RecordDecl *FoundDef = FoundRecord->getDefinition();
2644  if (D->isThisDeclarationADefinition() && FoundDef) {
2645  // FIXME: Structural equivalence check should check for same
2646  // user-defined methods.
2647  Importer.MapImported(D, FoundDef);
2648  if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2649  auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
2650  assert(FoundCXX && "Record type mismatch");
2651 
2652  if (!Importer.isMinimalImport())
2653  // FoundDef may not have every implicit method that D has
2654  // because implicit methods are created only if they are used.
2655  if (Error Err = ImportImplicitMethods(DCXX, FoundCXX))
2656  return std::move(Err);
2657  }
2658  }
2659  PrevDecl = FoundRecord->getMostRecentDecl();
2660  break;
2661  }
2662  ConflictingDecls.push_back(FoundDecl);
2663  } // kind is RecordDecl
2664  } // for
2665 
2666  if (!ConflictingDecls.empty() && SearchName) {
2667  ExpectedName NameOrErr = Importer.HandleNameConflict(
2668  SearchName, DC, IDNS, ConflictingDecls.data(),
2669  ConflictingDecls.size());
2670  if (NameOrErr)
2671  Name = NameOrErr.get();
2672  else
2673  return NameOrErr.takeError();
2674  }
2675  }
2676 
2677  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2678  if (!BeginLocOrErr)
2679  return BeginLocOrErr.takeError();
2680 
2681  // Create the record declaration.
2682  RecordDecl *D2 = nullptr;
2683  CXXRecordDecl *D2CXX = nullptr;
2684  if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2685  if (DCXX->isLambda()) {
2686  auto TInfoOrErr = import(DCXX->getLambdaTypeInfo());
2687  if (!TInfoOrErr)
2688  return TInfoOrErr.takeError();
2689  if (GetImportedOrCreateSpecialDecl(
2690  D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
2691  DC, *TInfoOrErr, Loc, DCXX->isDependentLambda(),
2692  DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
2693  return D2CXX;
2694  ExpectedDecl CDeclOrErr = import(DCXX->getLambdaContextDecl());
2695  if (!CDeclOrErr)
2696  return CDeclOrErr.takeError();
2697  D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), *CDeclOrErr);
2698  } else if (DCXX->isInjectedClassName()) {
2699  // We have to be careful to do a similar dance to the one in
2700  // Sema::ActOnStartCXXMemberDeclarations
2701  const bool DelayTypeCreation = true;
2702  if (GetImportedOrCreateDecl(
2703  D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
2704  *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2705  cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation))
2706  return D2CXX;
2707  Importer.getToContext().getTypeDeclType(
2708  D2CXX, dyn_cast<CXXRecordDecl>(DC));
2709  } else {
2710  if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
2711  D->getTagKind(), DC, *BeginLocOrErr, Loc,
2712  Name.getAsIdentifierInfo(),
2713  cast_or_null<CXXRecordDecl>(PrevDecl)))
2714  return D2CXX;
2715  }
2716 
2717  D2 = D2CXX;
2718  D2->setAccess(D->getAccess());
2719  D2->setLexicalDeclContext(LexicalDC);
2720  if (!DCXX->getDescribedClassTemplate() || DCXX->isImplicit())
2721  LexicalDC->addDeclInternal(D2);
2722 
2723  if (LexicalDC != DC && D->isInIdentifierNamespace(Decl::IDNS_TagFriend))
2724  DC->makeDeclVisibleInContext(D2);
2725 
2726  if (ClassTemplateDecl *FromDescribed =
2727  DCXX->getDescribedClassTemplate()) {
2728  ClassTemplateDecl *ToDescribed;
2729  if (Error Err = importInto(ToDescribed, FromDescribed))
2730  return std::move(Err);
2731  D2CXX->setDescribedClassTemplate(ToDescribed);
2732  if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
2733  // In a record describing a template the type should be an
2734  // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
2735  // previously set type to the correct value here (ToDescribed is not
2736  // available at record create).
2737  // FIXME: The previous type is cleared but not removed from
2738  // ASTContext's internal storage.
2739  CXXRecordDecl *Injected = nullptr;
2740  for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
2741  auto *Record = dyn_cast<CXXRecordDecl>(Found);
2742  if (Record && Record->isInjectedClassName()) {
2743  Injected = Record;
2744  break;
2745  }
2746  }
2747  // Create an injected type for the whole redecl chain.
2748  SmallVector<Decl *, 2> Redecls =
2750  for (auto *R : Redecls) {
2751  auto *RI = cast<CXXRecordDecl>(R);
2752  RI->setTypeForDecl(nullptr);
2753  // Below we create a new injected type and assign that to the
2754  // canonical decl, subsequent declarations in the chain will reuse
2755  // that type.
2756  Importer.getToContext().getInjectedClassNameType(
2757  RI, ToDescribed->getInjectedClassNameSpecialization());
2758  }
2759  // Set the new type for the previous injected decl too.
2760  if (Injected) {
2761  Injected->setTypeForDecl(nullptr);
2762  Importer.getToContext().getTypeDeclType(Injected, D2CXX);
2763  }
2764  }
2765  } else if (MemberSpecializationInfo *MemberInfo =
2766  DCXX->getMemberSpecializationInfo()) {
2768  MemberInfo->getTemplateSpecializationKind();
2769  CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
2770 
2771  if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst))
2772  D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK);
2773  else
2774  return ToInstOrErr.takeError();
2775 
2776  if (ExpectedSLoc POIOrErr =
2777  import(MemberInfo->getPointOfInstantiation()))
2779  *POIOrErr);
2780  else
2781  return POIOrErr.takeError();
2782  }
2783 
2784  } else {
2785  if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
2786  D->getTagKind(), DC, *BeginLocOrErr, Loc,
2787  Name.getAsIdentifierInfo(), PrevDecl))
2788  return D2;
2789  D2->setLexicalDeclContext(LexicalDC);
2790  LexicalDC->addDeclInternal(D2);
2791  }
2792 
2793  if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
2794  D2->setQualifierInfo(*QualifierLocOrErr);
2795  else
2796  return QualifierLocOrErr.takeError();
2797 
2798  if (D->isAnonymousStructOrUnion())
2799  D2->setAnonymousStructOrUnion(true);
2800 
2801  if (D->isCompleteDefinition())
2802  if (Error Err = ImportDefinition(D, D2, IDK_Default))
2803  return std::move(Err);
2804 
2805  return D2;
2806 }
2807 
2809  // Import the major distinguishing characteristics of this enumerator.
2810  DeclContext *DC, *LexicalDC;
2811  DeclarationName Name;
2812  SourceLocation Loc;
2813  NamedDecl *ToD;
2814  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2815  return std::move(Err);
2816  if (ToD)
2817  return ToD;
2818 
2819  // Determine whether there are any other declarations with the same name and
2820  // in the same context.
2821  if (!LexicalDC->isFunctionOrMethod()) {
2822  SmallVector<NamedDecl *, 4> ConflictingDecls;
2823  unsigned IDNS = Decl::IDNS_Ordinary;
2824  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2825  for (auto *FoundDecl : FoundDecls) {
2826  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2827  continue;
2828 
2829  if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
2830  if (IsStructuralMatch(D, FoundEnumConstant))
2831  return Importer.MapImported(D, FoundEnumConstant);
2832  ConflictingDecls.push_back(FoundDecl);
2833  }
2834  }
2835 
2836  if (!ConflictingDecls.empty()) {
2837  ExpectedName NameOrErr = Importer.HandleNameConflict(
2838  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2839  if (NameOrErr)
2840  Name = NameOrErr.get();
2841  else
2842  return NameOrErr.takeError();
2843  }
2844  }
2845 
2846  ExpectedType TypeOrErr = import(D->getType());
2847  if (!TypeOrErr)
2848  return TypeOrErr.takeError();
2849 
2850  ExpectedExpr InitOrErr = import(D->getInitExpr());
2851  if (!InitOrErr)
2852  return InitOrErr.takeError();
2853 
2854  EnumConstantDecl *ToEnumerator;
2855  if (GetImportedOrCreateDecl(
2856  ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2857  Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal()))
2858  return ToEnumerator;
2859 
2860  ToEnumerator->setAccess(D->getAccess());
2861  ToEnumerator->setLexicalDeclContext(LexicalDC);
2862  LexicalDC->addDeclInternal(ToEnumerator);
2863  return ToEnumerator;
2864 }
2865 
2867  DeclaratorDecl *ToD) {
2868  unsigned int Num = FromD->getNumTemplateParameterLists();
2869  if (Num == 0)
2870  return Error::success();
2872  for (unsigned int I = 0; I < Num; ++I)
2873  if (Expected<TemplateParameterList *> ToTPListOrErr =
2874  import(FromD->getTemplateParameterList(I)))
2875  ToTPLists[I] = *ToTPListOrErr;
2876  else
2877  return ToTPListOrErr.takeError();
2878  ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists);
2879  return Error::success();
2880 }
2881 
2883  FunctionDecl *FromFD, FunctionDecl *ToFD) {
2884  switch (FromFD->getTemplatedKind()) {
2887  return Error::success();
2888 
2891 
2892  if (Expected<FunctionDecl *> InstFDOrErr =
2893  import(FromFD->getInstantiatedFromMemberFunction()))
2894  ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK);
2895  else
2896  return InstFDOrErr.takeError();
2897 
2898  if (ExpectedSLoc POIOrErr = import(
2901  else
2902  return POIOrErr.takeError();
2903 
2904  return Error::success();
2905  }
2906 
2908  auto FunctionAndArgsOrErr =
2909  ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
2910  if (!FunctionAndArgsOrErr)
2911  return FunctionAndArgsOrErr.takeError();
2912 
2914  Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr));
2915 
2916  auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
2917  TemplateArgumentListInfo ToTAInfo;
2918  const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
2919  if (FromTAArgsAsWritten)
2920  if (Error Err = ImportTemplateArgumentListInfo(
2921  *FromTAArgsAsWritten, ToTAInfo))
2922  return Err;
2923 
2924  ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation());
2925  if (!POIOrErr)
2926  return POIOrErr.takeError();
2927 
2928  if (Error Err = ImportTemplateParameterLists(FromFD, ToFD))
2929  return Err;
2930 
2931  TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
2932  ToFD->setFunctionTemplateSpecialization(
2933  std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
2934  TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
2935  return Error::success();
2936  }
2937 
2939  auto *FromInfo = FromFD->getDependentSpecializationInfo();
2940  UnresolvedSet<8> TemplDecls;
2941  unsigned NumTemplates = FromInfo->getNumTemplates();
2942  for (unsigned I = 0; I < NumTemplates; I++) {
2943  if (Expected<FunctionTemplateDecl *> ToFTDOrErr =
2944  import(FromInfo->getTemplate(I)))
2945  TemplDecls.addDecl(*ToFTDOrErr);
2946  else
2947  return ToFTDOrErr.takeError();
2948  }
2949 
2950  // Import TemplateArgumentListInfo.
2951  TemplateArgumentListInfo ToTAInfo;
2952  if (Error Err = ImportTemplateArgumentListInfo(
2953  FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(),
2954  llvm::makeArrayRef(
2955  FromInfo->getTemplateArgs(), FromInfo->getNumTemplateArgs()),
2956  ToTAInfo))
2957  return Err;
2958 
2959  ToFD->setDependentTemplateSpecialization(Importer.getToContext(),
2960  TemplDecls, ToTAInfo);
2961  return Error::success();
2962  }
2963  }
2964  llvm_unreachable("All cases should be covered!");
2965 }
2966 
2969  auto FunctionAndArgsOrErr =
2970  ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
2971  if (!FunctionAndArgsOrErr)
2972  return FunctionAndArgsOrErr.takeError();
2973 
2974  FunctionTemplateDecl *Template;
2975  TemplateArgsTy ToTemplArgs;
2976  std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr;
2977  void *InsertPos = nullptr;
2978  auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos);
2979  return FoundSpec;
2980 }
2981 
2983  FunctionDecl *ToFD) {
2984  if (Stmt *FromBody = FromFD->getBody()) {
2985  if (ExpectedStmt ToBodyOrErr = import(FromBody))
2986  ToFD->setBody(*ToBodyOrErr);
2987  else
2988  return ToBodyOrErr.takeError();
2989  }
2990  return Error::success();
2991 }
2992 
2994 
2996  auto RedeclIt = Redecls.begin();
2997  // Import the first part of the decl chain. I.e. import all previous
2998  // declarations starting from the canonical decl.
2999  for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3000  ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3001  if (!ToRedeclOrErr)
3002  return ToRedeclOrErr.takeError();
3003  }
3004  assert(*RedeclIt == D);
3005 
3006  // Import the major distinguishing characteristics of this function.
3007  DeclContext *DC, *LexicalDC;
3008  DeclarationName Name;
3009  SourceLocation Loc;
3010  NamedDecl *ToD;
3011  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3012  return std::move(Err);
3013  if (ToD)
3014  return ToD;
3015 
3016  FunctionDecl *FoundByLookup = nullptr;
3018 
3019  // If this is a function template specialization, then try to find the same
3020  // existing specialization in the "to" context. The lookup below will not
3021  // find any specialization, but would find the primary template; thus, we
3022  // have to skip normal lookup in case of specializations.
3023  // FIXME handle member function templates (TK_MemberSpecialization) similarly?
3024  if (D->getTemplatedKind() ==
3026  auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D);
3027  if (!FoundFunctionOrErr)
3028  return FoundFunctionOrErr.takeError();
3029  if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
3030  if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3031  return Def;
3032  FoundByLookup = FoundFunction;
3033  }
3034  }
3035  // Try to find a function in our own ("to") context with the same name, same
3036  // type, and in the same context as the function we're importing.
3037  else if (!LexicalDC->isFunctionOrMethod()) {
3038  SmallVector<NamedDecl *, 4> ConflictingDecls;
3040  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3041  for (auto *FoundDecl : FoundDecls) {
3042  if (!FoundDecl->isInIdentifierNamespace(IDNS))
3043  continue;
3044 
3045  if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
3046  if (!hasSameVisibilityContext(FoundFunction, D))
3047  continue;
3048 
3049  if (IsStructuralMatch(D, FoundFunction)) {
3050  if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3051  return Def;
3052  FoundByLookup = FoundFunction;
3053  break;
3054  }
3055  // FIXME: Check for overloading more carefully, e.g., by boosting
3056  // Sema::IsOverload out to the AST library.
3057 
3058  // Function overloading is okay in C++.
3059  if (Importer.getToContext().getLangOpts().CPlusPlus)
3060  continue;
3061 
3062  // Complain about inconsistent function types.
3063  Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent)
3064  << Name << D->getType() << FoundFunction->getType();
3065  Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here)
3066  << FoundFunction->getType();
3067  ConflictingDecls.push_back(FoundDecl);
3068  }
3069  }
3070 
3071  if (!ConflictingDecls.empty()) {
3072  ExpectedName NameOrErr = Importer.HandleNameConflict(
3073  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3074  if (NameOrErr)
3075  Name = NameOrErr.get();
3076  else
3077  return NameOrErr.takeError();
3078  }
3079  }
3080 
3081  // We do not allow more than one in-class declaration of a function. This is
3082  // because AST clients like VTableBuilder asserts on this. VTableBuilder
3083  // assumes there is only one in-class declaration. Building a redecl
3084  // chain would result in more than one in-class declaration for
3085  // overrides (even if they are part of the same redecl chain inside the
3086  // derived class.)
3087  if (FoundByLookup) {
3088  if (isa<CXXMethodDecl>(FoundByLookup)) {
3089  if (D->getLexicalDeclContext() == D->getDeclContext()) {
3090  if (!D->doesThisDeclarationHaveABody()) {
3091  if (FunctionTemplateDecl *DescribedD =
3093  // Handle a "templated" function together with its described
3094  // template. This avoids need for a similar check at import of the
3095  // described template.
3096  assert(FoundByLookup->getDescribedFunctionTemplate() &&
3097  "Templated function mapped to non-templated?");
3098  Importer.MapImported(DescribedD,
3099  FoundByLookup->getDescribedFunctionTemplate());
3100  }
3101  return Importer.MapImported(D, FoundByLookup);
3102  } else {
3103  // Let's continue and build up the redecl chain in this case.
3104  // FIXME Merge the functions into one decl.
3105  }
3106  }
3107  }
3108  }
3109 
3110  DeclarationNameInfo NameInfo(Name, Loc);
3111  // Import additional name location/type info.
3112  if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
3113  return std::move(Err);
3114 
3115  QualType FromTy = D->getType();
3116  bool usedDifferentExceptionSpec = false;
3117 
3118  if (const auto *FromFPT = D->getType()->getAs<FunctionProtoType>()) {
3119  FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3120  // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3121  // FunctionDecl that we are importing the FunctionProtoType for.
3122  // To avoid an infinite recursion when importing, create the FunctionDecl
3123  // with a simplified function type and update it afterwards.
3124  if (FromEPI.ExceptionSpec.SourceDecl ||
3125  FromEPI.ExceptionSpec.SourceTemplate ||
3126  FromEPI.ExceptionSpec.NoexceptExpr) {
3128  FromTy = Importer.getFromContext().getFunctionType(
3129  FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
3130  usedDifferentExceptionSpec = true;
3131  }
3132  }
3133 
3134  QualType T;
3135  TypeSourceInfo *TInfo;
3136  SourceLocation ToInnerLocStart, ToEndLoc;
3137  NestedNameSpecifierLoc ToQualifierLoc;
3138  if (auto Imp = importSeq(
3139  FromTy, D->getTypeSourceInfo(), D->getInnerLocStart(),
3140  D->getQualifierLoc(), D->getEndLoc()))
3141  std::tie(T, TInfo, ToInnerLocStart, ToQualifierLoc, ToEndLoc) = *Imp;
3142  else
3143  return Imp.takeError();
3144 
3145  // Import the function parameters.
3146  SmallVector<ParmVarDecl *, 8> Parameters;
3147  for (auto P : D->parameters()) {
3148  if (Expected<ParmVarDecl *> ToPOrErr = import(P))
3149  Parameters.push_back(*ToPOrErr);
3150  else
3151  return ToPOrErr.takeError();
3152  }
3153 
3154  // Create the imported function.
3155  FunctionDecl *ToFunction = nullptr;
3156  if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3157  Expr *ExplicitExpr = nullptr;
3158  if (FromConstructor->getExplicitSpecifier().getExpr()) {
3159  auto Imp = importSeq(FromConstructor->getExplicitSpecifier().getExpr());
3160  if (!Imp)
3161  return Imp.takeError();
3162  std::tie(ExplicitExpr) = *Imp;
3163  }
3164  if (GetImportedOrCreateDecl<CXXConstructorDecl>(
3165  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3166  ToInnerLocStart, NameInfo, T, TInfo,
3168  ExplicitExpr,
3169  FromConstructor->getExplicitSpecifier().getKind()),
3170  D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind()))
3171  return ToFunction;
3172  } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) {
3173 
3174  auto Imp =
3175  importSeq(const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()),
3176  FromDtor->getOperatorDeleteThisArg());
3177 
3178  if (!Imp)
3179  return Imp.takeError();
3180 
3181  FunctionDecl *ToOperatorDelete;
3182  Expr *ToThisArg;
3183  std::tie(ToOperatorDelete, ToThisArg) = *Imp;
3184 
3185  if (GetImportedOrCreateDecl<CXXDestructorDecl>(
3186  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3187  ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
3188  D->isImplicit(), D->getConstexprKind()))
3189  return ToFunction;
3190 
3191  CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction);
3192 
3193  ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg);
3194  } else if (CXXConversionDecl *FromConversion =
3195  dyn_cast<CXXConversionDecl>(D)) {
3196  Expr *ExplicitExpr = nullptr;
3197  if (FromConversion->getExplicitSpecifier().getExpr()) {
3198  auto Imp = importSeq(FromConversion->getExplicitSpecifier().getExpr());
3199  if (!Imp)
3200  return Imp.takeError();
3201  std::tie(ExplicitExpr) = *Imp;
3202  }
3203  if (GetImportedOrCreateDecl<CXXConversionDecl>(
3204  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3205  ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
3206  ExplicitSpecifier(ExplicitExpr,
3207  FromConversion->getExplicitSpecifier().getKind()),
3209  return ToFunction;
3210  } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3211  if (GetImportedOrCreateDecl<CXXMethodDecl>(
3212  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3213  ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
3214  Method->isInlineSpecified(), D->getConstexprKind(),
3215  SourceLocation()))
3216  return ToFunction;
3217  } else {
3218  if (GetImportedOrCreateDecl(
3219  ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart,
3220  NameInfo, T, TInfo, D->getStorageClass(), D->isInlineSpecified(),
3222  return ToFunction;
3223  }
3224 
3225  // Connect the redecl chain.
3226  if (FoundByLookup) {
3227  auto *Recent = const_cast<FunctionDecl *>(
3228  FoundByLookup->getMostRecentDecl());
3229  ToFunction->setPreviousDecl(Recent);
3230  // FIXME Probably we should merge exception specifications. E.g. In the
3231  // "To" context the existing function may have exception specification with
3232  // noexcept-unevaluated, while the newly imported function may have an
3233  // evaluated noexcept. A call to adjustExceptionSpec() on the imported
3234  // decl and its redeclarations may be required.
3235  }
3236 
3237  ToFunction->setQualifierInfo(ToQualifierLoc);
3238  ToFunction->setAccess(D->getAccess());
3239  ToFunction->setLexicalDeclContext(LexicalDC);
3240  ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3241  ToFunction->setTrivial(D->isTrivial());
3242  ToFunction->setPure(D->isPure());
3243  ToFunction->setDefaulted(D->isDefaulted());
3245  ToFunction->setDeletedAsWritten(D->isDeletedAsWritten());
3246  ToFunction->setRangeEnd(ToEndLoc);
3247 
3248  // Set the parameters.
3249  for (auto *Param : Parameters) {
3250  Param->setOwningFunction(ToFunction);
3251  ToFunction->addDeclInternal(Param);
3252  }
3253  ToFunction->setParams(Parameters);
3254 
3255  // We need to complete creation of FunctionProtoTypeLoc manually with setting
3256  // params it refers to.
3257  if (TInfo) {
3258  if (auto ProtoLoc =
3260  for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
3261  ProtoLoc.setParam(I, Parameters[I]);
3262  }
3263  }
3264 
3265  if (usedDifferentExceptionSpec) {
3266  // Update FunctionProtoType::ExtProtoInfo.
3267  if (ExpectedType TyOrErr = import(D->getType()))
3268  ToFunction->setType(*TyOrErr);
3269  else
3270  return TyOrErr.takeError();
3271  }
3272 
3273  // Import the describing template function, if any.
3274  if (FromFT) {
3275  auto ToFTOrErr = import(FromFT);
3276  if (!ToFTOrErr)
3277  return ToFTOrErr.takeError();
3278  }
3279 
3280  // Import Ctor initializers.
3281  if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3282  if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
3283  SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
3284  // Import first, then allocate memory and copy if there was no error.
3285  if (Error Err = ImportContainerChecked(
3286  FromConstructor->inits(), CtorInitializers))
3287  return std::move(Err);
3288  auto **Memory =
3289  new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
3290  std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
3291  auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
3292  ToCtor->setCtorInitializers(Memory);
3293  ToCtor->setNumCtorInitializers(NumInitializers);
3294  }
3295  }
3296 
3297  if (D->doesThisDeclarationHaveABody()) {
3298  Error Err = ImportFunctionDeclBody(D, ToFunction);
3299 
3300  if (Err)
3301  return std::move(Err);
3302  }
3303 
3304  // FIXME: Other bits to merge?
3305 
3306  // If it is a template, import all related things.
3307  if (Error Err = ImportTemplateInformation(D, ToFunction))
3308  return std::move(Err);
3309 
3311 
3312  // TODO Can we generalize this approach to other AST nodes as well?
3313  if (D->getDeclContext()->containsDeclAndLoad(D))
3314  DC->addDeclInternal(ToFunction);
3315  if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
3316  LexicalDC->addDeclInternal(ToFunction);
3317 
3318  // Friend declaration's lexical context is the befriending class, but the
3319  // semantic context is the enclosing scope of the befriending class.
3320  // We want the friend functions to be found in the semantic context by lookup.
3321  // FIXME should we handle this generically in VisitFriendDecl?
3322  // In Other cases when LexicalDC != DC we don't want it to be added,
3323  // e.g out-of-class definitions like void B::f() {} .
3324  if (LexicalDC != DC && IsFriend) {
3325  DC->makeDeclVisibleInContext(ToFunction);
3326  }
3327 
3328  if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
3329  if (Error Err = ImportOverriddenMethods(cast<CXXMethodDecl>(ToFunction),
3330  FromCXXMethod))
3331  return std::move(Err);
3332 
3333  // Import the rest of the chain. I.e. import all subsequent declarations.
3334  for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3335  ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3336  if (!ToRedeclOrErr)
3337  return ToRedeclOrErr.takeError();
3338  }
3339 
3340  return ToFunction;
3341 }
3342 
3344  return VisitFunctionDecl(D);
3345 }
3346 
3348  return VisitCXXMethodDecl(D);
3349 }
3350 
3352  return VisitCXXMethodDecl(D);
3353 }
3354 
3356  return VisitCXXMethodDecl(D);
3357 }
3358 
3360  // Import the major distinguishing characteristics of a variable.
3361  DeclContext *DC, *LexicalDC;
3362  DeclarationName Name;
3363  SourceLocation Loc;
3364  NamedDecl *ToD;
3365  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3366  return std::move(Err);
3367  if (ToD)
3368  return ToD;
3369 
3370  // Determine whether we've already imported this field.
3371  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3372  for (auto *FoundDecl : FoundDecls) {
3373  if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
3374  // For anonymous fields, match up by index.
3375  if (!Name &&
3377  ASTImporter::getFieldIndex(FoundField))
3378  continue;
3379 
3380  if (Importer.IsStructurallyEquivalent(D->getType(),
3381  FoundField->getType())) {
3382  Importer.MapImported(D, FoundField);
3383  // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
3384  // initializer of a FieldDecl might not had been instantiated in the
3385  // "To" context. However, the "From" context might instantiated that,
3386  // thus we have to merge that.
3387  if (Expr *FromInitializer = D->getInClassInitializer()) {
3388  // We don't have yet the initializer set.
3389  if (FoundField->hasInClassInitializer() &&
3390  !FoundField->getInClassInitializer()) {
3391  if (ExpectedExpr ToInitializerOrErr = import(FromInitializer))
3392  FoundField->setInClassInitializer(*ToInitializerOrErr);
3393  else {
3394  // We can't return error here,
3395  // since we already mapped D as imported.
3396  // FIXME: warning message?
3397  consumeError(ToInitializerOrErr.takeError());
3398  return FoundField;
3399  }
3400  }
3401  }
3402  return FoundField;
3403  }
3404 
3405  // FIXME: Why is this case not handled with calling HandleNameConflict?
3406  Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3407  << Name << D->getType() << FoundField->getType();
3408  Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3409  << FoundField->getType();
3410 
3411  return make_error<ImportError>(ImportError::NameConflict);
3412  }
3413  }
3414 
3415  QualType ToType;
3416  TypeSourceInfo *ToTInfo;
3417  Expr *ToBitWidth;
3418  SourceLocation ToInnerLocStart;
3419  Expr *ToInitializer;
3420  if (auto Imp = importSeq(
3421  D->getType(), D->getTypeSourceInfo(), D->getBitWidth(),
3423  std::tie(
3424  ToType, ToTInfo, ToBitWidth, ToInnerLocStart, ToInitializer) = *Imp;
3425  else
3426  return Imp.takeError();
3427 
3428  FieldDecl *ToField;
3429  if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
3430  ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3431  ToType, ToTInfo, ToBitWidth, D->isMutable(),
3432  D->getInClassInitStyle()))
3433  return ToField;
3434 
3435  ToField->setAccess(D->getAccess());
3436  ToField->setLexicalDeclContext(LexicalDC);
3437  if (ToInitializer)
3438  ToField->setInClassInitializer(ToInitializer);
3439  ToField->setImplicit(D->isImplicit());
3440  LexicalDC->addDeclInternal(ToField);
3441  return ToField;
3442 }
3443 
3445  // Import the major distinguishing characteristics of a variable.
3446  DeclContext *DC, *LexicalDC;
3447  DeclarationName Name;
3448  SourceLocation Loc;
3449  NamedDecl *ToD;
3450  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3451  return std::move(Err);
3452  if (ToD)
3453  return ToD;
3454 
3455  // Determine whether we've already imported this field.
3456  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3457  for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3458  if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3459  // For anonymous indirect fields, match up by index.
3460  if (!Name &&
3462  ASTImporter::getFieldIndex(FoundField))
3463  continue;
3464 
3465  if (Importer.IsStructurallyEquivalent(D->getType(),
3466  FoundField->getType(),
3467  !Name.isEmpty())) {
3468  Importer.MapImported(D, FoundField);
3469  return FoundField;
3470  }
3471 
3472  // If there are more anonymous fields to check, continue.
3473  if (!Name && I < N-1)
3474  continue;
3475 
3476  // FIXME: Why is this case not handled with calling HandleNameConflict?
3477  Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3478  << Name << D->getType() << FoundField->getType();
3479  Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3480  << FoundField->getType();
3481 
3482  return make_error<ImportError>(ImportError::NameConflict);
3483  }
3484  }
3485 
3486  // Import the type.
3487  auto TypeOrErr = import(D->getType());
3488  if (!TypeOrErr)
3489  return TypeOrErr.takeError();
3490 
3491  auto **NamedChain =
3492  new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
3493 
3494  unsigned i = 0;
3495  for (auto *PI : D->chain())
3496  if (Expected<NamedDecl *> ToD = import(PI))
3497  NamedChain[i++] = *ToD;
3498  else
3499  return ToD.takeError();
3500 
3501  llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
3502  IndirectFieldDecl *ToIndirectField;
3503  if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
3504  Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
3505  // FIXME here we leak `NamedChain` which is allocated before
3506  return ToIndirectField;
3507 
3508  ToIndirectField->setAccess(D->getAccess());
3509  ToIndirectField->setLexicalDeclContext(LexicalDC);
3510  LexicalDC->addDeclInternal(ToIndirectField);
3511  return ToIndirectField;
3512 }
3513 
3515  // Import the major distinguishing characteristics of a declaration.
3516  DeclContext *DC, *LexicalDC;
3517  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
3518  return std::move(Err);
3519 
3520  // Determine whether we've already imported this decl.
3521  // FriendDecl is not a NamedDecl so we cannot use lookup.
3522  auto *RD = cast<CXXRecordDecl>(DC);
3523  FriendDecl *ImportedFriend = RD->getFirstFriend();
3524 
3525  while (ImportedFriend) {
3526  if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
3527  if (IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(),
3528  /*Complain=*/false))
3529  return Importer.MapImported(D, ImportedFriend);
3530 
3531  } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
3532  if (Importer.IsStructurallyEquivalent(
3533  D->getFriendType()->getType(),
3534  ImportedFriend->getFriendType()->getType(), true))
3535  return Importer.MapImported(D, ImportedFriend);
3536  }
3537  ImportedFriend = ImportedFriend->getNextFriend();
3538  }
3539 
3540  // Not found. Create it.
3542  if (NamedDecl *FriendD = D->getFriendDecl()) {
3543  NamedDecl *ToFriendD;
3544  if (Error Err = importInto(ToFriendD, FriendD))
3545  return std::move(Err);
3546 
3547  if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
3548  !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
3549  ToFriendD->setObjectOfFriendDecl(false);
3550 
3551  ToFU = ToFriendD;
3552  } else { // The friend is a type, not a decl.
3553  if (auto TSIOrErr = import(D->getFriendType()))
3554  ToFU = *TSIOrErr;
3555  else
3556  return TSIOrErr.takeError();
3557  }
3558 
3559  SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
3560  auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
3561  for (unsigned I = 0; I < D->NumTPLists; I++) {
3562  if (auto ListOrErr = import(FromTPLists[I]))
3563  ToTPLists[I] = *ListOrErr;
3564  else
3565  return ListOrErr.takeError();
3566  }
3567 
3568  auto LocationOrErr = import(D->getLocation());
3569  if (!LocationOrErr)
3570  return LocationOrErr.takeError();
3571  auto FriendLocOrErr = import(D->getFriendLoc());
3572  if (!FriendLocOrErr)
3573  return FriendLocOrErr.takeError();
3574 
3575  FriendDecl *FrD;
3576  if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
3577  *LocationOrErr, ToFU,
3578  *FriendLocOrErr, ToTPLists))
3579  return FrD;
3580 
3581  FrD->setAccess(D->getAccess());
3582  FrD->setLexicalDeclContext(LexicalDC);
3583  LexicalDC->addDeclInternal(FrD);
3584  return FrD;
3585 }
3586 
3588  // Import the major distinguishing characteristics of an ivar.
3589  DeclContext *DC, *LexicalDC;
3590  DeclarationName Name;
3591  SourceLocation Loc;
3592  NamedDecl *ToD;
3593  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3594  return std::move(Err);
3595  if (ToD)
3596  return ToD;
3597 
3598  // Determine whether we've already imported this ivar
3599  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3600  for (auto *FoundDecl : FoundDecls) {
3601  if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
3602  if (Importer.IsStructurallyEquivalent(D->getType(),
3603  FoundIvar->getType())) {
3604  Importer.MapImported(D, FoundIvar);
3605  return FoundIvar;
3606  }
3607 
3608  Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent)
3609  << Name << D->getType() << FoundIvar->getType();
3610  Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3611  << FoundIvar->getType();
3612 
3613  return make_error<ImportError>(ImportError::NameConflict);
3614  }
3615  }
3616 
3617  QualType ToType;
3618  TypeSourceInfo *ToTypeSourceInfo;
3619  Expr *ToBitWidth;
3620  SourceLocation ToInnerLocStart;
3621  if (auto Imp = importSeq(
3622  D->getType(), D->getTypeSourceInfo(), D->getBitWidth(), D->getInnerLocStart()))
3623  std::tie(ToType, ToTypeSourceInfo, ToBitWidth, ToInnerLocStart) = *Imp;
3624  else
3625  return Imp.takeError();
3626 
3627  ObjCIvarDecl *ToIvar;
3628  if (GetImportedOrCreateDecl(
3629  ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
3630  ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3631  ToType, ToTypeSourceInfo,
3632  D->getAccessControl(),ToBitWidth, D->getSynthesize()))
3633  return ToIvar;
3634 
3635  ToIvar->setLexicalDeclContext(LexicalDC);
3636  LexicalDC->addDeclInternal(ToIvar);
3637  return ToIvar;
3638 }
3639 
3641 
3643  auto RedeclIt = Redecls.begin();
3644  // Import the first part of the decl chain. I.e. import all previous
3645  // declarations starting from the canonical decl.
3646  for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3647  ExpectedDecl RedeclOrErr = import(*RedeclIt);
3648  if (!RedeclOrErr)
3649  return RedeclOrErr.takeError();
3650  }
3651  assert(*RedeclIt == D);
3652 
3653  // Import the major distinguishing characteristics of a variable.
3654  DeclContext *DC, *LexicalDC;
3655  DeclarationName Name;
3656  SourceLocation Loc;
3657  NamedDecl *ToD;
3658  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3659  return std::move(Err);
3660  if (ToD)
3661  return ToD;
3662 
3663  // Try to find a variable in our own ("to") context with the same name and
3664  // in the same context as the variable we're importing.
3665  VarDecl *FoundByLookup = nullptr;
3666  if (D->isFileVarDecl()) {
3667  SmallVector<NamedDecl *, 4> ConflictingDecls;
3668  unsigned IDNS = Decl::IDNS_Ordinary;
3669  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3670  for (auto *FoundDecl : FoundDecls) {
3671  if (!FoundDecl->isInIdentifierNamespace(IDNS))
3672  continue;
3673 
3674  if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
3675  if (!hasSameVisibilityContext(FoundVar, D))
3676  continue;
3677  if (Importer.IsStructurallyEquivalent(D->getType(),
3678  FoundVar->getType())) {
3679 
3680  // The VarDecl in the "From" context has a definition, but in the
3681  // "To" context we already have a definition.
3682  VarDecl *FoundDef = FoundVar->getDefinition();
3683  if (D->isThisDeclarationADefinition() && FoundDef)
3684  // FIXME Check for ODR error if the two definitions have
3685  // different initializers?
3686  return Importer.MapImported(D, FoundDef);
3687 
3688  // The VarDecl in the "From" context has an initializer, but in the
3689  // "To" context we already have an initializer.
3690  const VarDecl *FoundDInit = nullptr;
3691  if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
3692  // FIXME Diagnose ODR error if the two initializers are different?
3693  return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
3694 
3695  FoundByLookup = FoundVar;
3696  break;
3697  }
3698 
3699  const ArrayType *FoundArray
3700  = Importer.getToContext().getAsArrayType(FoundVar->getType());
3701  const ArrayType *TArray
3702  = Importer.getToContext().getAsArrayType(D->getType());
3703  if (FoundArray && TArray) {
3704  if (isa<IncompleteArrayType>(FoundArray) &&
3705  isa<ConstantArrayType>(TArray)) {
3706  // Import the type.
3707  if (auto TyOrErr = import(D->getType()))
3708  FoundVar->setType(*TyOrErr);
3709  else
3710  return TyOrErr.takeError();
3711 
3712  FoundByLookup = FoundVar;
3713  break;
3714  } else if (isa<IncompleteArrayType>(TArray) &&
3715  isa<ConstantArrayType>(FoundArray)) {
3716  FoundByLookup = FoundVar;
3717  break;
3718  }
3719  }
3720 
3721  Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent)
3722  << Name << D->getType() << FoundVar->getType();
3723  Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3724  << FoundVar->getType();
3725  ConflictingDecls.push_back(FoundDecl);
3726  }
3727  }
3728 
3729  if (!ConflictingDecls.empty()) {
3730  ExpectedName NameOrErr = Importer.HandleNameConflict(
3731  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3732  if (NameOrErr)
3733  Name = NameOrErr.get();
3734  else
3735  return NameOrErr.takeError();
3736  }
3737  }
3738 
3739  QualType ToType;
3740  TypeSourceInfo *ToTypeSourceInfo;
3741  SourceLocation ToInnerLocStart;
3742  NestedNameSpecifierLoc ToQualifierLoc;
3743  if (auto Imp = importSeq(
3744  D->getType(), D->getTypeSourceInfo(), D->getInnerLocStart(),
3745  D->getQualifierLoc()))
3746  std::tie(ToType, ToTypeSourceInfo, ToInnerLocStart, ToQualifierLoc) = *Imp;
3747  else
3748  return Imp.takeError();
3749 
3750  // Create the imported variable.
3751  VarDecl *ToVar;
3752  if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
3753  ToInnerLocStart, Loc,
3754  Name.getAsIdentifierInfo(),
3755  ToType, ToTypeSourceInfo,
3756  D->getStorageClass()))
3757  return ToVar;
3758 
3759  ToVar->setQualifierInfo(ToQualifierLoc);
3760  ToVar->setAccess(D->getAccess());
3761  ToVar->setLexicalDeclContext(LexicalDC);
3762 
3763  if (FoundByLookup) {
3764  auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
3765  ToVar->setPreviousDecl(Recent);
3766  }
3767 
3768  if (Error Err = ImportInitializer(D, ToVar))
3769  return std::move(Err);
3770 
3771  if (D->isConstexpr())
3772  ToVar->setConstexpr(true);
3773 
3774  if (D->getDeclContext()->containsDeclAndLoad(D))
3775  DC->addDeclInternal(ToVar);
3776  if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
3777  LexicalDC->addDeclInternal(ToVar);
3778 
3779  // Import the rest of the chain. I.e. import all subsequent declarations.
3780  for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3781  ExpectedDecl RedeclOrErr = import(*RedeclIt);
3782  if (!RedeclOrErr)
3783  return RedeclOrErr.takeError();
3784  }
3785 
3786  return ToVar;
3787 }
3788 
3790  // Parameters are created in the translation unit's context, then moved
3791  // into the function declaration's context afterward.
3792  DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3793 
3794  DeclarationName ToDeclName;
3795  SourceLocation ToLocation;
3796  QualType ToType;
3797  if (auto Imp = importSeq(D->getDeclName(), D->getLocation(), D->getType()))
3798  std::tie(ToDeclName, ToLocation, ToType) = *Imp;
3799  else
3800  return Imp.takeError();
3801 
3802  // Create the imported parameter.
3803  ImplicitParamDecl *ToParm = nullptr;
3804  if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
3805  ToLocation, ToDeclName.getAsIdentifierInfo(),
3806  ToType, D->getParameterKind()))
3807  return ToParm;
3808  return ToParm;
3809 }
3810 
3812  const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
3813  ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg());
3814  ToParam->setKNRPromoted(FromParam->isKNRPromoted());
3815 
3816  if (FromParam->hasUninstantiatedDefaultArg()) {
3817  if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg()))
3818  ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
3819  else
3820  return ToDefArgOrErr.takeError();
3821  } else if (FromParam->hasUnparsedDefaultArg()) {
3822  ToParam->setUnparsedDefaultArg();
3823  } else if (FromParam->hasDefaultArg()) {
3824  if (auto ToDefArgOrErr = import(FromParam->getDefaultArg()))
3825  ToParam->setDefaultArg(*ToDefArgOrErr);
3826  else
3827  return ToDefArgOrErr.takeError();
3828  }
3829 
3830  return Error::success();
3831 }
3832 
3834  // Parameters are created in the translation unit's context, then moved
3835  // into the function declaration's context afterward.
3836  DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3837 
3838  DeclarationName ToDeclName;
3839  SourceLocation ToLocation, ToInnerLocStart;
3840  QualType ToType;
3841  TypeSourceInfo *ToTypeSourceInfo;
3842  if (auto Imp = importSeq(
3843  D->getDeclName(), D->getLocation(), D->getType(), D->getInnerLocStart(),
3844  D->getTypeSourceInfo()))
3845  std::tie(
3846  ToDeclName, ToLocation, ToType, ToInnerLocStart,
3847  ToTypeSourceInfo) = *Imp;
3848  else
3849  return Imp.takeError();
3850 
3851  ParmVarDecl *ToParm;
3852  if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
3853  ToInnerLocStart, ToLocation,
3854  ToDeclName.getAsIdentifierInfo(), ToType,
3855  ToTypeSourceInfo, D->getStorageClass(),
3856  /*DefaultArg*/ nullptr))
3857  return ToParm;
3858 
3859  // Set the default argument. It should be no problem if it was already done.
3860  // Do not import the default expression before GetImportedOrCreateDecl call
3861  // to avoid possible infinite import loop because circular dependency.
3862  if (Error Err = ImportDefaultArgOfParmVarDecl(D, ToParm))
3863  return std::move(Err);
3864 
3865  if (D->isObjCMethodParameter()) {
3868  } else {
3869  ToParm->setScopeInfo(D->getFunctionScopeDepth(),
3870  D->getFunctionScopeIndex());
3871  }
3872 
3873  return ToParm;
3874 }
3875 
3877  // Import the major distinguishing characteristics of a method.
3878  DeclContext *DC, *LexicalDC;
3879  DeclarationName Name;
3880  SourceLocation Loc;
3881  NamedDecl *ToD;
3882  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3883  return std::move(Err);
3884  if (ToD)
3885  return ToD;
3886 
3887  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3888  for (auto *FoundDecl : FoundDecls) {
3889  if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
3890  if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3891  continue;
3892 
3893  // Check return types.
3894  if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3895  FoundMethod->getReturnType())) {
3896  Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent)
3897  << D->isInstanceMethod() << Name << D->getReturnType()
3898  << FoundMethod->getReturnType();
3899  Importer.ToDiag(FoundMethod->getLocation(),
3900  diag::note_odr_objc_method_here)
3901  << D->isInstanceMethod() << Name;
3902 
3903  return make_error<ImportError>(ImportError::NameConflict);
3904  }
3905 
3906  // Check the number of parameters.
3907  if (D->param_size() != FoundMethod->param_size()) {
3908  Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent)
3909  << D->isInstanceMethod() << Name
3910  << D->param_size() << FoundMethod->param_size();
3911  Importer.ToDiag(FoundMethod->getLocation(),
3912  diag::note_odr_objc_method_here)
3913  << D->isInstanceMethod() << Name;
3914 
3915  return make_error<ImportError>(ImportError::NameConflict);
3916  }
3917 
3918  // Check parameter types.
3920  PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3921  P != PEnd; ++P, ++FoundP) {
3922  if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3923  (*FoundP)->getType())) {
3924  Importer.FromDiag((*P)->getLocation(),
3925  diag::warn_odr_objc_method_param_type_inconsistent)
3926  << D->isInstanceMethod() << Name
3927  << (*P)->getType() << (*FoundP)->getType();
3928  Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3929  << (*FoundP)->getType();
3930 
3931  return make_error<ImportError>(ImportError::NameConflict);
3932  }
3933  }
3934 
3935  // Check variadic/non-variadic.
3936  // Check the number of parameters.
3937  if (D->isVariadic() != FoundMethod->isVariadic()) {
3938  Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent)
3939  << D->isInstanceMethod() << Name;
3940  Importer.ToDiag(FoundMethod->getLocation(),
3941  diag::note_odr_objc_method_here)
3942  << D->isInstanceMethod() << Name;
3943 
3944  return make_error<ImportError>(ImportError::NameConflict);
3945  }
3946 
3947  // FIXME: Any other bits we need to merge?
3948  return Importer.MapImported(D, FoundMethod);
3949  }
3950  }
3951 
3952  SourceLocation ToEndLoc;
3953  QualType ToReturnType;
3954  TypeSourceInfo *ToReturnTypeSourceInfo;
3955  if (auto Imp = importSeq(
3957  std::tie(ToEndLoc, ToReturnType, ToReturnTypeSourceInfo) = *Imp;
3958  else
3959  return Imp.takeError();
3960 
3961  ObjCMethodDecl *ToMethod;
3962  if (GetImportedOrCreateDecl(
3963  ToMethod, D, Importer.getToContext(), Loc,
3964  ToEndLoc, Name.getObjCSelector(), ToReturnType,
3965  ToReturnTypeSourceInfo, DC, D->isInstanceMethod(), D->isVariadic(),
3966  D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3968  return ToMethod;
3969 
3970  // FIXME: When we decide to merge method definitions, we'll need to
3971  // deal with implicit parameters.
3972 
3973  // Import the parameters
3975  for (auto *FromP : D->parameters()) {
3976  if (Expected<ParmVarDecl *> ToPOrErr = import(FromP))
3977  ToParams.push_back(*ToPOrErr);
3978  else
3979  return ToPOrErr.takeError();
3980  }
3981 
3982  // Set the parameters.
3983  for (auto *ToParam : ToParams) {
3984  ToParam->setOwningFunction(ToMethod);
3985  ToMethod->addDeclInternal(ToParam);
3986  }
3987 
3988  SmallVector<SourceLocation, 12> FromSelLocs;
3989  D->getSelectorLocs(FromSelLocs);
3990  SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
3991  if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs))
3992  return std::move(Err);
3993 
3994  ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs);
3995 
3996  ToMethod->setLexicalDeclContext(LexicalDC);
3997  LexicalDC->addDeclInternal(ToMethod);
3998  return ToMethod;
3999 }
4000 
4002  // Import the major distinguishing characteristics of a category.
4003  DeclContext *DC, *LexicalDC;
4004  DeclarationName Name;
4005  SourceLocation Loc;
4006  NamedDecl *ToD;
4007  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4008  return std::move(Err);
4009  if (ToD)
4010  return ToD;
4011 
4012  SourceLocation ToVarianceLoc, ToLocation, ToColonLoc;
4013  TypeSourceInfo *ToTypeSourceInfo;
4014  if (auto Imp = importSeq(
4015  D->getVarianceLoc(), D->getLocation(), D->getColonLoc(),
4016  D->getTypeSourceInfo()))
4017  std::tie(ToVarianceLoc, ToLocation, ToColonLoc, ToTypeSourceInfo) = *Imp;
4018  else
4019  return Imp.takeError();
4020 
4022  if (GetImportedOrCreateDecl(
4023  Result, D, Importer.getToContext(), DC, D->getVariance(),
4024  ToVarianceLoc, D->getIndex(),
4025  ToLocation, Name.getAsIdentifierInfo(),
4026  ToColonLoc, ToTypeSourceInfo))
4027  return Result;
4028 
4029  Result->setLexicalDeclContext(LexicalDC);
4030  return Result;
4031 }
4032 
4034  // Import the major distinguishing characteristics of a category.
4035  DeclContext *DC, *LexicalDC;
4036  DeclarationName Name;
4037  SourceLocation Loc;
4038  NamedDecl *ToD;
4039  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4040  return std::move(Err);
4041  if (ToD)
4042  return ToD;
4043 
4044  ObjCInterfaceDecl *ToInterface;
4045  if (Error Err = importInto(ToInterface, D->getClassInterface()))
4046  return std::move(Err);
4047 
4048  // Determine if we've already encountered this category.
4049  ObjCCategoryDecl *MergeWithCategory
4050  = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
4051  ObjCCategoryDecl *ToCategory = MergeWithCategory;
4052  if (!ToCategory) {
4053  SourceLocation ToAtStartLoc, ToCategoryNameLoc;
4054  SourceLocation ToIvarLBraceLoc, ToIvarRBraceLoc;
4055  if (auto Imp = importSeq(
4056  D->getAtStartLoc(), D->getCategoryNameLoc(),
4057  D->getIvarLBraceLoc(), D->getIvarRBraceLoc()))
4058  std::tie(
4059  ToAtStartLoc, ToCategoryNameLoc,
4060  ToIvarLBraceLoc, ToIvarRBraceLoc) = *Imp;
4061  else
4062  return Imp.takeError();
4063 
4064  if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
4065  ToAtStartLoc, Loc,
4066  ToCategoryNameLoc,
4067  Name.getAsIdentifierInfo(), ToInterface,
4068  /*TypeParamList=*/nullptr,
4069  ToIvarLBraceLoc,
4070  ToIvarRBraceLoc))
4071  return ToCategory;
4072 
4073  ToCategory->setLexicalDeclContext(LexicalDC);
4074  LexicalDC->addDeclInternal(ToCategory);
4075  // Import the type parameter list after MapImported, to avoid
4076  // loops when bringing in their DeclContext.
4077  if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList()))
4078  ToCategory->setTypeParamList(*PListOrErr);
4079  else
4080  return PListOrErr.takeError();
4081 
4082  // Import protocols
4084  SmallVector<SourceLocation, 4> ProtocolLocs;
4086  = D->protocol_loc_begin();
4088  FromProtoEnd = D->protocol_end();
4089  FromProto != FromProtoEnd;
4090  ++FromProto, ++FromProtoLoc) {
4091  if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4092  Protocols.push_back(*ToProtoOrErr);
4093  else
4094  return ToProtoOrErr.takeError();
4095 
4096  if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4097  ProtocolLocs.push_back(*ToProtoLocOrErr);
4098  else
4099  return ToProtoLocOrErr.takeError();
4100  }
4101 
4102  // FIXME: If we're merging, make sure that the protocol list is the same.
4103  ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
4104  ProtocolLocs.data(), Importer.getToContext());
4105 
4106  } else {
4107  Importer.MapImported(D, ToCategory);
4108  }
4109 
4110  // Import all of the members of this category.
4111  if (Error Err = ImportDeclContext(D))
4112  return std::move(Err);
4113 
4114  // If we have an implementation, import it as well.
4115  if (D->getImplementation()) {
4116  if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
4117  import(D->getImplementation()))
4118  ToCategory->setImplementation(*ToImplOrErr);
4119  else
4120  return ToImplOrErr.takeError();
4121  }
4122 
4123  return ToCategory;
4124 }
4125 
4128  if (To->getDefinition()) {
4129  if (shouldForceImportDeclContext(Kind))
4130  if (Error Err = ImportDeclContext(From))
4131  return Err;
4132  return Error::success();
4133  }
4134 
4135  // Start the protocol definition
4136  To->startDefinition();
4137 
4138  // Import protocols
4140  SmallVector<SourceLocation, 4> ProtocolLocs;
4142  From->protocol_loc_begin();
4143  for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
4144  FromProtoEnd = From->protocol_end();
4145  FromProto != FromProtoEnd;
4146  ++FromProto, ++FromProtoLoc) {
4147  if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4148  Protocols.push_back(*ToProtoOrErr);
4149  else
4150  return ToProtoOrErr.takeError();
4151 
4152  if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4153  ProtocolLocs.push_back(*ToProtoLocOrErr);
4154  else
4155  return ToProtoLocOrErr.takeError();
4156 
4157  }
4158 
4159  // FIXME: If we're merging, make sure that the protocol list is the same.
4160  To->setProtocolList(Protocols.data(), Protocols.size(),
4161  ProtocolLocs.data(), Importer.getToContext());
4162 
4163  if (shouldForceImportDeclContext(Kind)) {
4164  // Import all of the members of this protocol.
4165  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4166  return Err;
4167  }
4168  return Error::success();
4169 }
4170 
4172  // If this protocol has a definition in the translation unit we're coming
4173  // from, but this particular declaration is not that definition, import the
4174  // definition and map to that.
4175  ObjCProtocolDecl *Definition = D->getDefinition();
4176  if (Definition && Definition != D) {
4177  if (ExpectedDecl ImportedDefOrErr = import(Definition))
4178  return Importer.MapImported(D, *ImportedDefOrErr);
4179  else
4180  return ImportedDefOrErr.takeError();
4181  }
4182 
4183  // Import the major distinguishing characteristics of a protocol.
4184  DeclContext *DC, *LexicalDC;
4185  DeclarationName Name;
4186  SourceLocation Loc;
4187  NamedDecl *ToD;
4188  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4189  return std::move(Err);
4190  if (ToD)
4191  return ToD;
4192 
4193  ObjCProtocolDecl *MergeWithProtocol = nullptr;
4194  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4195  for (auto *FoundDecl : FoundDecls) {
4197  continue;
4198 
4199  if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
4200  break;
4201  }
4202 
4203  ObjCProtocolDecl *ToProto = MergeWithProtocol;
4204  if (!ToProto) {
4205  auto ToAtBeginLocOrErr = import(D->getAtStartLoc());
4206  if (!ToAtBeginLocOrErr)
4207  return ToAtBeginLocOrErr.takeError();
4208 
4209  if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
4210  Name.getAsIdentifierInfo(), Loc,
4211  *ToAtBeginLocOrErr,
4212  /*PrevDecl=*/nullptr))
4213  return ToProto;
4214  ToProto->setLexicalDeclContext(LexicalDC);
4215  LexicalDC->addDeclInternal(ToProto);
4216  }
4217 
4218  Importer.MapImported(D, ToProto);
4219 
4221  if (Error Err = ImportDefinition(D, ToProto))
4222  return std::move(Err);
4223 
4224  return ToProto;
4225 }
4226 
4228  DeclContext *DC, *LexicalDC;
4229  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4230  return std::move(Err);
4231 
4232  ExpectedSLoc ExternLocOrErr = import(D->getExternLoc());
4233  if (!ExternLocOrErr)
4234  return ExternLocOrErr.takeError();
4235 
4236  ExpectedSLoc LangLocOrErr = import(D->getLocation());
4237  if (!LangLocOrErr)
4238  return LangLocOrErr.takeError();
4239 
4240  bool HasBraces = D->hasBraces();
4241 
4242  LinkageSpecDecl *ToLinkageSpec;
4243  if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
4244  *ExternLocOrErr, *LangLocOrErr,
4245  D->getLanguage(), HasBraces))
4246  return ToLinkageSpec;
4247 
4248  if (HasBraces) {
4249  ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
4250  if (!RBraceLocOrErr)
4251  return RBraceLocOrErr.takeError();
4252  ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
4253  }
4254 
4255  ToLinkageSpec->setLexicalDeclContext(LexicalDC);
4256  LexicalDC->addDeclInternal(ToLinkageSpec);
4257 
4258  return ToLinkageSpec;
4259 }
4260 
4262  DeclContext *DC, *LexicalDC;
4263  DeclarationName Name;
4264  SourceLocation Loc;
4265  NamedDecl *ToD = nullptr;
4266  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4267  return std::move(Err);
4268  if (ToD)
4269  return ToD;
4270 
4271  SourceLocation ToLoc, ToUsingLoc;
4272  NestedNameSpecifierLoc ToQualifierLoc;
4273  if (auto Imp = importSeq(
4274  D->getNameInfo().getLoc(), D->getUsingLoc(), D->getQualifierLoc()))
4275  std::tie(ToLoc, ToUsingLoc, ToQualifierLoc) = *Imp;
4276  else
4277  return Imp.takeError();
4278 
4279  DeclarationNameInfo NameInfo(Name, ToLoc);
4280  if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4281  return std::move(Err);
4282 
4283  UsingDecl *ToUsing;
4284  if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4285  ToUsingLoc, ToQualifierLoc, NameInfo,
4286  D->hasTypename()))
4287  return ToUsing;
4288 
4289  ToUsing->setLexicalDeclContext(LexicalDC);
4290  LexicalDC->addDeclInternal(ToUsing);
4291 
4292  if (NamedDecl *FromPattern =
4293  Importer.getFromContext().getInstantiatedFromUsingDecl(D)) {
4294  if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern))
4295  Importer.getToContext().setInstantiatedFromUsingDecl(
4296  ToUsing, *ToPatternOrErr);
4297  else
4298  return ToPatternOrErr.takeError();
4299  }
4300 
4301  for (UsingShadowDecl *FromShadow : D->shadows()) {
4302  if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow))
4303  ToUsing->addShadowDecl(*ToShadowOrErr);
4304  else
4305  // FIXME: We return error here but the definition is already created
4306  // and available with lookups. How to fix this?..
4307  return ToShadowOrErr.takeError();
4308  }
4309  return ToUsing;
4310 }
4311 
4313  DeclContext *DC, *LexicalDC;
4314  DeclarationName Name;
4315  SourceLocation Loc;
4316  NamedDecl *ToD = nullptr;
4317  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4318  return std::move(Err);
4319  if (ToD)
4320  return ToD;
4321 
4322  Expected<UsingDecl *> ToUsingOrErr = import(D->getUsingDecl());
4323  if (!ToUsingOrErr)
4324  return ToUsingOrErr.takeError();
4325 
4326  Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl());
4327  if (!ToTargetOrErr)
4328  return ToTargetOrErr.takeError();
4329 
4330  UsingShadowDecl *ToShadow;
4331  if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
4332  *ToUsingOrErr, *ToTargetOrErr))
4333  return ToShadow;
4334 
4335  ToShadow->setLexicalDeclContext(LexicalDC);
4336  ToShadow->setAccess(D->getAccess());
4337 
4338  if (UsingShadowDecl *FromPattern =
4339  Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) {
4340  if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern))
4341  Importer.getToContext().setInstantiatedFromUsingShadowDecl(
4342  ToShadow, *ToPatternOrErr);
4343  else
4344  // FIXME: We return error here but the definition is already created
4345  // and available with lookups. How to fix this?..
4346  return ToPatternOrErr.takeError();
4347  }
4348 
4349  LexicalDC->addDeclInternal(ToShadow);
4350 
4351  return ToShadow;
4352 }
4353 
4355  DeclContext *DC, *LexicalDC;
4356  DeclarationName Name;
4357  SourceLocation Loc;
4358  NamedDecl *ToD = nullptr;
4359  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4360  return std::move(Err);
4361  if (ToD)
4362  return ToD;
4363 
4364  auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor());
4365  if (!ToComAncestorOrErr)
4366  return ToComAncestorOrErr.takeError();
4367 
4368  NamespaceDecl *ToNominatedNamespace;
4369  SourceLocation ToUsingLoc, ToNamespaceKeyLocation, ToIdentLocation;
4370  NestedNameSpecifierLoc ToQualifierLoc;
4371  if (auto Imp = importSeq(
4374  D->getIdentLocation()))
4375  std::tie(
4376  ToNominatedNamespace, ToUsingLoc, ToNamespaceKeyLocation,
4377  ToQualifierLoc, ToIdentLocation) = *Imp;
4378  else
4379  return Imp.takeError();
4380 
4381  UsingDirectiveDecl *ToUsingDir;
4382  if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
4383  ToUsingLoc,
4384  ToNamespaceKeyLocation,
4385  ToQualifierLoc,
4386  ToIdentLocation,
4387  ToNominatedNamespace, *ToComAncestorOrErr))
4388  return ToUsingDir;
4389 
4390  ToUsingDir->setLexicalDeclContext(LexicalDC);
4391  LexicalDC->addDeclInternal(ToUsingDir);
4392 
4393  return ToUsingDir;
4394 }
4395 
4398  DeclContext *DC, *LexicalDC;
4399  DeclarationName Name;
4400  SourceLocation Loc;
4401  NamedDecl *ToD = nullptr;
4402  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4403  return std::move(Err);
4404  if (ToD)
4405  return ToD;
4406 
4407  SourceLocation ToLoc, ToUsingLoc, ToEllipsisLoc;
4408  NestedNameSpecifierLoc ToQualifierLoc;
4409  if (auto Imp = importSeq(
4410  D->getNameInfo().getLoc(), D->getUsingLoc(), D->getQualifierLoc(),
4411  D->getEllipsisLoc()))
4412  std::tie(ToLoc, ToUsingLoc, ToQualifierLoc, ToEllipsisLoc) = *Imp;
4413  else
4414  return Imp.takeError();
4415 
4416  DeclarationNameInfo NameInfo(Name, ToLoc);
4417  if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4418  return std::move(Err);
4419 
4420  UnresolvedUsingValueDecl *ToUsingValue;
4421  if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
4422  ToUsingLoc, ToQualifierLoc, NameInfo,
4423  ToEllipsisLoc))
4424  return ToUsingValue;
4425 
4426  ToUsingValue->setAccess(D->getAccess());
4427  ToUsingValue->setLexicalDeclContext(LexicalDC);
4428  LexicalDC->addDeclInternal(ToUsingValue);
4429 
4430  return ToUsingValue;
4431 }
4432 
4435  DeclContext *DC, *LexicalDC;
4436  DeclarationName Name;
4437  SourceLocation Loc;
4438  NamedDecl *ToD = nullptr;
4439  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4440  return std::move(Err);
4441  if (ToD)
4442  return ToD;
4443 
4444  SourceLocation ToUsingLoc, ToTypenameLoc, ToEllipsisLoc;
4445  NestedNameSpecifierLoc ToQualifierLoc;
4446  if (auto Imp = importSeq(
4447  D->getUsingLoc(), D->getTypenameLoc(), D->getQualifierLoc(),
4448  D->getEllipsisLoc()))
4449  std::tie(ToUsingLoc, ToTypenameLoc, ToQualifierLoc, ToEllipsisLoc) = *Imp;
4450  else
4451  return Imp.takeError();
4452 
4453  UnresolvedUsingTypenameDecl *ToUsing;
4454  if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4455  ToUsingLoc, ToTypenameLoc,
4456  ToQualifierLoc, Loc, Name, ToEllipsisLoc))
4457  return ToUsing;
4458 
4459  ToUsing->setAccess(D->getAccess());
4460  ToUsing->setLexicalDeclContext(LexicalDC);
4461  LexicalDC->addDeclInternal(ToUsing);
4462 
4463  return ToUsing;
4464 }
4465 
4466 
4469  if (To->getDefinition()) {
4470  // Check consistency of superclass.
4471  ObjCInterfaceDecl *FromSuper = From->getSuperClass();
4472  if (FromSuper) {
4473  if (auto FromSuperOrErr = import(FromSuper))
4474  FromSuper = *FromSuperOrErr;
4475  else
4476  return FromSuperOrErr.takeError();
4477  }
4478 
4479  ObjCInterfaceDecl *ToSuper = To->getSuperClass();
4480  if ((bool)FromSuper != (bool)ToSuper ||
4481  (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
4482  Importer.ToDiag(To->getLocation(),
4483  diag::warn_odr_objc_superclass_inconsistent)
4484  << To->getDeclName();
4485  if (ToSuper)
4486  Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
4487  << To->getSuperClass()->getDeclName();
4488  else
4489  Importer.ToDiag(To->getLocation(),
4490  diag::note_odr_objc_missing_superclass);
4491  if (From->getSuperClass())
4492  Importer.FromDiag(From->getSuperClassLoc(),
4493  diag::note_odr_objc_superclass)
4494  << From->getSuperClass()->getDeclName();
4495  else
4496  Importer.FromDiag(From->getLocation(),
4497  diag::note_odr_objc_missing_superclass);
4498  }
4499 
4500  if (shouldForceImportDeclContext(Kind))
4501  if (Error Err = ImportDeclContext(From))
4502  return Err;
4503  return Error::success();
4504  }
4505 
4506  // Start the definition.
4507  To->startDefinition();
4508 
4509  // If this class has a superclass, import it.
4510  if (From->getSuperClass()) {
4511  if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo()))
4512  To->setSuperClass(*SuperTInfoOrErr);
4513  else
4514  return SuperTInfoOrErr.takeError();
4515  }
4516 
4517  // Import protocols
4519  SmallVector<SourceLocation, 4> ProtocolLocs;
4521  From->protocol_loc_begin();
4522 
4523  for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
4524  FromProtoEnd = From->protocol_end();
4525  FromProto != FromProtoEnd;
4526  ++FromProto, ++FromProtoLoc) {
4527  if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4528  Protocols.push_back(*ToProtoOrErr);
4529  else
4530  return ToProtoOrErr.takeError();
4531 
4532  if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4533  ProtocolLocs.push_back(*ToProtoLocOrErr);
4534  else
4535  return ToProtoLocOrErr.takeError();
4536 
4537  }
4538 
4539  // FIXME: If we're merging, make sure that the protocol list is the same.
4540  To->setProtocolList(Protocols.data(), Protocols.size(),
4541  ProtocolLocs.data(), Importer.getToContext());
4542 
4543  // Import categories. When the categories themselves are imported, they'll
4544  // hook themselves into this interface.
4545  for (auto *Cat : From->known_categories()) {
4546  auto ToCatOrErr = import(Cat);
4547  if (!ToCatOrErr)
4548  return ToCatOrErr.takeError();
4549  }
4550 
4551  // If we have an @implementation, import it as well.
4552  if (From->getImplementation()) {
4553  if (Expected<ObjCImplementationDecl *> ToImplOrErr =
4554  import(From->getImplementation()))
4555  To->setImplementation(*ToImplOrErr);
4556  else
4557  return ToImplOrErr.takeError();
4558  }
4559 
4560  if (shouldForceImportDeclContext(Kind)) {
4561  // Import all of the members of this class.
4562  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4563  return Err;
4564  }
4565  return Error::success();
4566 }
4567 
4570  if (!list)
4571  return nullptr;
4572 
4574  for (auto *fromTypeParam : *list) {
4575  if (auto toTypeParamOrErr = import(fromTypeParam))
4576  toTypeParams.push_back(*toTypeParamOrErr);
4577  else
4578  return toTypeParamOrErr.takeError();
4579  }
4580 
4581  auto LAngleLocOrErr = import(list->getLAngleLoc());
4582  if (!LAngleLocOrErr)
4583  return LAngleLocOrErr.takeError();
4584 
4585  auto RAngleLocOrErr = import(list->getRAngleLoc());
4586  if (!RAngleLocOrErr)
4587  return RAngleLocOrErr.takeError();
4588 
4589  return ObjCTypeParamList::create(Importer.getToContext(),
4590  *LAngleLocOrErr,
4591  toTypeParams,
4592  *RAngleLocOrErr);
4593 }
4594 
4596  // If this class has a definition in the translation unit we're coming from,
4597  // but this particular declaration is not that definition, import the
4598  // definition and map to that.
4599  ObjCInterfaceDecl *Definition = D->getDefinition();
4600  if (Definition && Definition != D) {
4601  if (ExpectedDecl ImportedDefOrErr = import(Definition))
4602  return Importer.MapImported(D, *ImportedDefOrErr);
4603  else
4604  return ImportedDefOrErr.takeError();
4605  }
4606 
4607  // Import the major distinguishing characteristics of an @interface.
4608  DeclContext *DC, *LexicalDC;
4609  DeclarationName Name;
4610  SourceLocation Loc;
4611  NamedDecl *ToD;
4612  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4613  return std::move(Err);
4614  if (ToD)
4615  return ToD;
4616 
4617  // Look for an existing interface with the same name.
4618  ObjCInterfaceDecl *MergeWithIface = nullptr;
4619  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4620  for (auto *FoundDecl : FoundDecls) {
4622  continue;
4623 
4624  if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
4625  break;
4626  }
4627 
4628  // Create an interface declaration, if one does not already exist.
4629  ObjCInterfaceDecl *ToIface = MergeWithIface;
4630  if (!ToIface) {
4631  ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc());
4632  if (!AtBeginLocOrErr)
4633  return AtBeginLocOrErr.takeError();
4634 
4635  if (GetImportedOrCreateDecl(
4636  ToIface, D, Importer.getToContext(), DC,
4637  *AtBeginLocOrErr, Name.getAsIdentifierInfo(),
4638  /*TypeParamList=*/nullptr,
4639  /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
4640  return ToIface;
4641  ToIface->setLexicalDeclContext(LexicalDC);
4642  LexicalDC->addDeclInternal(ToIface);
4643  }
4644  Importer.MapImported(D, ToIface);
4645  // Import the type parameter list after MapImported, to avoid
4646  // loops when bringing in their DeclContext.
4647  if (auto ToPListOrErr =
4648  ImportObjCTypeParamList(D->getTypeParamListAsWritten()))
4649  ToIface->setTypeParamList(*ToPListOrErr);
4650  else
4651  return ToPListOrErr.takeError();
4652 
4654  if (Error Err = ImportDefinition(D, ToIface))
4655  return std::move(Err);
4656 
4657  return ToIface;
4658 }
4659 
4663  if (Error Err = importInto(Category, D->getCategoryDecl()))
4664  return std::move(Err);
4665 
4666  ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
4667  if (!ToImpl) {
4668  DeclContext *DC, *LexicalDC;
4669  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4670  return std::move(Err);
4671 
4672  SourceLocation ToLocation, ToAtStartLoc, ToCategoryNameLoc;
4673  if (auto Imp = importSeq(
4674  D->getLocation(), D->getAtStartLoc(), D->getCategoryNameLoc()))
4675  std::tie(ToLocation, ToAtStartLoc, ToCategoryNameLoc) = *Imp;
4676  else
4677  return Imp.takeError();
4678 
4679  if (GetImportedOrCreateDecl(
4680  ToImpl, D, Importer.getToContext(), DC,
4681  Importer.Import(D->getIdentifier()), Category->getClassInterface(),
4682  ToLocation, ToAtStartLoc, ToCategoryNameLoc))
4683  return ToImpl;
4684 
4685  ToImpl->setLexicalDeclContext(LexicalDC);
4686  LexicalDC->addDeclInternal(ToImpl);
4687  Category->setImplementation(ToImpl);
4688  }
4689 
4690  Importer.MapImported(D, ToImpl);
4691  if (Error Err = ImportDeclContext(D))
4692  return std::move(Err);
4693 
4694  return ToImpl;
4695 }
4696 
4699  // Find the corresponding interface.
4700  ObjCInterfaceDecl *Iface;
4701  if (Error Err = importInto(Iface, D->getClassInterface()))
4702  return std::move(Err);
4703 
4704  // Import the superclass, if any.
4705  ObjCInterfaceDecl *Super;
4706  if (Error Err = importInto(Super, D->getSuperClass()))
4707  return std::move(Err);
4708 
4709  ObjCImplementationDecl *Impl = Iface->getImplementation();
4710  if (!Impl) {
4711  // We haven't imported an implementation yet. Create a new @implementation
4712  // now.
4713  DeclContext *DC, *LexicalDC;
4714  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4715  return std::move(Err);
4716 
4717  SourceLocation ToLocation, ToAtStartLoc, ToSuperClassLoc;
4718  SourceLocation ToIvarLBraceLoc, ToIvarRBraceLoc;
4719  if (auto Imp = importSeq(
4720  D->getLocation(), D->getAtStartLoc(), D->getSuperClassLoc(),
4721  D->getIvarLBraceLoc(), D->getIvarRBraceLoc()))
4722  std::tie(
4723  ToLocation, ToAtStartLoc, ToSuperClassLoc,
4724  ToIvarLBraceLoc, ToIvarRBraceLoc) = *Imp;
4725  else
4726  return Imp.takeError();
4727 
4728  if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
4729  DC, Iface, Super,
4730  ToLocation,
4731  ToAtStartLoc,
4732  ToSuperClassLoc,
4733  ToIvarLBraceLoc,
4734  ToIvarRBraceLoc))
4735  return Impl;
4736 
4737  Impl->setLexicalDeclContext(LexicalDC);
4738 
4739  // Associate the implementation with the class it implements.
4740  Iface->setImplementation(Impl);
4741  Importer.MapImported(D, Iface->getImplementation());
4742  } else {
4743  Importer.MapImported(D, Iface->getImplementation());
4744 
4745  // Verify that the existing @implementation has the same superclass.
4746  if ((Super && !Impl->getSuperClass()) ||
4747  (!Super && Impl->getSuperClass()) ||
4748  (Super && Impl->getSuperClass() &&
4750  Impl->getSuperClass()))) {
4751  Importer.ToDiag(Impl->getLocation(),
4752  diag::warn_odr_objc_superclass_inconsistent)
4753  << Iface->getDeclName();
4754  // FIXME: It would be nice to have the location of the superclass
4755  // below.
4756  if (Impl->getSuperClass())
4757  Importer.ToDiag(Impl->getLocation(),
4758  diag::note_odr_objc_superclass)
4759  << Impl->getSuperClass()->getDeclName();
4760  else
4761  Importer.ToDiag(Impl->getLocation(),
4762  diag::note_odr_objc_missing_superclass);
4763  if (D->getSuperClass())
4764  Importer.FromDiag(D->getLocation(),
4765  diag::note_odr_objc_superclass)
4766  << D->getSuperClass()->getDeclName();
4767  else
4768  Importer.FromDiag(D->getLocation(),
4769  diag::note_odr_objc_missing_superclass);
4770 
4771  return make_error<ImportError>(ImportError::NameConflict);
4772  }
4773  }
4774 
4775  // Import all of the members of this @implementation.
4776  if (Error Err = ImportDeclContext(D))
4777  return std::move(Err);
4778 
4779  return Impl;
4780 }
4781 
4783  // Import the major distinguishing characteristics of an @property.
4784  DeclContext *DC, *LexicalDC;
4785  DeclarationName Name;
4786  SourceLocation Loc;
4787  NamedDecl *ToD;
4788  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4789  return std::move(Err);
4790  if (ToD)
4791  return ToD;
4792 
4793  // Check whether we have already imported this property.
4794  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4795  for (auto *FoundDecl : FoundDecls) {
4796  if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) {
4797  // Check property types.
4798  if (!Importer.IsStructurallyEquivalent(D->getType(),
4799  FoundProp->getType())) {
4800  Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent)
4801  << Name << D->getType() << FoundProp->getType();
4802  Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
4803  << FoundProp->getType();
4804 
4805  return make_error<ImportError>(ImportError::NameConflict);
4806  }
4807 
4808  // FIXME: Check property attributes, getters, setters, etc.?
4809 
4810  // Consider these properties to be equivalent.
4811  Importer.MapImported(D, FoundProp);
4812  return FoundProp;
4813  }
4814  }
4815 
4816  QualType ToType;
4817  TypeSourceInfo *ToTypeSourceInfo;
4818  SourceLocation ToAtLoc, ToLParenLoc;
4819  if (auto Imp = importSeq(
4820  D->getType(), D->getTypeSourceInfo(), D->getAtLoc(), D->getLParenLoc()))
4821  std::tie(ToType, ToTypeSourceInfo, ToAtLoc, ToLParenLoc) = *Imp;
4822  else
4823  return Imp.takeError();
4824 
4825  // Create the new property.
4826  ObjCPropertyDecl *ToProperty;
4827  if (GetImportedOrCreateDecl(
4828  ToProperty, D, Importer.getToContext(), DC, Loc,
4829  Name.getAsIdentifierInfo(), ToAtLoc,
4830  ToLParenLoc, ToType,
4831  ToTypeSourceInfo, D->getPropertyImplementation()))
4832  return ToProperty;
4833 
4834  Selector ToGetterName, ToSetterName;
4835  SourceLocation ToGetterNameLoc, ToSetterNameLoc;
4836  ObjCMethodDecl *ToGetterMethodDecl, *ToSetterMethodDecl;
4837  ObjCIvarDecl *ToPropertyIvarDecl;
4838  if (auto Imp = importSeq(
4839  D->getGetterName(), D->getSetterName(),
4842  D->getPropertyIvarDecl()))
4843  std::tie(
4844  ToGetterName, ToSetterName,
4845  ToGetterNameLoc, ToSetterNameLoc,
4846  ToGetterMethodDecl, ToSetterMethodDecl,
4847  ToPropertyIvarDecl) = *Imp;
4848  else
4849  return Imp.takeError();
4850 
4851  ToProperty->setLexicalDeclContext(LexicalDC);
4852  LexicalDC->addDeclInternal(ToProperty);
4853 
4854  ToProperty->setPropertyAttributes(D->getPropertyAttributes());
4855  ToProperty->setPropertyAttributesAsWritten(
4857  ToProperty->setGetterName(ToGetterName, ToGetterNameLoc);
4858  ToProperty->setSetterName(ToSetterName, ToSetterNameLoc);
4859  ToProperty->setGetterMethodDecl(ToGetterMethodDecl);
4860  ToProperty->setSetterMethodDecl(ToSetterMethodDecl);
4861  ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl);
4862  return ToProperty;
4863 }
4864 
4868  if (Error Err = importInto(Property, D->getPropertyDecl()))
4869  return std::move(Err);
4870 
4871  DeclContext *DC, *LexicalDC;
4872  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4873  return std::move(Err);
4874 
4875  auto *InImpl = cast<ObjCImplDecl>(LexicalDC);
4876 
4877  // Import the ivar (for an @synthesize).
4878  ObjCIvarDecl *Ivar = nullptr;
4879  if (Error Err = importInto(Ivar, D->getPropertyIvarDecl()))
4880  return std::move(Err);
4881 
4882  ObjCPropertyImplDecl *ToImpl
4883  = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
4884  Property->getQueryKind());
4885  if (!ToImpl) {
4886  SourceLocation ToBeginLoc, ToLocation, ToPropertyIvarDeclLoc;
4887  if (auto Imp = importSeq(
4889  std::tie(ToBeginLoc, ToLocation, ToPropertyIvarDeclLoc) = *Imp;
4890  else
4891  return Imp.takeError();
4892 
4893  if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC,
4894  ToBeginLoc,
4895  ToLocation, Property,
4896  D->getPropertyImplementation(), Ivar,
4897  ToPropertyIvarDeclLoc))
4898  return ToImpl;
4899 
4900  ToImpl->setLexicalDeclContext(LexicalDC);
4901  LexicalDC->addDeclInternal(ToImpl);
4902  } else {
4903  // Check that we have the same kind of property implementation (@synthesize
4904  // vs. @dynamic).
4905  if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
4906  Importer.ToDiag(ToImpl->getLocation(),
4907  diag::warn_odr_objc_property_impl_kind_inconsistent)
4908  << Property->getDeclName()
4909  << (ToImpl->getPropertyImplementation()
4911  Importer.FromDiag(D->getLocation(),
4912  diag::note_odr_objc_property_impl_kind)
4913  << D->getPropertyDecl()->getDeclName()
4915 
4916  return make_error<ImportError>(ImportError::NameConflict);
4917  }
4918 
4919  // For @synthesize, check that we have the same
4921  Ivar != ToImpl->getPropertyIvarDecl()) {
4922  Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
4923  diag::warn_odr_objc_synthesize_ivar_inconsistent)
4924  << Property->getDeclName()
4925  << ToImpl->getPropertyIvarDecl()->getDeclName()
4926  << Ivar->getDeclName();
4927  Importer.FromDiag(D->getPropertyIvarDeclLoc(),
4928  diag::note_odr_objc_synthesize_ivar_here)
4929  << D->getPropertyIvarDecl()->getDeclName();
4930 
4931  return make_error<ImportError>(ImportError::NameConflict);
4932  }
4933 
4934  // Merge the existing implementation with the new implementation.
4935  Importer.MapImported(D, ToImpl);
4936  }
4937 
4938  return ToImpl;
4939 }
4940 
4943  // For template arguments, we adopt the translation unit as our declaration
4944  // context. This context will be fixed when the actual template declaration
4945  // is created.
4946 
4947  // FIXME: Import default argument.
4948 
4949  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
4950  if (!BeginLocOrErr)
4951  return BeginLocOrErr.takeError();
4952 
4953  ExpectedSLoc LocationOrErr = import(D->getLocation());
4954  if (!LocationOrErr)
4955  return LocationOrErr.takeError();
4956 
4957  TemplateTypeParmDecl *ToD = nullptr;
4958  (void)GetImportedOrCreateDecl(
4959  ToD, D, Importer.getToContext(),
4960  Importer.getToContext().getTranslationUnitDecl(),
4961  *BeginLocOrErr, *LocationOrErr,
4962  D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()),
4964  return ToD;
4965 }
4966 
4969  DeclarationName ToDeclName;
4970  SourceLocation ToLocation, ToInnerLocStart;
4971  QualType ToType;
4972  TypeSourceInfo *ToTypeSourceInfo;
4973  if (auto Imp = importSeq(
4974  D->getDeclName(), D->getLocation(), D->getType(), D->getTypeSourceInfo(),
4975  D->getInnerLocStart()))
4976  std::tie(
4977  ToDeclName, ToLocation, ToType, ToTypeSourceInfo,
4978  ToInnerLocStart) = *Imp;
4979  else
4980  return Imp.takeError();
4981 
4982  // FIXME: Import default argument.
4983 
4984  NonTypeTemplateParmDecl *ToD = nullptr;
4985  (void)GetImportedOrCreateDecl(
4986  ToD, D, Importer.getToContext(),
4987  Importer.getToContext().getTranslationUnitDecl(),
4988  ToInnerLocStart, ToLocation, D->getDepth(),
4989  D->getPosition(), ToDeclName.getAsIdentifierInfo(), ToType,
4990  D->isParameterPack(), ToTypeSourceInfo);
4991  return ToD;
4992 }
4993 
4996  // Import the name of this declaration.
4997  auto NameOrErr = import(D->getDeclName());
4998  if (!NameOrErr)
4999  return NameOrErr.takeError();
5000 
5001  // Import the location of this declaration.
5002  ExpectedSLoc LocationOrErr = import(D->getLocation());
5003  if (!LocationOrErr)
5004  return LocationOrErr.takeError();
5005 
5006  // Import template parameters.
5007  auto TemplateParamsOrErr = import(D->getTemplateParameters());
5008  if (!TemplateParamsOrErr)
5009  return TemplateParamsOrErr.takeError();
5010 
5011  // FIXME: Import default argument.
5012 
5013  TemplateTemplateParmDecl *ToD = nullptr;
5014  (void)GetImportedOrCreateDecl(
5015  ToD, D, Importer.getToContext(),
5016  Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr,
5017  D->getDepth(), D->getPosition(), D->isParameterPack(),
5018  (*NameOrErr).getAsIdentifierInfo(),
5019  *TemplateParamsOrErr);
5020  return ToD;
5021 }
5022 
5023 // Returns the definition for a (forward) declaration of a TemplateDecl, if
5024 // it has any definition in the redecl chain.
5025 template <typename T> static auto getTemplateDefinition(T *D) -> T * {
5026  assert(D->getTemplatedDecl() && "Should be called on templates only");
5027  auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
5028  if (!ToTemplatedDef)
5029  return nullptr;
5030  auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate();
5031  return cast_or_null<T>(TemplateWithDef);
5032 }
5033 
5035  bool IsFriend = D->getFriendObjectKind() != Decl::FOK_None;
5036 
5037  // Import the major distinguishing characteristics of this class template.
5038  DeclContext *DC, *LexicalDC;
5039  DeclarationName Name;
5040  SourceLocation Loc;
5041  NamedDecl *ToD;
5042  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5043  return std::move(Err);
5044  if (ToD)
5045  return ToD;
5046 
5047  ClassTemplateDecl *FoundByLookup = nullptr;
5048 
5049  // We may already have a template of the same name; try to find and match it.
5050  if (!DC->isFunctionOrMethod()) {
5051  SmallVector<NamedDecl *, 4> ConflictingDecls;
5052  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5053  for (auto *FoundDecl : FoundDecls) {
5056  continue;
5057 
5058  Decl *Found = FoundDecl;
5059  auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found);
5060  if (FoundTemplate) {
5061 
5062  if (IsStructuralMatch(D, FoundTemplate)) {
5063  ClassTemplateDecl *TemplateWithDef =
5064  getTemplateDefinition(FoundTemplate);
5065  if (D->isThisDeclarationADefinition() && TemplateWithDef)
5066  return Importer.MapImported(D, TemplateWithDef);
5067  if (!FoundByLookup)
5068  FoundByLookup = FoundTemplate;
5069  // Search in all matches because there may be multiple decl chains,
5070  // see ASTTests test ImportExistingFriendClassTemplateDef.
5071  continue;
5072  }
5073  ConflictingDecls.push_back(FoundDecl);
5074  }
5075  }
5076 
5077  if (!ConflictingDecls.empty()) {
5078  ExpectedName NameOrErr = Importer.HandleNameConflict(
5079  Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
5080  ConflictingDecls.size());
5081  if (NameOrErr)
5082  Name = NameOrErr.get();
5083  else
5084  return NameOrErr.takeError();
5085  }
5086  }
5087 
5088  CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
5089 
5090  // Create the declaration that is being templated.
5091  CXXRecordDecl *ToTemplated;
5092  if (Error Err = importInto(ToTemplated, FromTemplated))
5093  return std::move(Err);
5094 
5095  // Create the class template declaration itself.
5096  auto TemplateParamsOrErr = import(D->getTemplateParameters());
5097  if (!TemplateParamsOrErr)
5098  return TemplateParamsOrErr.takeError();
5099 
5100  ClassTemplateDecl *D2;
5101  if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name,
5102  *TemplateParamsOrErr, ToTemplated))
5103  return D2;
5104 
5105  ToTemplated->setDescribedClassTemplate(D2);
5106 
5107  D2->setAccess(D->getAccess());
5108  D2->setLexicalDeclContext(LexicalDC);
5109 
5110  if (D->getDeclContext()->containsDeclAndLoad(D))
5111  DC->addDeclInternal(D2);
5112  if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
5113  LexicalDC->addDeclInternal(D2);
5114 
5115  if (FoundByLookup) {
5116  auto *Recent =
5117  const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5118 
5119  // It is possible that during the import of the class template definition
5120  // we start the import of a fwd friend decl of the very same class template
5121  // and we add the fwd friend decl to the lookup table. But the ToTemplated
5122  // had been created earlier and by that time the lookup could not find
5123  // anything existing, so it has no previous decl. Later, (still during the
5124  // import of the fwd friend decl) we start to import the definition again
5125  // and this time the lookup finds the previous fwd friend class template.
5126  // In this case we must set up the previous decl for the templated decl.
5127  if (!ToTemplated->getPreviousDecl()) {
5128  assert(FoundByLookup->getTemplatedDecl() &&
5129  "Found decl must have its templated decl set");
5130  CXXRecordDecl *PrevTemplated =
5131  FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5132  if (ToTemplated != PrevTemplated)
5133  ToTemplated->setPreviousDecl(PrevTemplated);
5134  }
5135 
5136  D2->setPreviousDecl(Recent);
5137  }
5138 
5139  if (LexicalDC != DC && IsFriend)
5140  DC->makeDeclVisibleInContext(D2);
5141 
5142  if (FromTemplated->isCompleteDefinition() &&
5143  !ToTemplated->isCompleteDefinition()) {
5144  // FIXME: Import definition!
5145  }
5146 
5147  return D2;
5148 }
5149 
5152  ClassTemplateDecl *ClassTemplate;
5153  if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate()))
5154  return std::move(Err);
5155 
5156  // Import the context of this declaration.
5157  DeclContext *DC, *LexicalDC;
5158  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5159  return std::move(Err);
5160 
5161  // Import template arguments.
5162  SmallVector<TemplateArgument, 2> TemplateArgs;
5163  if (Error Err = ImportTemplateArguments(
5164  D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5165  return std::move(Err);
5166 
5167  // Try to find an existing specialization with these template arguments.
5168  void *InsertPos = nullptr;
5169  ClassTemplateSpecializationDecl *PrevDecl = nullptr;
5172  if (PartialSpec)
5173  PrevDecl =
5174  ClassTemplate->findPartialSpecialization(TemplateArgs, InsertPos);
5175  else
5176  PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
5177 
5178  if (PrevDecl) {
5179  if (IsStructuralMatch(D, PrevDecl)) {
5180  if (D->isThisDeclarationADefinition() && PrevDecl->getDefinition()) {
5181  Importer.MapImported(D, PrevDecl->getDefinition());
5182  // Import those default field initializers which have been
5183  // instantiated in the "From" context, but not in the "To" context.
5184  for (auto *FromField : D->fields()) {
5185  auto ToOrErr = import(FromField);
5186  if (!ToOrErr)
5187  return ToOrErr.takeError();
5188  }
5189 
5190  // Import those methods which have been instantiated in the
5191  // "From" context, but not in the "To" context.
5192  for (CXXMethodDecl *FromM : D->methods()) {
5193  auto ToOrErr = import(FromM);
5194  if (!ToOrErr)
5195  return ToOrErr.takeError();
5196  }
5197 
5198  // TODO Import instantiated default arguments.
5199  // TODO Import instantiated exception specifications.
5200  //
5201  // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint
5202  // what else could be fused during an AST merge.
5203  return PrevDecl;
5204  }
5205  } else { // ODR violation.
5206  // FIXME HandleNameConflict
5207  return make_error<ImportError>(ImportError::NameConflict);
5208  }
5209  }
5210 
5211  // Import the location of this declaration.
5212  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5213  if (!BeginLocOrErr)
5214  return BeginLocOrErr.takeError();
5215  ExpectedSLoc IdLocOrErr = import(D->getLocation());
5216  if (!IdLocOrErr)
5217  return IdLocOrErr.takeError();
5218 
5219  // Create the specialization.
5220  ClassTemplateSpecializationDecl *D2 = nullptr;
5221  if (PartialSpec) {
5222  // Import TemplateArgumentListInfo.
5223  TemplateArgumentListInfo ToTAInfo;
5224  const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
5225  if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo))
5226  return std::move(Err);
5227 
5228  QualType CanonInjType;
5229  if (Error Err = importInto(
5230  CanonInjType, PartialSpec->getInjectedSpecializationType()))
5231  return std::move(Err);
5232  CanonInjType = CanonInjType.getCanonicalType();
5233 
5234  auto ToTPListOrErr = import(PartialSpec->getTemplateParameters());
5235  if (!ToTPListOrErr)
5236  return ToTPListOrErr.takeError();
5237 
5238  if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
5239  D2, D, Importer.getToContext(), D->getTagKind(), DC,
5240  *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr, ClassTemplate,
5241  llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()),
5242  ToTAInfo, CanonInjType,
5243  cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl)))
5244  return D2;
5245 
5246  // Update InsertPos, because preceding import calls may have invalidated
5247  // it by adding new specializations.
5248  if (!ClassTemplate->findPartialSpecialization(TemplateArgs, InsertPos))
5249  // Add this partial specialization to the class template.
5250  ClassTemplate->AddPartialSpecialization(
5251  cast<ClassTemplatePartialSpecializationDecl>(D2), InsertPos);
5252 
5253  } else { // Not a partial specialization.
5254  if (GetImportedOrCreateDecl(
5255  D2, D, Importer.getToContext(), D->getTagKind(), DC,
5256  *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs,
5257  PrevDecl))
5258  return D2;
5259 
5260  // Update InsertPos, because preceding import calls may have invalidated
5261  // it by adding new specializations.
5262  if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos))
5263  // Add this specialization to the class template.
5264  ClassTemplate->AddSpecialization(D2, InsertPos);
5265  }
5266 
5268 
5269  // Set the context of this specialization/instantiation.
5270  D2->setLexicalDeclContext(LexicalDC);
5271 
5272  // Add to the DC only if it was an explicit specialization/instantiation.
5274  LexicalDC->addDeclInternal(D2);
5275  }
5276 
5277  // Import the qualifier, if any.
5278  if (auto LocOrErr = import(D->getQualifierLoc()))
5279  D2->setQualifierInfo(*LocOrErr);
5280  else
5281  return LocOrErr.takeError();
5282 
5283  if (auto *TSI = D->getTypeAsWritten()) {
5284  if (auto TInfoOrErr = import(TSI))
5285  D2->setTypeAsWritten(*TInfoOrErr);
5286  else
5287  return TInfoOrErr.takeError();
5288 
5289  if (auto LocOrErr = import(D->getTemplateKeywordLoc()))
5290  D2->setTemplateKeywordLoc(*LocOrErr);
5291  else
5292  return LocOrErr.takeError();
5293 
5294  if (auto LocOrErr = import(D->getExternLoc()))
5295  D2->setExternLoc(*LocOrErr);
5296  else
5297  return LocOrErr.takeError();
5298  }
5299 
5300  if (D->getPointOfInstantiation().isValid()) {
5301  if (auto POIOrErr = import(D->getPointOfInstantiation()))
5302  D2->setPointOfInstantiation(*POIOrErr);
5303  else
5304  return POIOrErr.takeError();
5305  }
5306 
5308 
5309  if (D->isCompleteDefinition())
5310  if (Error Err = ImportDefinition(D, D2))
5311  return std::move(Err);
5312 
5313  return D2;
5314 }
5315 
5317  // If this variable has a definition in the translation unit we're coming
5318  // from,
5319  // but this particular declaration is not that definition, import the
5320  // definition and map to that.
5321  auto *Definition =
5322  cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
5323  if (Definition && Definition != D->getTemplatedDecl()) {
5324  if (ExpectedDecl ImportedDefOrErr = import(
5325  Definition->getDescribedVarTemplate()))
5326  return Importer.MapImported(D, *ImportedDefOrErr);
5327  else
5328  return ImportedDefOrErr.takeError();
5329  }
5330 
5331  // Import the major distinguishing characteristics of this variable template.
5332  DeclContext *DC, *LexicalDC;
5333  DeclarationName Name;
5334  SourceLocation Loc;
5335  NamedDecl *ToD;
5336  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5337  return std::move(Err);
5338  if (ToD)
5339  return ToD;
5340 
5341  // We may already have a template of the same name; try to find and match it.
5342  assert(!DC->isFunctionOrMethod() &&
5343  "Variable templates cannot be declared at function scope");
5344  SmallVector<NamedDecl *, 4> ConflictingDecls;
5345  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5346  for (auto *FoundDecl : FoundDecls) {
5348  continue;
5349 
5350  Decl *Found = FoundDecl;
5351  if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
5352  if (IsStructuralMatch(D, FoundTemplate)) {
5353  // The variable templates structurally match; call it the same template.
5354  Importer.MapImported(D->getTemplatedDecl(),
5355  FoundTemplate->getTemplatedDecl());
5356  return Importer.MapImported(D, FoundTemplate);
5357  }
5358  ConflictingDecls.push_back(FoundDecl);
5359  }
5360  }
5361 
5362  if (!ConflictingDecls.empty()) {
5363  ExpectedName NameOrErr = Importer.HandleNameConflict(
5364  Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
5365  ConflictingDecls.size());
5366  if (NameOrErr)
5367  Name = NameOrErr.get();
5368  else
5369  return NameOrErr.takeError();
5370  }
5371 
5372  VarDecl *DTemplated = D->getTemplatedDecl();
5373 
5374  // Import the type.
5375  // FIXME: Value not used?
5376  ExpectedType TypeOrErr = import(DTemplated->getType());
5377  if (!TypeOrErr)
5378  return TypeOrErr.takeError();
5379 
5380  // Create the declaration that is being templated.
5381  VarDecl *ToTemplated;
5382  if (Error Err = importInto(ToTemplated, DTemplated))
5383  return std::move(Err);
5384 
5385  // Create the variable template declaration itself.
5386  auto TemplateParamsOrErr = import(D->getTemplateParameters());
5387  if (!TemplateParamsOrErr)
5388  return TemplateParamsOrErr.takeError();
5389 
5390  VarTemplateDecl *ToVarTD;
5391  if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc,
5392  Name, *TemplateParamsOrErr, ToTemplated))
5393  return ToVarTD;
5394 
5395  ToTemplated->setDescribedVarTemplate(ToVarTD);
5396 
5397  ToVarTD->setAccess(D->getAccess());
5398  ToVarTD->setLexicalDeclContext(LexicalDC);
5399  LexicalDC->addDeclInternal(ToVarTD);
5400 
5401  if (DTemplated->isThisDeclarationADefinition() &&
5402  !ToTemplated->isThisDeclarationADefinition()) {
5403  // FIXME: Import definition!
5404  }
5405 
5406  return ToVarTD;
5407 }
5408 
5411  // If this record has a definition in the translation unit we're coming from,
5412  // but this particular declaration is not that definition, import the
5413  // definition and map to that.
5414  VarDecl *Definition = D->getDefinition();
5415  if (Definition && Definition != D) {
5416  if (ExpectedDecl ImportedDefOrErr = import(Definition))
5417  return Importer.MapImported(D, *ImportedDefOrErr);
5418  else
5419  return ImportedDefOrErr.takeError();
5420  }
5421 
5422  VarTemplateDecl *VarTemplate = nullptr;
5423  if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate()))
5424  return std::move(Err);
5425 
5426  // Import the context of this declaration.
5427  DeclContext *DC, *LexicalDC;
5428  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5429  return std::move(Err);
5430 
5431  // Import the location of this declaration.
5432  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5433  if (!BeginLocOrErr)
5434  return BeginLocOrErr.takeError();
5435 
5436  auto IdLocOrErr = import(D->getLocation());
5437  if (!IdLocOrErr)
5438  return IdLocOrErr.takeError();
5439 
5440  // Import template arguments.
5441  SmallVector<TemplateArgument, 2> TemplateArgs;
5442  if (Error Err = ImportTemplateArguments(
5443  D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5444  return std::move(Err);
5445 
5446  // Try to find an existing specialization with these template arguments.
5447  void *InsertPos = nullptr;
5449  TemplateArgs, InsertPos);
5450  if (D2) {
5451  // We already have a variable template specialization with these template
5452  // arguments.
5453 
5454  // FIXME: Check for specialization vs. instantiation errors.
5455 
5456  if (VarDecl *FoundDef = D2->getDefinition()) {
5457  if (!D->isThisDeclarationADefinition() ||
5458  IsStructuralMatch(D, FoundDef)) {
5459  // The record types structurally match, or the "from" translation
5460  // unit only had a forward declaration anyway; call it the same
5461  // variable.
5462  return Importer.MapImported(D, FoundDef);
5463  }
5464  }
5465  } else {
5466  // Import the type.
5467  QualType T;
5468  if (Error Err = importInto(T, D->getType()))
5469  return std::move(Err);
5470 
5471  auto TInfoOrErr = import(D->getTypeSourceInfo());
5472  if (!TInfoOrErr)
5473  return TInfoOrErr.takeError();
5474 
5475  TemplateArgumentListInfo ToTAInfo;
5476  if (Error Err = ImportTemplateArgumentListInfo(
5477  D->getTemplateArgsInfo(), ToTAInfo))
5478  return std::move(Err);
5479 
5480  using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
5481  // Create a new specialization.
5482  if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) {
5483  // Import TemplateArgumentListInfo
5484  TemplateArgumentListInfo ArgInfos;
5485  const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten();
5486  // NOTE: FromTAArgsAsWritten and template parameter list are non-null.
5487  if (Error Err = ImportTemplateArgumentListInfo(
5488  *FromTAArgsAsWritten, ArgInfos))
5489  return std::move(Err);
5490 
5491  auto ToTPListOrErr = import(FromPartial->getTemplateParameters());
5492  if (!ToTPListOrErr)
5493  return ToTPListOrErr.takeError();
5494 
5495  PartVarSpecDecl *ToPartial;
5496  if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC,
5497  *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr,
5498  VarTemplate, T, *TInfoOrErr,
5499  D->getStorageClass(), TemplateArgs, ArgInfos))
5500  return ToPartial;
5501 
5502  if (Expected<PartVarSpecDecl *> ToInstOrErr = import(
5503  FromPartial->getInstantiatedFromMember()))
5504  ToPartial->setInstantiatedFromMember(*ToInstOrErr);
5505  else
5506  return ToInstOrErr.takeError();
5507 
5508  if (FromPartial->isMemberSpecialization())
5509  ToPartial->setMemberSpecialization();
5510 
5511  D2 = ToPartial;
5512 
5513  } else { // Full specialization
5514  if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC,
5515  *BeginLocOrErr, *IdLocOrErr, VarTemplate,
5516  T, *TInfoOrErr,
5517  D->getStorageClass(), TemplateArgs))
5518  return D2;
5519  }
5520 
5521  if (D->getPointOfInstantiation().isValid()) {
5522  if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation()))
5523  D2->setPointOfInstantiation(*POIOrErr);
5524  else
5525  return POIOrErr.takeError();
5526  }
5527 
5529  D2->setTemplateArgsInfo(ToTAInfo);
5530 
5531  // Add this specialization to the class template.
5532  VarTemplate->AddSpecialization(D2, InsertPos);
5533 
5534  // Import the qualifier, if any.
5535  if (auto LocOrErr = import(D->getQualifierLoc()))
5536  D2->setQualifierInfo(*LocOrErr);
5537  else
5538  return LocOrErr.takeError();
5539 
5540  if (D->isConstexpr())
5541  D2->setConstexpr(true);
5542 
5543  // Add the specialization to this context.
5544  D2->setLexicalDeclContext(LexicalDC);
5545  LexicalDC->addDeclInternal(D2);
5546 
5547  D2->setAccess(D->getAccess());
5548  }
5549 
5550  if (Error Err = ImportInitializer(D, D2))
5551  return std::move(Err);
5552 
5553  return D2;
5554 }
5555 
5558  DeclContext *DC, *LexicalDC;
5559  DeclarationName Name;
5560  SourceLocation Loc;
5561  NamedDecl *ToD;
5562 
5563  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5564  return std::move(Err);
5565 
5566  if (ToD)
5567  return ToD;
5568 
5569  const FunctionTemplateDecl *FoundByLookup = nullptr;
5570 
5571  // Try to find a function in our own ("to") context with the same name, same
5572  // type, and in the same context as the function we're importing.
5573  // FIXME Split this into a separate function.
5574  if (!LexicalDC->isFunctionOrMethod()) {
5576  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5577  for (auto *FoundDecl : FoundDecls) {
5578  if (!FoundDecl->isInIdentifierNamespace(IDNS))
5579  continue;
5580 
5581  if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(FoundDecl)) {
5582  if (!hasSameVisibilityContext(FoundTemplate, D))
5583  continue;
5584  if (IsStructuralMatch(D, FoundTemplate)) {
5585  FunctionTemplateDecl *TemplateWithDef =
5586  getTemplateDefinition(FoundTemplate);
5587  if (D->isThisDeclarationADefinition() && TemplateWithDef)
5588  return Importer.MapImported(D, TemplateWithDef);
5589 
5590  FoundByLookup = FoundTemplate;
5591  break;
5592  // TODO: handle conflicting names
5593  }
5594  }
5595  }
5596  }
5597 
5598  auto ParamsOrErr = import(D->getTemplateParameters());
5599  if (!ParamsOrErr)
5600  return ParamsOrErr.takeError();
5601 
5602  FunctionDecl *TemplatedFD;
5603  if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl()))
5604  return std::move(Err);
5605 
5606  FunctionTemplateDecl *ToFunc;
5607  if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name,
5608  *ParamsOrErr, TemplatedFD))
5609  return ToFunc;
5610 
5611  TemplatedFD->setDescribedFunctionTemplate(ToFunc);
5612 
5613  ToFunc->setAccess(D->getAccess());
5614  ToFunc->setLexicalDeclContext(LexicalDC);
5615  LexicalDC->addDeclInternal(ToFunc);
5616 
5617  if (FoundByLookup) {
5618  auto *Recent =
5619  const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5620  if (!TemplatedFD->getPreviousDecl()) {
5621  assert(FoundByLookup->getTemplatedDecl() &&
5622  "Found decl must have its templated decl set");
5623  auto *PrevTemplated =
5624  FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5625  if (TemplatedFD != PrevTemplated)
5626  TemplatedFD->setPreviousDecl(PrevTemplated);
5627  }
5628  ToFunc->setPreviousDecl(Recent);
5629  }
5630 
5631  return ToFunc;
5632 }
5633 
5634 //----------------------------------------------------------------------------
5635 // Import Statements
5636 //----------------------------------------------------------------------------
5637 
5639  Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node)
5640  << S->getStmtClassName();
5641  return make_error<ImportError>(ImportError::UnsupportedConstruct);
5642 }
5643 
5644 
5646  if (Importer.returnWithErrorInTest())
5647  return make_error<ImportError>(ImportError::UnsupportedConstruct);
5649  for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5650  IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
5651  // ToII is nullptr when no symbolic name is given for output operand
5652  // see ParseStmtAsm::ParseAsmOperandsOpt
5653  Names.push_back(ToII);
5654  }
5655 
5656  for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
5657  IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
5658  // ToII is nullptr when no symbolic name is given for input operand
5659  // see ParseStmtAsm::ParseAsmOperandsOpt
5660  Names.push_back(ToII);
5661  }
5662 
5664  for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
5665  if (auto ClobberOrErr = import(S->getClobberStringLiteral(I)))
5666  Clobbers.push_back(*ClobberOrErr);
5667  else
5668  return ClobberOrErr.takeError();
5669 
5670  }
5671 
5672  SmallVector<StringLiteral *, 4> Constraints;
5673  for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5674  if (auto OutputOrErr = import(S->getOutputConstraintLiteral(I)))
5675  Constraints.push_back(*OutputOrErr);
5676  else
5677  return OutputOrErr.takeError();
5678  }
5679 
5680  for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
5681  if (auto InputOrErr = import(S->getInputConstraintLiteral(I)))
5682  Constraints.push_back(*InputOrErr);
5683  else
5684  return InputOrErr.takeError();
5685  }
5686 
5688  S->getNumLabels());
5689  if (Error Err = ImportContainerChecked(S->outputs(), Exprs))
5690  return std::move(Err);
5691 
5692  if (Error Err =
5693  ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
5694  return std::move(Err);
5695 
5696  if (Error Err = ImportArrayChecked(
5697  S->labels(), Exprs.begin() + S->getNumOutputs() + S->getNumInputs()))
5698  return std::move(Err);
5699 
5700  ExpectedSLoc AsmLocOrErr = import(S->getAsmLoc());
5701  if (!AsmLocOrErr)
5702  return AsmLocOrErr.takeError();
5703  auto AsmStrOrErr = import(S->getAsmString());
5704  if (!AsmStrOrErr)
5705  return AsmStrOrErr.takeError();
5706  ExpectedSLoc RParenLocOrErr = import(S->getRParenLoc());
5707  if (!RParenLocOrErr)
5708  return RParenLocOrErr.takeError();
5709 
5710  return new (Importer.getToContext()) GCCAsmStmt(
5711  Importer.getToContext(),
5712  *AsmLocOrErr,
5713  S->isSimple(),
5714  S->isVolatile(),
5715  S->getNumOutputs(),
5716  S->getNumInputs(),
5717  Names.data(),
5718  Constraints.data(),
5719  Exprs.data(),
5720  *AsmStrOrErr,
5721  S->getNumClobbers(),
5722  Clobbers.data(),
5723  S->getNumLabels(),
5724  *RParenLocOrErr);
5725 }
5726 
5728  auto Imp = importSeq(S->getDeclGroup(), S->getBeginLoc(), S->getEndLoc());
5729  if (!Imp)
5730  return Imp.takeError();
5731 
5732  DeclGroupRef ToDG;
5733  SourceLocation ToBeginLoc, ToEndLoc;
5734  std::tie(ToDG, ToBeginLoc, ToEndLoc) = *Imp;
5735 
5736  return new (Importer.getToContext()) DeclStmt(ToDG, ToBeginLoc, ToEndLoc);
5737 }
5738 
5740  ExpectedSLoc ToSemiLocOrErr = import(S->getSemiLoc());
5741  if (!ToSemiLocOrErr)
5742  return ToSemiLocOrErr.takeError();
5743  return new (Importer.getToContext()) NullStmt(
5744  *ToSemiLocOrErr, S->hasLeadingEmptyMacro());
5745 }
5746 
5748  SmallVector<Stmt *, 8> ToStmts(S->size());
5749 
5750  if (Error Err = ImportContainerChecked(S->body(), ToStmts))
5751  return std::move(Err);
5752 
5753  ExpectedSLoc ToLBracLocOrErr = import(S->getLBracLoc());
5754  if (!ToLBracLocOrErr)
5755  return ToLBracLocOrErr.takeError();
5756 
5757  ExpectedSLoc ToRBracLocOrErr = import(S->getRBracLoc());
5758  if (!ToRBracLocOrErr)
5759  return ToRBracLocOrErr.takeError();
5760 
5761  return CompoundStmt::Create(
5762  Importer.get