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