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