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