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