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" 15 #include "clang/AST/ASTImporterSharedState.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTDiagnostic.h" 18 #include "clang/AST/ASTStructuralEquivalence.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclAccessPair.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" 29 #include "clang/AST/DeclarationName.h" 30 #include "clang/AST/Expr.h" 31 #include "clang/AST/ExprCXX.h" 32 #include "clang/AST/ExprObjC.h" 33 #include "clang/AST/ExternalASTSource.h" 34 #include "clang/AST/LambdaCapture.h" 35 #include "clang/AST/NestedNameSpecifier.h" 36 #include "clang/AST/OperationKinds.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" 46 #include "clang/AST/UnresolvedSet.h" 47 #include "clang/Basic/Builtins.h" 48 #include "clang/Basic/ExceptionSpecificationType.h" 49 #include "clang/Basic/FileManager.h" 50 #include "clang/Basic/IdentifierTable.h" 51 #include "clang/Basic/LLVM.h" 52 #include "clang/Basic/LangOptions.h" 53 #include "clang/Basic/SourceLocation.h" 54 #include "clang/Basic/SourceManager.h" 55 #include "clang/Basic/Specifiers.h" 56 #include "llvm/ADT/APSInt.h" 57 #include "llvm/ADT/ArrayRef.h" 58 #include "llvm/ADT/DenseMap.h" 59 #include "llvm/ADT/None.h" 60 #include "llvm/ADT/Optional.h" 61 #include "llvm/ADT/ScopeExit.h" 62 #include "llvm/ADT/STLExtras.h" 63 #include "llvm/ADT/SmallVector.h" 64 #include "llvm/Support/Casting.h" 65 #include "llvm/Support/ErrorHandling.h" 66 #include "llvm/Support/MemoryBuffer.h" 67 #include <algorithm> 68 #include <cassert> 69 #include <cstddef> 70 #include <memory> 71 #include <type_traits> 72 #include <utility> 73 74 namespace clang { 75 76 using llvm::make_error; 77 using llvm::Error; 78 using llvm::Expected; 79 using ExpectedTypePtr = llvm::Expected<const Type *>; 80 using ExpectedType = llvm::Expected<QualType>; 81 using ExpectedStmt = llvm::Expected<Stmt *>; 82 using ExpectedExpr = llvm::Expected<Expr *>; 83 using ExpectedDecl = llvm::Expected<Decl *>; 84 using ExpectedSLoc = llvm::Expected<SourceLocation>; 85 using ExpectedName = llvm::Expected<DeclarationName>; 86 87 std::string ASTImportError::toString() const { 88 // FIXME: Improve error texts. 89 switch (Error) { 90 case NameConflict: 91 return "NameConflict"; 92 case UnsupportedConstruct: 93 return "UnsupportedConstruct"; 94 case Unknown: 95 return "Unknown error"; 96 } 97 llvm_unreachable("Invalid error code."); 98 return "Invalid error code."; 99 } 100 101 void ASTImportError::log(raw_ostream &OS) const { OS << toString(); } 102 103 std::error_code ASTImportError::convertToErrorCode() const { 104 llvm_unreachable("Function not implemented."); 105 } 106 107 char ASTImportError::ID; 108 109 template <class T> 110 SmallVector<Decl *, 2> 111 getCanonicalForwardRedeclChain(Redeclarable<T>* D) { 112 SmallVector<Decl *, 2> Redecls; 113 for (auto *R : D->getFirstDecl()->redecls()) { 114 if (R != D->getFirstDecl()) 115 Redecls.push_back(R); 116 } 117 Redecls.push_back(D->getFirstDecl()); 118 std::reverse(Redecls.begin(), Redecls.end()); 119 return Redecls; 120 } 121 122 SmallVector<Decl*, 2> getCanonicalForwardRedeclChain(Decl* D) { 123 if (auto *FD = dyn_cast<FunctionDecl>(D)) 124 return getCanonicalForwardRedeclChain<FunctionDecl>(FD); 125 if (auto *VD = dyn_cast<VarDecl>(D)) 126 return getCanonicalForwardRedeclChain<VarDecl>(VD); 127 if (auto *TD = dyn_cast<TagDecl>(D)) 128 return getCanonicalForwardRedeclChain<TagDecl>(TD); 129 llvm_unreachable("Bad declaration kind"); 130 } 131 132 void updateFlags(const Decl *From, Decl *To) { 133 // Check if some flags or attrs are new in 'From' and copy into 'To'. 134 // FIXME: Other flags or attrs? 135 if (From->isUsed(false) && !To->isUsed(false)) 136 To->setIsUsed(); 137 } 138 139 /// How to handle import errors that occur when import of a child declaration 140 /// of a DeclContext fails. 141 class ChildErrorHandlingStrategy { 142 /// This context is imported (in the 'from' domain). 143 /// It is nullptr if a non-DeclContext is imported. 144 const DeclContext *const FromDC; 145 /// Ignore import errors of the children. 146 /// If true, the context can be imported successfully if a child 147 /// of it failed to import. Otherwise the import errors of the child nodes 148 /// are accumulated (joined) into the import error object of the parent. 149 /// (Import of a parent can fail in other ways.) 150 bool const IgnoreChildErrors; 151 152 public: 153 ChildErrorHandlingStrategy(const DeclContext *FromDC) 154 : FromDC(FromDC), IgnoreChildErrors(!isa<TagDecl>(FromDC)) {} 155 ChildErrorHandlingStrategy(const Decl *FromD) 156 : FromDC(dyn_cast<DeclContext>(FromD)), 157 IgnoreChildErrors(!isa<TagDecl>(FromD)) {} 158 159 /// Process the import result of a child (of the current declaration). 160 /// \param ResultErr The import error that can be used as result of 161 /// importing the parent. This may be changed by the function. 162 /// \param ChildErr Result of importing a child. Can be success or error. 163 void handleChildImportResult(Error &ResultErr, Error &&ChildErr) { 164 if (ChildErr && !IgnoreChildErrors) 165 ResultErr = joinErrors(std::move(ResultErr), std::move(ChildErr)); 166 else 167 consumeError(std::move(ChildErr)); 168 } 169 170 /// Determine if import failure of a child does not cause import failure of 171 /// its parent. 172 bool ignoreChildErrorOnParent(Decl *FromChildD) const { 173 if (!IgnoreChildErrors || !FromDC) 174 return false; 175 return FromDC->containsDecl(FromChildD); 176 } 177 }; 178 179 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>, 180 public DeclVisitor<ASTNodeImporter, ExpectedDecl>, 181 public StmtVisitor<ASTNodeImporter, ExpectedStmt> { 182 ASTImporter &Importer; 183 184 // Use this instead of Importer.importInto . 185 template <typename ImportT> 186 LLVM_NODISCARD Error importInto(ImportT &To, const ImportT &From) { 187 return Importer.importInto(To, From); 188 } 189 190 // Use this to import pointers of specific type. 191 template <typename ImportT> 192 LLVM_NODISCARD Error importInto(ImportT *&To, ImportT *From) { 193 auto ToOrErr = Importer.Import(From); 194 if (ToOrErr) 195 To = cast_or_null<ImportT>(*ToOrErr); 196 return ToOrErr.takeError(); 197 } 198 199 // Call the import function of ASTImporter for a baseclass of type `T` and 200 // cast the return value to `T`. 201 template <typename T> 202 auto import(T *From) 203 -> std::conditional_t<std::is_base_of<Type, T>::value, 204 Expected<const T *>, Expected<T *>> { 205 auto ToOrErr = Importer.Import(From); 206 if (!ToOrErr) 207 return ToOrErr.takeError(); 208 return cast_or_null<T>(*ToOrErr); 209 } 210 211 template <typename T> 212 auto import(const T *From) { 213 return import(const_cast<T *>(From)); 214 } 215 216 // Call the import function of ASTImporter for type `T`. 217 template <typename T> 218 Expected<T> import(const T &From) { 219 return Importer.Import(From); 220 } 221 222 // Import an Optional<T> by importing the contained T, if any. 223 template<typename T> 224 Expected<Optional<T>> import(Optional<T> From) { 225 if (!From) 226 return Optional<T>(); 227 return import(*From); 228 } 229 230 ExplicitSpecifier importExplicitSpecifier(Error &Err, 231 ExplicitSpecifier ESpec); 232 233 // Wrapper for an overload set. 234 template <typename ToDeclT> struct CallOverloadedCreateFun { 235 template <typename... Args> decltype(auto) operator()(Args &&... args) { 236 return ToDeclT::Create(std::forward<Args>(args)...); 237 } 238 }; 239 240 // Always use these functions to create a Decl during import. There are 241 // certain tasks which must be done after the Decl was created, e.g. we 242 // must immediately register that as an imported Decl. The parameter `ToD` 243 // will be set to the newly created Decl or if had been imported before 244 // then to the already imported Decl. Returns a bool value set to true if 245 // the `FromD` had been imported before. 246 template <typename ToDeclT, typename FromDeclT, typename... Args> 247 LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD, 248 Args &&... args) { 249 // There may be several overloads of ToDeclT::Create. We must make sure 250 // to call the one which would be chosen by the arguments, thus we use a 251 // wrapper for the overload set. 252 CallOverloadedCreateFun<ToDeclT> OC; 253 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD, 254 std::forward<Args>(args)...); 255 } 256 // Use this overload if a special Type is needed to be created. E.g if we 257 // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl` 258 // then: 259 // TypedefNameDecl *ToTypedef; 260 // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...); 261 template <typename NewDeclT, typename ToDeclT, typename FromDeclT, 262 typename... Args> 263 LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD, 264 Args &&... args) { 265 CallOverloadedCreateFun<NewDeclT> OC; 266 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD, 267 std::forward<Args>(args)...); 268 } 269 // Use this version if a special create function must be 270 // used, e.g. CXXRecordDecl::CreateLambda . 271 template <typename ToDeclT, typename CreateFunT, typename FromDeclT, 272 typename... Args> 273 LLVM_NODISCARD bool 274 GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun, 275 FromDeclT *FromD, Args &&... args) { 276 if (Importer.getImportDeclErrorIfAny(FromD)) { 277 ToD = nullptr; 278 return true; // Already imported but with error. 279 } 280 ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD)); 281 if (ToD) 282 return true; // Already imported. 283 ToD = CreateFun(std::forward<Args>(args)...); 284 // Keep track of imported Decls. 285 Importer.RegisterImportedDecl(FromD, ToD); 286 Importer.SharedState->markAsNewDecl(ToD); 287 InitializeImportedDecl(FromD, ToD); 288 return false; // A new Decl is created. 289 } 290 291 void InitializeImportedDecl(Decl *FromD, Decl *ToD) { 292 ToD->IdentifierNamespace = FromD->IdentifierNamespace; 293 if (FromD->isUsed()) 294 ToD->setIsUsed(); 295 if (FromD->isImplicit()) 296 ToD->setImplicit(); 297 } 298 299 // Check if we have found an existing definition. Returns with that 300 // definition if yes, otherwise returns null. 301 Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) { 302 const FunctionDecl *Definition = nullptr; 303 if (D->doesThisDeclarationHaveABody() && 304 FoundFunction->hasBody(Definition)) 305 return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition)); 306 return nullptr; 307 } 308 309 void addDeclToContexts(Decl *FromD, Decl *ToD) { 310 if (Importer.isMinimalImport()) { 311 // In minimal import case the decl must be added even if it is not 312 // contained in original context, for LLDB compatibility. 313 // FIXME: Check if a better solution is possible. 314 if (!FromD->getDescribedTemplate() && 315 FromD->getFriendObjectKind() == Decl::FOK_None) 316 ToD->getLexicalDeclContext()->addDeclInternal(ToD); 317 return; 318 } 319 320 DeclContext *FromDC = FromD->getDeclContext(); 321 DeclContext *FromLexicalDC = FromD->getLexicalDeclContext(); 322 DeclContext *ToDC = ToD->getDeclContext(); 323 DeclContext *ToLexicalDC = ToD->getLexicalDeclContext(); 324 325 bool Visible = false; 326 if (FromDC->containsDeclAndLoad(FromD)) { 327 ToDC->addDeclInternal(ToD); 328 Visible = true; 329 } 330 if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(FromD)) { 331 ToLexicalDC->addDeclInternal(ToD); 332 Visible = true; 333 } 334 335 // If the Decl was added to any context, it was made already visible. 336 // Otherwise it is still possible that it should be visible. 337 if (!Visible) { 338 if (auto *FromNamed = dyn_cast<NamedDecl>(FromD)) { 339 auto *ToNamed = cast<NamedDecl>(ToD); 340 DeclContextLookupResult FromLookup = 341 FromDC->lookup(FromNamed->getDeclName()); 342 if (llvm::is_contained(FromLookup, FromNamed)) 343 ToDC->makeDeclVisibleInContext(ToNamed); 344 } 345 } 346 } 347 348 void updateLookupTableForTemplateParameters(TemplateParameterList &Params, 349 DeclContext *OldDC) { 350 ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable(); 351 if (!LT) 352 return; 353 354 for (NamedDecl *TP : Params) 355 LT->update(TP, OldDC); 356 } 357 358 void updateLookupTableForTemplateParameters(TemplateParameterList &Params) { 359 updateLookupTableForTemplateParameters( 360 Params, Importer.getToContext().getTranslationUnitDecl()); 361 } 362 363 public: 364 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {} 365 366 using TypeVisitor<ASTNodeImporter, ExpectedType>::Visit; 367 using DeclVisitor<ASTNodeImporter, ExpectedDecl>::Visit; 368 using StmtVisitor<ASTNodeImporter, ExpectedStmt>::Visit; 369 370 // Importing types 371 ExpectedType VisitType(const Type *T); 372 ExpectedType VisitAtomicType(const AtomicType *T); 373 ExpectedType VisitBuiltinType(const BuiltinType *T); 374 ExpectedType VisitDecayedType(const DecayedType *T); 375 ExpectedType VisitComplexType(const ComplexType *T); 376 ExpectedType VisitPointerType(const PointerType *T); 377 ExpectedType VisitBlockPointerType(const BlockPointerType *T); 378 ExpectedType VisitLValueReferenceType(const LValueReferenceType *T); 379 ExpectedType VisitRValueReferenceType(const RValueReferenceType *T); 380 ExpectedType VisitMemberPointerType(const MemberPointerType *T); 381 ExpectedType VisitConstantArrayType(const ConstantArrayType *T); 382 ExpectedType VisitIncompleteArrayType(const IncompleteArrayType *T); 383 ExpectedType VisitVariableArrayType(const VariableArrayType *T); 384 ExpectedType VisitDependentSizedArrayType(const DependentSizedArrayType *T); 385 // FIXME: DependentSizedExtVectorType 386 ExpectedType VisitVectorType(const VectorType *T); 387 ExpectedType VisitExtVectorType(const ExtVectorType *T); 388 ExpectedType VisitFunctionNoProtoType(const FunctionNoProtoType *T); 389 ExpectedType VisitFunctionProtoType(const FunctionProtoType *T); 390 ExpectedType VisitUnresolvedUsingType(const UnresolvedUsingType *T); 391 ExpectedType VisitParenType(const ParenType *T); 392 ExpectedType VisitTypedefType(const TypedefType *T); 393 ExpectedType VisitTypeOfExprType(const TypeOfExprType *T); 394 // FIXME: DependentTypeOfExprType 395 ExpectedType VisitTypeOfType(const TypeOfType *T); 396 ExpectedType VisitUsingType(const UsingType *T); 397 ExpectedType VisitDecltypeType(const DecltypeType *T); 398 ExpectedType VisitUnaryTransformType(const UnaryTransformType *T); 399 ExpectedType VisitAutoType(const AutoType *T); 400 ExpectedType VisitDeducedTemplateSpecializationType( 401 const DeducedTemplateSpecializationType *T); 402 ExpectedType VisitInjectedClassNameType(const InjectedClassNameType *T); 403 // FIXME: DependentDecltypeType 404 ExpectedType VisitRecordType(const RecordType *T); 405 ExpectedType VisitEnumType(const EnumType *T); 406 ExpectedType VisitAttributedType(const AttributedType *T); 407 ExpectedType VisitTemplateTypeParmType(const TemplateTypeParmType *T); 408 ExpectedType VisitSubstTemplateTypeParmType( 409 const SubstTemplateTypeParmType *T); 410 ExpectedType 411 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T); 412 ExpectedType VisitTemplateSpecializationType( 413 const TemplateSpecializationType *T); 414 ExpectedType VisitElaboratedType(const ElaboratedType *T); 415 ExpectedType VisitDependentNameType(const DependentNameType *T); 416 ExpectedType VisitPackExpansionType(const PackExpansionType *T); 417 ExpectedType VisitDependentTemplateSpecializationType( 418 const DependentTemplateSpecializationType *T); 419 ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T); 420 ExpectedType VisitObjCObjectType(const ObjCObjectType *T); 421 ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T); 422 423 // Importing declarations 424 Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD, 425 SourceLocation &Loc); 426 Error ImportDeclParts( 427 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC, 428 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc); 429 Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr); 430 Error ImportDeclarationNameLoc( 431 const DeclarationNameInfo &From, DeclarationNameInfo &To); 432 Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false); 433 Error ImportDeclContext( 434 Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC); 435 Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To); 436 437 Expected<CXXCastPath> ImportCastPath(CastExpr *E); 438 Expected<APValue> ImportAPValue(const APValue &FromValue); 439 440 using Designator = DesignatedInitExpr::Designator; 441 442 /// What we should import from the definition. 443 enum ImportDefinitionKind { 444 /// Import the default subset of the definition, which might be 445 /// nothing (if minimal import is set) or might be everything (if minimal 446 /// import is not set). 447 IDK_Default, 448 /// Import everything. 449 IDK_Everything, 450 /// Import only the bare bones needed to establish a valid 451 /// DeclContext. 452 IDK_Basic 453 }; 454 455 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) { 456 return IDK == IDK_Everything || 457 (IDK == IDK_Default && !Importer.isMinimalImport()); 458 } 459 460 Error ImportInitializer(VarDecl *From, VarDecl *To); 461 Error ImportDefinition( 462 RecordDecl *From, RecordDecl *To, 463 ImportDefinitionKind Kind = IDK_Default); 464 Error ImportDefinition( 465 EnumDecl *From, EnumDecl *To, 466 ImportDefinitionKind Kind = IDK_Default); 467 Error ImportDefinition( 468 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, 469 ImportDefinitionKind Kind = IDK_Default); 470 Error ImportDefinition( 471 ObjCProtocolDecl *From, ObjCProtocolDecl *To, 472 ImportDefinitionKind Kind = IDK_Default); 473 Error ImportTemplateArguments( 474 const TemplateArgument *FromArgs, unsigned NumFromArgs, 475 SmallVectorImpl<TemplateArgument> &ToArgs); 476 Expected<TemplateArgument> 477 ImportTemplateArgument(const TemplateArgument &From); 478 479 template <typename InContainerTy> 480 Error ImportTemplateArgumentListInfo( 481 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo); 482 483 template<typename InContainerTy> 484 Error ImportTemplateArgumentListInfo( 485 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc, 486 const InContainerTy &Container, TemplateArgumentListInfo &Result); 487 488 using TemplateArgsTy = SmallVector<TemplateArgument, 8>; 489 using FunctionTemplateAndArgsTy = 490 std::tuple<FunctionTemplateDecl *, TemplateArgsTy>; 491 Expected<FunctionTemplateAndArgsTy> 492 ImportFunctionTemplateWithTemplateArgsFromSpecialization( 493 FunctionDecl *FromFD); 494 Error ImportTemplateParameterLists(const DeclaratorDecl *FromD, 495 DeclaratorDecl *ToD); 496 497 Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD); 498 499 Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD); 500 501 Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam, 502 ParmVarDecl *ToParam); 503 504 Expected<InheritedConstructor> 505 ImportInheritedConstructor(const InheritedConstructor &From); 506 507 template <typename T> 508 bool hasSameVisibilityContextAndLinkage(T *Found, T *From); 509 510 bool IsStructuralMatch(Decl *From, Decl *To, bool Complain = true); 511 ExpectedDecl VisitDecl(Decl *D); 512 ExpectedDecl VisitImportDecl(ImportDecl *D); 513 ExpectedDecl VisitEmptyDecl(EmptyDecl *D); 514 ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D); 515 ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D); 516 ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D); 517 ExpectedDecl VisitBindingDecl(BindingDecl *D); 518 ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D); 519 ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D); 520 ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias); 521 ExpectedDecl VisitTypedefDecl(TypedefDecl *D); 522 ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D); 523 ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D); 524 ExpectedDecl VisitLabelDecl(LabelDecl *D); 525 ExpectedDecl VisitEnumDecl(EnumDecl *D); 526 ExpectedDecl VisitRecordDecl(RecordDecl *D); 527 ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D); 528 ExpectedDecl VisitFunctionDecl(FunctionDecl *D); 529 ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D); 530 ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D); 531 ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D); 532 ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D); 533 ExpectedDecl VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D); 534 ExpectedDecl VisitFieldDecl(FieldDecl *D); 535 ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D); 536 ExpectedDecl VisitFriendDecl(FriendDecl *D); 537 ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D); 538 ExpectedDecl VisitVarDecl(VarDecl *D); 539 ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D); 540 ExpectedDecl VisitParmVarDecl(ParmVarDecl *D); 541 ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D); 542 ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D); 543 ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D); 544 ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D); 545 ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D); 546 ExpectedDecl VisitUsingDecl(UsingDecl *D); 547 ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D); 548 ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D); 549 ExpectedDecl VisitUsingPackDecl(UsingPackDecl *D); 550 ExpectedDecl ImportUsingShadowDecls(BaseUsingDecl *D, BaseUsingDecl *ToSI); 551 ExpectedDecl VisitUsingEnumDecl(UsingEnumDecl *D); 552 ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); 553 ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); 554 ExpectedDecl VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D); 555 ExpectedDecl 556 VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D); 557 558 Expected<ObjCTypeParamList *> 559 ImportObjCTypeParamList(ObjCTypeParamList *list); 560 561 ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); 562 ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); 563 ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D); 564 ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D); 565 ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D); 566 ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 567 ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); 568 ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); 569 ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D); 570 ExpectedDecl VisitClassTemplateSpecializationDecl( 571 ClassTemplateSpecializationDecl *D); 572 ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D); 573 ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D); 574 ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 575 576 // Importing statements 577 ExpectedStmt VisitStmt(Stmt *S); 578 ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S); 579 ExpectedStmt VisitDeclStmt(DeclStmt *S); 580 ExpectedStmt VisitNullStmt(NullStmt *S); 581 ExpectedStmt VisitCompoundStmt(CompoundStmt *S); 582 ExpectedStmt VisitCaseStmt(CaseStmt *S); 583 ExpectedStmt VisitDefaultStmt(DefaultStmt *S); 584 ExpectedStmt VisitLabelStmt(LabelStmt *S); 585 ExpectedStmt VisitAttributedStmt(AttributedStmt *S); 586 ExpectedStmt VisitIfStmt(IfStmt *S); 587 ExpectedStmt VisitSwitchStmt(SwitchStmt *S); 588 ExpectedStmt VisitWhileStmt(WhileStmt *S); 589 ExpectedStmt VisitDoStmt(DoStmt *S); 590 ExpectedStmt VisitForStmt(ForStmt *S); 591 ExpectedStmt VisitGotoStmt(GotoStmt *S); 592 ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S); 593 ExpectedStmt VisitContinueStmt(ContinueStmt *S); 594 ExpectedStmt VisitBreakStmt(BreakStmt *S); 595 ExpectedStmt VisitReturnStmt(ReturnStmt *S); 596 // FIXME: MSAsmStmt 597 // FIXME: SEHExceptStmt 598 // FIXME: SEHFinallyStmt 599 // FIXME: SEHTryStmt 600 // FIXME: SEHLeaveStmt 601 // FIXME: CapturedStmt 602 ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S); 603 ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S); 604 ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S); 605 // FIXME: MSDependentExistsStmt 606 ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); 607 ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S); 608 ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S); 609 ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S); 610 ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S); 611 ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S); 612 ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); 613 614 // Importing expressions 615 ExpectedStmt VisitExpr(Expr *E); 616 ExpectedStmt VisitSourceLocExpr(SourceLocExpr *E); 617 ExpectedStmt VisitVAArgExpr(VAArgExpr *E); 618 ExpectedStmt VisitChooseExpr(ChooseExpr *E); 619 ExpectedStmt VisitShuffleVectorExpr(ShuffleVectorExpr *E); 620 ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E); 621 ExpectedStmt VisitGenericSelectionExpr(GenericSelectionExpr *E); 622 ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E); 623 ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E); 624 ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); 625 ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E); 626 ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E); 627 ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E); 628 ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E); 629 ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E); 630 ExpectedStmt VisitFixedPointLiteral(FixedPointLiteral *E); 631 ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E); 632 ExpectedStmt VisitStringLiteral(StringLiteral *E); 633 ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E); 634 ExpectedStmt VisitAtomicExpr(AtomicExpr *E); 635 ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E); 636 ExpectedStmt VisitConstantExpr(ConstantExpr *E); 637 ExpectedStmt VisitParenExpr(ParenExpr *E); 638 ExpectedStmt VisitParenListExpr(ParenListExpr *E); 639 ExpectedStmt VisitStmtExpr(StmtExpr *E); 640 ExpectedStmt VisitUnaryOperator(UnaryOperator *E); 641 ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E); 642 ExpectedStmt VisitBinaryOperator(BinaryOperator *E); 643 ExpectedStmt VisitConditionalOperator(ConditionalOperator *E); 644 ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E); 645 ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E); 646 ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E); 647 ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E); 648 ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E); 649 ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E); 650 ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E); 651 ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E); 652 ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE); 653 ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E); 654 ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E); 655 ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E); 656 ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 657 ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); 658 ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E); 659 ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E); 660 ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E); 661 ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E); 662 ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E); 663 ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E); 664 ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E); 665 ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E); 666 ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E); 667 ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E); 668 ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E); 669 ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E); 670 ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E); 671 ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E); 672 ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E); 673 ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E); 674 ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E); 675 ExpectedStmt VisitMemberExpr(MemberExpr *E); 676 ExpectedStmt VisitCallExpr(CallExpr *E); 677 ExpectedStmt VisitLambdaExpr(LambdaExpr *LE); 678 ExpectedStmt VisitInitListExpr(InitListExpr *E); 679 ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E); 680 ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E); 681 ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E); 682 ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E); 683 ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E); 684 ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E); 685 ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E); 686 ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E); 687 ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E); 688 ExpectedStmt VisitCXXFoldExpr(CXXFoldExpr *E); 689 690 // Helper for chaining together multiple imports. If an error is detected, 691 // subsequent imports will return default constructed nodes, so that failure 692 // can be detected with a single conditional branch after a sequence of 693 // imports. 694 template <typename T> T importChecked(Error &Err, const T &From) { 695 // Don't attempt to import nodes if we hit an error earlier. 696 if (Err) 697 return T{}; 698 Expected<T> MaybeVal = import(From); 699 if (!MaybeVal) { 700 Err = MaybeVal.takeError(); 701 return T{}; 702 } 703 return *MaybeVal; 704 } 705 706 template<typename IIter, typename OIter> 707 Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) { 708 using ItemT = std::remove_reference_t<decltype(*Obegin)>; 709 for (; Ibegin != Iend; ++Ibegin, ++Obegin) { 710 Expected<ItemT> ToOrErr = import(*Ibegin); 711 if (!ToOrErr) 712 return ToOrErr.takeError(); 713 *Obegin = *ToOrErr; 714 } 715 return Error::success(); 716 } 717 718 // Import every item from a container structure into an output container. 719 // If error occurs, stops at first error and returns the error. 720 // The output container should have space for all needed elements (it is not 721 // expanded, new items are put into from the beginning). 722 template<typename InContainerTy, typename OutContainerTy> 723 Error ImportContainerChecked( 724 const InContainerTy &InContainer, OutContainerTy &OutContainer) { 725 return ImportArrayChecked( 726 InContainer.begin(), InContainer.end(), OutContainer.begin()); 727 } 728 729 template<typename InContainerTy, typename OIter> 730 Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) { 731 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin); 732 } 733 734 Error ImportOverriddenMethods(CXXMethodDecl *ToMethod, 735 CXXMethodDecl *FromMethod); 736 737 Expected<FunctionDecl *> FindFunctionTemplateSpecialization( 738 FunctionDecl *FromFD); 739 740 // Returns true if the given function has a placeholder return type and 741 // that type is declared inside the body of the function. 742 // E.g. auto f() { struct X{}; return X(); } 743 bool hasAutoReturnTypeDeclaredInside(FunctionDecl *D); 744 }; 745 746 template <typename InContainerTy> 747 Error ASTNodeImporter::ImportTemplateArgumentListInfo( 748 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc, 749 const InContainerTy &Container, TemplateArgumentListInfo &Result) { 750 auto ToLAngleLocOrErr = import(FromLAngleLoc); 751 if (!ToLAngleLocOrErr) 752 return ToLAngleLocOrErr.takeError(); 753 auto ToRAngleLocOrErr = import(FromRAngleLoc); 754 if (!ToRAngleLocOrErr) 755 return ToRAngleLocOrErr.takeError(); 756 757 TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr); 758 if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo)) 759 return Err; 760 Result = ToTAInfo; 761 return Error::success(); 762 } 763 764 template <> 765 Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>( 766 const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) { 767 return ImportTemplateArgumentListInfo( 768 From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result); 769 } 770 771 template <> 772 Error ASTNodeImporter::ImportTemplateArgumentListInfo< 773 ASTTemplateArgumentListInfo>( 774 const ASTTemplateArgumentListInfo &From, 775 TemplateArgumentListInfo &Result) { 776 return ImportTemplateArgumentListInfo( 777 From.LAngleLoc, From.RAngleLoc, From.arguments(), Result); 778 } 779 780 Expected<ASTNodeImporter::FunctionTemplateAndArgsTy> 781 ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization( 782 FunctionDecl *FromFD) { 783 assert(FromFD->getTemplatedKind() == 784 FunctionDecl::TK_FunctionTemplateSpecialization); 785 786 FunctionTemplateAndArgsTy Result; 787 788 auto *FTSInfo = FromFD->getTemplateSpecializationInfo(); 789 if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate())) 790 return std::move(Err); 791 792 // Import template arguments. 793 auto TemplArgs = FTSInfo->TemplateArguments->asArray(); 794 if (Error Err = ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(), 795 std::get<1>(Result))) 796 return std::move(Err); 797 798 return Result; 799 } 800 801 template <> 802 Expected<TemplateParameterList *> 803 ASTNodeImporter::import(TemplateParameterList *From) { 804 SmallVector<NamedDecl *, 4> To(From->size()); 805 if (Error Err = ImportContainerChecked(*From, To)) 806 return std::move(Err); 807 808 ExpectedExpr ToRequiresClause = import(From->getRequiresClause()); 809 if (!ToRequiresClause) 810 return ToRequiresClause.takeError(); 811 812 auto ToTemplateLocOrErr = import(From->getTemplateLoc()); 813 if (!ToTemplateLocOrErr) 814 return ToTemplateLocOrErr.takeError(); 815 auto ToLAngleLocOrErr = import(From->getLAngleLoc()); 816 if (!ToLAngleLocOrErr) 817 return ToLAngleLocOrErr.takeError(); 818 auto ToRAngleLocOrErr = import(From->getRAngleLoc()); 819 if (!ToRAngleLocOrErr) 820 return ToRAngleLocOrErr.takeError(); 821 822 return TemplateParameterList::Create( 823 Importer.getToContext(), 824 *ToTemplateLocOrErr, 825 *ToLAngleLocOrErr, 826 To, 827 *ToRAngleLocOrErr, 828 *ToRequiresClause); 829 } 830 831 template <> 832 Expected<TemplateArgument> 833 ASTNodeImporter::import(const TemplateArgument &From) { 834 switch (From.getKind()) { 835 case TemplateArgument::Null: 836 return TemplateArgument(); 837 838 case TemplateArgument::Type: { 839 ExpectedType ToTypeOrErr = import(From.getAsType()); 840 if (!ToTypeOrErr) 841 return ToTypeOrErr.takeError(); 842 return TemplateArgument(*ToTypeOrErr); 843 } 844 845 case TemplateArgument::Integral: { 846 ExpectedType ToTypeOrErr = import(From.getIntegralType()); 847 if (!ToTypeOrErr) 848 return ToTypeOrErr.takeError(); 849 return TemplateArgument(From, *ToTypeOrErr); 850 } 851 852 case TemplateArgument::Declaration: { 853 Expected<ValueDecl *> ToOrErr = import(From.getAsDecl()); 854 if (!ToOrErr) 855 return ToOrErr.takeError(); 856 ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl()); 857 if (!ToTypeOrErr) 858 return ToTypeOrErr.takeError(); 859 return TemplateArgument(*ToOrErr, *ToTypeOrErr); 860 } 861 862 case TemplateArgument::NullPtr: { 863 ExpectedType ToTypeOrErr = import(From.getNullPtrType()); 864 if (!ToTypeOrErr) 865 return ToTypeOrErr.takeError(); 866 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/true); 867 } 868 869 case TemplateArgument::Template: { 870 Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate()); 871 if (!ToTemplateOrErr) 872 return ToTemplateOrErr.takeError(); 873 874 return TemplateArgument(*ToTemplateOrErr); 875 } 876 877 case TemplateArgument::TemplateExpansion: { 878 Expected<TemplateName> ToTemplateOrErr = 879 import(From.getAsTemplateOrTemplatePattern()); 880 if (!ToTemplateOrErr) 881 return ToTemplateOrErr.takeError(); 882 883 return TemplateArgument( 884 *ToTemplateOrErr, From.getNumTemplateExpansions()); 885 } 886 887 case TemplateArgument::Expression: 888 if (ExpectedExpr ToExpr = import(From.getAsExpr())) 889 return TemplateArgument(*ToExpr); 890 else 891 return ToExpr.takeError(); 892 893 case TemplateArgument::Pack: { 894 SmallVector<TemplateArgument, 2> ToPack; 895 ToPack.reserve(From.pack_size()); 896 if (Error Err = ImportTemplateArguments( 897 From.pack_begin(), From.pack_size(), ToPack)) 898 return std::move(Err); 899 900 return TemplateArgument( 901 llvm::makeArrayRef(ToPack).copy(Importer.getToContext())); 902 } 903 } 904 905 llvm_unreachable("Invalid template argument kind"); 906 } 907 908 template <> 909 Expected<TemplateArgumentLoc> 910 ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) { 911 Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument()); 912 if (!ArgOrErr) 913 return ArgOrErr.takeError(); 914 TemplateArgument Arg = *ArgOrErr; 915 916 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo(); 917 918 TemplateArgumentLocInfo ToInfo; 919 if (Arg.getKind() == TemplateArgument::Expression) { 920 ExpectedExpr E = import(FromInfo.getAsExpr()); 921 if (!E) 922 return E.takeError(); 923 ToInfo = TemplateArgumentLocInfo(*E); 924 } else if (Arg.getKind() == TemplateArgument::Type) { 925 if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo())) 926 ToInfo = TemplateArgumentLocInfo(*TSIOrErr); 927 else 928 return TSIOrErr.takeError(); 929 } else { 930 auto ToTemplateQualifierLocOrErr = 931 import(FromInfo.getTemplateQualifierLoc()); 932 if (!ToTemplateQualifierLocOrErr) 933 return ToTemplateQualifierLocOrErr.takeError(); 934 auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc()); 935 if (!ToTemplateNameLocOrErr) 936 return ToTemplateNameLocOrErr.takeError(); 937 auto ToTemplateEllipsisLocOrErr = 938 import(FromInfo.getTemplateEllipsisLoc()); 939 if (!ToTemplateEllipsisLocOrErr) 940 return ToTemplateEllipsisLocOrErr.takeError(); 941 ToInfo = TemplateArgumentLocInfo( 942 Importer.getToContext(), *ToTemplateQualifierLocOrErr, 943 *ToTemplateNameLocOrErr, *ToTemplateEllipsisLocOrErr); 944 } 945 946 return TemplateArgumentLoc(Arg, ToInfo); 947 } 948 949 template <> 950 Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) { 951 if (DG.isNull()) 952 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0); 953 size_t NumDecls = DG.end() - DG.begin(); 954 SmallVector<Decl *, 1> ToDecls; 955 ToDecls.reserve(NumDecls); 956 for (Decl *FromD : DG) { 957 if (auto ToDOrErr = import(FromD)) 958 ToDecls.push_back(*ToDOrErr); 959 else 960 return ToDOrErr.takeError(); 961 } 962 return DeclGroupRef::Create(Importer.getToContext(), 963 ToDecls.begin(), 964 NumDecls); 965 } 966 967 template <> 968 Expected<ASTNodeImporter::Designator> 969 ASTNodeImporter::import(const Designator &D) { 970 if (D.isFieldDesignator()) { 971 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName()); 972 973 ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc()); 974 if (!ToDotLocOrErr) 975 return ToDotLocOrErr.takeError(); 976 977 ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc()); 978 if (!ToFieldLocOrErr) 979 return ToFieldLocOrErr.takeError(); 980 981 return Designator(ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr); 982 } 983 984 ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc()); 985 if (!ToLBracketLocOrErr) 986 return ToLBracketLocOrErr.takeError(); 987 988 ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc()); 989 if (!ToRBracketLocOrErr) 990 return ToRBracketLocOrErr.takeError(); 991 992 if (D.isArrayDesignator()) 993 return Designator(D.getFirstExprIndex(), 994 *ToLBracketLocOrErr, *ToRBracketLocOrErr); 995 996 ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc()); 997 if (!ToEllipsisLocOrErr) 998 return ToEllipsisLocOrErr.takeError(); 999 1000 assert(D.isArrayRangeDesignator()); 1001 return Designator( 1002 D.getFirstExprIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr, 1003 *ToRBracketLocOrErr); 1004 } 1005 1006 template <> 1007 Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) { 1008 VarDecl *Var = nullptr; 1009 if (From.capturesVariable()) { 1010 if (auto VarOrErr = import(From.getCapturedVar())) 1011 Var = *VarOrErr; 1012 else 1013 return VarOrErr.takeError(); 1014 } 1015 1016 auto LocationOrErr = import(From.getLocation()); 1017 if (!LocationOrErr) 1018 return LocationOrErr.takeError(); 1019 1020 SourceLocation EllipsisLoc; 1021 if (From.isPackExpansion()) 1022 if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc())) 1023 return std::move(Err); 1024 1025 return LambdaCapture( 1026 *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var, 1027 EllipsisLoc); 1028 } 1029 1030 template <typename T> 1031 bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(T *Found, T *From) { 1032 if (Found->getLinkageInternal() != From->getLinkageInternal()) 1033 return false; 1034 1035 if (From->hasExternalFormalLinkage()) 1036 return Found->hasExternalFormalLinkage(); 1037 if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl()) 1038 return false; 1039 if (From->isInAnonymousNamespace()) 1040 return Found->isInAnonymousNamespace(); 1041 else 1042 return !Found->isInAnonymousNamespace() && 1043 !Found->hasExternalFormalLinkage(); 1044 } 1045 1046 template <> 1047 bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(TypedefNameDecl *Found, 1048 TypedefNameDecl *From) { 1049 if (Found->getLinkageInternal() != From->getLinkageInternal()) 1050 return false; 1051 1052 if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace()) 1053 return Importer.GetFromTU(Found) == From->getTranslationUnitDecl(); 1054 return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace(); 1055 } 1056 1057 } // namespace clang 1058 1059 //---------------------------------------------------------------------------- 1060 // Import Types 1061 //---------------------------------------------------------------------------- 1062 1063 using namespace clang; 1064 1065 ExpectedType ASTNodeImporter::VisitType(const Type *T) { 1066 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node) 1067 << T->getTypeClassName(); 1068 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 1069 } 1070 1071 ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){ 1072 ExpectedType UnderlyingTypeOrErr = import(T->getValueType()); 1073 if (!UnderlyingTypeOrErr) 1074 return UnderlyingTypeOrErr.takeError(); 1075 1076 return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr); 1077 } 1078 1079 ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) { 1080 switch (T->getKind()) { 1081 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1082 case BuiltinType::Id: \ 1083 return Importer.getToContext().SingletonId; 1084 #include "clang/Basic/OpenCLImageTypes.def" 1085 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1086 case BuiltinType::Id: \ 1087 return Importer.getToContext().Id##Ty; 1088 #include "clang/Basic/OpenCLExtensionTypes.def" 1089 #define SVE_TYPE(Name, Id, SingletonId) \ 1090 case BuiltinType::Id: \ 1091 return Importer.getToContext().SingletonId; 1092 #include "clang/Basic/AArch64SVEACLETypes.def" 1093 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 1094 case BuiltinType::Id: \ 1095 return Importer.getToContext().Id##Ty; 1096 #include "clang/Basic/PPCTypes.def" 1097 #define RVV_TYPE(Name, Id, SingletonId) \ 1098 case BuiltinType::Id: \ 1099 return Importer.getToContext().SingletonId; 1100 #include "clang/Basic/RISCVVTypes.def" 1101 #define SHARED_SINGLETON_TYPE(Expansion) 1102 #define BUILTIN_TYPE(Id, SingletonId) \ 1103 case BuiltinType::Id: return Importer.getToContext().SingletonId; 1104 #include "clang/AST/BuiltinTypes.def" 1105 1106 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to" 1107 // context supports C++. 1108 1109 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to" 1110 // context supports ObjC. 1111 1112 case BuiltinType::Char_U: 1113 // The context we're importing from has an unsigned 'char'. If we're 1114 // importing into a context with a signed 'char', translate to 1115 // 'unsigned char' instead. 1116 if (Importer.getToContext().getLangOpts().CharIsSigned) 1117 return Importer.getToContext().UnsignedCharTy; 1118 1119 return Importer.getToContext().CharTy; 1120 1121 case BuiltinType::Char_S: 1122 // The context we're importing from has an unsigned 'char'. If we're 1123 // importing into a context with a signed 'char', translate to 1124 // 'unsigned char' instead. 1125 if (!Importer.getToContext().getLangOpts().CharIsSigned) 1126 return Importer.getToContext().SignedCharTy; 1127 1128 return Importer.getToContext().CharTy; 1129 1130 case BuiltinType::WChar_S: 1131 case BuiltinType::WChar_U: 1132 // FIXME: If not in C++, shall we translate to the C equivalent of 1133 // wchar_t? 1134 return Importer.getToContext().WCharTy; 1135 } 1136 1137 llvm_unreachable("Invalid BuiltinType Kind!"); 1138 } 1139 1140 ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) { 1141 ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType()); 1142 if (!ToOriginalTypeOrErr) 1143 return ToOriginalTypeOrErr.takeError(); 1144 1145 return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr); 1146 } 1147 1148 ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) { 1149 ExpectedType ToElementTypeOrErr = import(T->getElementType()); 1150 if (!ToElementTypeOrErr) 1151 return ToElementTypeOrErr.takeError(); 1152 1153 return Importer.getToContext().getComplexType(*ToElementTypeOrErr); 1154 } 1155 1156 ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) { 1157 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); 1158 if (!ToPointeeTypeOrErr) 1159 return ToPointeeTypeOrErr.takeError(); 1160 1161 return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr); 1162 } 1163 1164 ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) { 1165 // FIXME: Check for blocks support in "to" context. 1166 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); 1167 if (!ToPointeeTypeOrErr) 1168 return ToPointeeTypeOrErr.takeError(); 1169 1170 return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr); 1171 } 1172 1173 ExpectedType 1174 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) { 1175 // FIXME: Check for C++ support in "to" context. 1176 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten()); 1177 if (!ToPointeeTypeOrErr) 1178 return ToPointeeTypeOrErr.takeError(); 1179 1180 return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr); 1181 } 1182 1183 ExpectedType 1184 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) { 1185 // FIXME: Check for C++0x support in "to" context. 1186 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten()); 1187 if (!ToPointeeTypeOrErr) 1188 return ToPointeeTypeOrErr.takeError(); 1189 1190 return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr); 1191 } 1192 1193 ExpectedType 1194 ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) { 1195 // FIXME: Check for C++ support in "to" context. 1196 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); 1197 if (!ToPointeeTypeOrErr) 1198 return ToPointeeTypeOrErr.takeError(); 1199 1200 ExpectedTypePtr ClassTypeOrErr = import(T->getClass()); 1201 if (!ClassTypeOrErr) 1202 return ClassTypeOrErr.takeError(); 1203 1204 return Importer.getToContext().getMemberPointerType(*ToPointeeTypeOrErr, 1205 *ClassTypeOrErr); 1206 } 1207 1208 ExpectedType 1209 ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) { 1210 Error Err = Error::success(); 1211 auto ToElementType = importChecked(Err, T->getElementType()); 1212 auto ToSizeExpr = importChecked(Err, T->getSizeExpr()); 1213 if (Err) 1214 return std::move(Err); 1215 1216 return Importer.getToContext().getConstantArrayType( 1217 ToElementType, T->getSize(), ToSizeExpr, T->getSizeModifier(), 1218 T->getIndexTypeCVRQualifiers()); 1219 } 1220 1221 ExpectedType 1222 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) { 1223 ExpectedType ToElementTypeOrErr = import(T->getElementType()); 1224 if (!ToElementTypeOrErr) 1225 return ToElementTypeOrErr.takeError(); 1226 1227 return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr, 1228 T->getSizeModifier(), 1229 T->getIndexTypeCVRQualifiers()); 1230 } 1231 1232 ExpectedType 1233 ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) { 1234 Error Err = Error::success(); 1235 QualType ToElementType = importChecked(Err, T->getElementType()); 1236 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr()); 1237 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange()); 1238 if (Err) 1239 return std::move(Err); 1240 return Importer.getToContext().getVariableArrayType( 1241 ToElementType, ToSizeExpr, T->getSizeModifier(), 1242 T->getIndexTypeCVRQualifiers(), ToBracketsRange); 1243 } 1244 1245 ExpectedType ASTNodeImporter::VisitDependentSizedArrayType( 1246 const DependentSizedArrayType *T) { 1247 Error Err = Error::success(); 1248 QualType ToElementType = importChecked(Err, T->getElementType()); 1249 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr()); 1250 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange()); 1251 if (Err) 1252 return std::move(Err); 1253 // SizeExpr may be null if size is not specified directly. 1254 // For example, 'int a[]'. 1255 1256 return Importer.getToContext().getDependentSizedArrayType( 1257 ToElementType, ToSizeExpr, T->getSizeModifier(), 1258 T->getIndexTypeCVRQualifiers(), ToBracketsRange); 1259 } 1260 1261 ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) { 1262 ExpectedType ToElementTypeOrErr = import(T->getElementType()); 1263 if (!ToElementTypeOrErr) 1264 return ToElementTypeOrErr.takeError(); 1265 1266 return Importer.getToContext().getVectorType(*ToElementTypeOrErr, 1267 T->getNumElements(), 1268 T->getVectorKind()); 1269 } 1270 1271 ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) { 1272 ExpectedType ToElementTypeOrErr = import(T->getElementType()); 1273 if (!ToElementTypeOrErr) 1274 return ToElementTypeOrErr.takeError(); 1275 1276 return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr, 1277 T->getNumElements()); 1278 } 1279 1280 ExpectedType 1281 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) { 1282 // FIXME: What happens if we're importing a function without a prototype 1283 // into C++? Should we make it variadic? 1284 ExpectedType ToReturnTypeOrErr = import(T->getReturnType()); 1285 if (!ToReturnTypeOrErr) 1286 return ToReturnTypeOrErr.takeError(); 1287 1288 return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr, 1289 T->getExtInfo()); 1290 } 1291 1292 ExpectedType 1293 ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) { 1294 ExpectedType ToReturnTypeOrErr = import(T->getReturnType()); 1295 if (!ToReturnTypeOrErr) 1296 return ToReturnTypeOrErr.takeError(); 1297 1298 // Import argument types 1299 SmallVector<QualType, 4> ArgTypes; 1300 for (const auto &A : T->param_types()) { 1301 ExpectedType TyOrErr = import(A); 1302 if (!TyOrErr) 1303 return TyOrErr.takeError(); 1304 ArgTypes.push_back(*TyOrErr); 1305 } 1306 1307 // Import exception types 1308 SmallVector<QualType, 4> ExceptionTypes; 1309 for (const auto &E : T->exceptions()) { 1310 ExpectedType TyOrErr = import(E); 1311 if (!TyOrErr) 1312 return TyOrErr.takeError(); 1313 ExceptionTypes.push_back(*TyOrErr); 1314 } 1315 1316 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo(); 1317 Error Err = Error::success(); 1318 FunctionProtoType::ExtProtoInfo ToEPI; 1319 ToEPI.ExtInfo = FromEPI.ExtInfo; 1320 ToEPI.Variadic = FromEPI.Variadic; 1321 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn; 1322 ToEPI.TypeQuals = FromEPI.TypeQuals; 1323 ToEPI.RefQualifier = FromEPI.RefQualifier; 1324 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type; 1325 ToEPI.ExceptionSpec.NoexceptExpr = 1326 importChecked(Err, FromEPI.ExceptionSpec.NoexceptExpr); 1327 ToEPI.ExceptionSpec.SourceDecl = 1328 importChecked(Err, FromEPI.ExceptionSpec.SourceDecl); 1329 ToEPI.ExceptionSpec.SourceTemplate = 1330 importChecked(Err, FromEPI.ExceptionSpec.SourceTemplate); 1331 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes; 1332 1333 if (Err) 1334 return std::move(Err); 1335 1336 return Importer.getToContext().getFunctionType( 1337 *ToReturnTypeOrErr, ArgTypes, ToEPI); 1338 } 1339 1340 ExpectedType ASTNodeImporter::VisitUnresolvedUsingType( 1341 const UnresolvedUsingType *T) { 1342 Error Err = Error::success(); 1343 auto ToD = importChecked(Err, T->getDecl()); 1344 auto ToPrevD = importChecked(Err, T->getDecl()->getPreviousDecl()); 1345 if (Err) 1346 return std::move(Err); 1347 1348 return Importer.getToContext().getTypeDeclType( 1349 ToD, cast_or_null<TypeDecl>(ToPrevD)); 1350 } 1351 1352 ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) { 1353 ExpectedType ToInnerTypeOrErr = import(T->getInnerType()); 1354 if (!ToInnerTypeOrErr) 1355 return ToInnerTypeOrErr.takeError(); 1356 1357 return Importer.getToContext().getParenType(*ToInnerTypeOrErr); 1358 } 1359 1360 ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) { 1361 Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl()); 1362 if (!ToDeclOrErr) 1363 return ToDeclOrErr.takeError(); 1364 1365 return Importer.getToContext().getTypeDeclType(*ToDeclOrErr); 1366 } 1367 1368 ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) { 1369 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr()); 1370 if (!ToExprOrErr) 1371 return ToExprOrErr.takeError(); 1372 1373 return Importer.getToContext().getTypeOfExprType(*ToExprOrErr); 1374 } 1375 1376 ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) { 1377 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType()); 1378 if (!ToUnderlyingTypeOrErr) 1379 return ToUnderlyingTypeOrErr.takeError(); 1380 1381 return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr); 1382 } 1383 1384 ExpectedType ASTNodeImporter::VisitUsingType(const UsingType *T) { 1385 Expected<UsingShadowDecl *> FoundOrErr = import(T->getFoundDecl()); 1386 if (!FoundOrErr) 1387 return FoundOrErr.takeError(); 1388 Expected<QualType> UnderlyingOrErr = import(T->getUnderlyingType()); 1389 if (!UnderlyingOrErr) 1390 return UnderlyingOrErr.takeError(); 1391 1392 return Importer.getToContext().getUsingType(*FoundOrErr, *UnderlyingOrErr); 1393 } 1394 1395 ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) { 1396 // FIXME: Make sure that the "to" context supports C++0x! 1397 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr()); 1398 if (!ToExprOrErr) 1399 return ToExprOrErr.takeError(); 1400 1401 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType()); 1402 if (!ToUnderlyingTypeOrErr) 1403 return ToUnderlyingTypeOrErr.takeError(); 1404 1405 return Importer.getToContext().getDecltypeType( 1406 *ToExprOrErr, *ToUnderlyingTypeOrErr); 1407 } 1408 1409 ExpectedType 1410 ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) { 1411 ExpectedType ToBaseTypeOrErr = import(T->getBaseType()); 1412 if (!ToBaseTypeOrErr) 1413 return ToBaseTypeOrErr.takeError(); 1414 1415 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType()); 1416 if (!ToUnderlyingTypeOrErr) 1417 return ToUnderlyingTypeOrErr.takeError(); 1418 1419 return Importer.getToContext().getUnaryTransformType( 1420 *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind()); 1421 } 1422 1423 ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) { 1424 // FIXME: Make sure that the "to" context supports C++11! 1425 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType()); 1426 if (!ToDeducedTypeOrErr) 1427 return ToDeducedTypeOrErr.takeError(); 1428 1429 ExpectedDecl ToTypeConstraintConcept = import(T->getTypeConstraintConcept()); 1430 if (!ToTypeConstraintConcept) 1431 return ToTypeConstraintConcept.takeError(); 1432 1433 SmallVector<TemplateArgument, 2> ToTemplateArgs; 1434 ArrayRef<TemplateArgument> FromTemplateArgs = T->getTypeConstraintArguments(); 1435 if (Error Err = ImportTemplateArguments(FromTemplateArgs.data(), 1436 FromTemplateArgs.size(), 1437 ToTemplateArgs)) 1438 return std::move(Err); 1439 1440 return Importer.getToContext().getAutoType( 1441 *ToDeducedTypeOrErr, T->getKeyword(), /*IsDependent*/false, 1442 /*IsPack=*/false, cast_or_null<ConceptDecl>(*ToTypeConstraintConcept), 1443 ToTemplateArgs); 1444 } 1445 1446 ExpectedType ASTNodeImporter::VisitDeducedTemplateSpecializationType( 1447 const DeducedTemplateSpecializationType *T) { 1448 // FIXME: Make sure that the "to" context supports C++17! 1449 Expected<TemplateName> ToTemplateNameOrErr = import(T->getTemplateName()); 1450 if (!ToTemplateNameOrErr) 1451 return ToTemplateNameOrErr.takeError(); 1452 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType()); 1453 if (!ToDeducedTypeOrErr) 1454 return ToDeducedTypeOrErr.takeError(); 1455 1456 return Importer.getToContext().getDeducedTemplateSpecializationType( 1457 *ToTemplateNameOrErr, *ToDeducedTypeOrErr, T->isDependentType()); 1458 } 1459 1460 ExpectedType ASTNodeImporter::VisitInjectedClassNameType( 1461 const InjectedClassNameType *T) { 1462 Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl()); 1463 if (!ToDeclOrErr) 1464 return ToDeclOrErr.takeError(); 1465 1466 ExpectedType ToInjTypeOrErr = import(T->getInjectedSpecializationType()); 1467 if (!ToInjTypeOrErr) 1468 return ToInjTypeOrErr.takeError(); 1469 1470 // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading 1471 // See comments in InjectedClassNameType definition for details 1472 // return Importer.getToContext().getInjectedClassNameType(D, InjType); 1473 enum { 1474 TypeAlignmentInBits = 4, 1475 TypeAlignment = 1 << TypeAlignmentInBits 1476 }; 1477 1478 return QualType(new (Importer.getToContext(), TypeAlignment) 1479 InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0); 1480 } 1481 1482 ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) { 1483 Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl()); 1484 if (!ToDeclOrErr) 1485 return ToDeclOrErr.takeError(); 1486 1487 return Importer.getToContext().getTagDeclType(*ToDeclOrErr); 1488 } 1489 1490 ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) { 1491 Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl()); 1492 if (!ToDeclOrErr) 1493 return ToDeclOrErr.takeError(); 1494 1495 return Importer.getToContext().getTagDeclType(*ToDeclOrErr); 1496 } 1497 1498 ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) { 1499 ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType()); 1500 if (!ToModifiedTypeOrErr) 1501 return ToModifiedTypeOrErr.takeError(); 1502 ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType()); 1503 if (!ToEquivalentTypeOrErr) 1504 return ToEquivalentTypeOrErr.takeError(); 1505 1506 return Importer.getToContext().getAttributedType(T->getAttrKind(), 1507 *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr); 1508 } 1509 1510 ExpectedType ASTNodeImporter::VisitTemplateTypeParmType( 1511 const TemplateTypeParmType *T) { 1512 Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl()); 1513 if (!ToDeclOrErr) 1514 return ToDeclOrErr.takeError(); 1515 1516 return Importer.getToContext().getTemplateTypeParmType( 1517 T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr); 1518 } 1519 1520 ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType( 1521 const SubstTemplateTypeParmType *T) { 1522 Expected<const TemplateTypeParmType *> ReplacedOrErr = 1523 import(T->getReplacedParameter()); 1524 if (!ReplacedOrErr) 1525 return ReplacedOrErr.takeError(); 1526 1527 ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType()); 1528 if (!ToReplacementTypeOrErr) 1529 return ToReplacementTypeOrErr.takeError(); 1530 1531 return Importer.getToContext().getSubstTemplateTypeParmType( 1532 *ReplacedOrErr, ToReplacementTypeOrErr->getCanonicalType()); 1533 } 1534 1535 ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmPackType( 1536 const SubstTemplateTypeParmPackType *T) { 1537 Expected<const TemplateTypeParmType *> ReplacedOrErr = 1538 import(T->getReplacedParameter()); 1539 if (!ReplacedOrErr) 1540 return ReplacedOrErr.takeError(); 1541 1542 Expected<TemplateArgument> ToArgumentPack = import(T->getArgumentPack()); 1543 if (!ToArgumentPack) 1544 return ToArgumentPack.takeError(); 1545 1546 return Importer.getToContext().getSubstTemplateTypeParmPackType( 1547 *ReplacedOrErr, *ToArgumentPack); 1548 } 1549 1550 ExpectedType ASTNodeImporter::VisitTemplateSpecializationType( 1551 const TemplateSpecializationType *T) { 1552 auto ToTemplateOrErr = import(T->getTemplateName()); 1553 if (!ToTemplateOrErr) 1554 return ToTemplateOrErr.takeError(); 1555 1556 SmallVector<TemplateArgument, 2> ToTemplateArgs; 1557 if (Error Err = ImportTemplateArguments( 1558 T->getArgs(), T->getNumArgs(), ToTemplateArgs)) 1559 return std::move(Err); 1560 1561 QualType ToCanonType; 1562 if (!T->isCanonicalUnqualified()) { 1563 QualType FromCanonType 1564 = Importer.getFromContext().getCanonicalType(QualType(T, 0)); 1565 if (ExpectedType TyOrErr = import(FromCanonType)) 1566 ToCanonType = *TyOrErr; 1567 else 1568 return TyOrErr.takeError(); 1569 } 1570 return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr, 1571 ToTemplateArgs, 1572 ToCanonType); 1573 } 1574 1575 ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) { 1576 // Note: the qualifier in an ElaboratedType is optional. 1577 auto ToQualifierOrErr = import(T->getQualifier()); 1578 if (!ToQualifierOrErr) 1579 return ToQualifierOrErr.takeError(); 1580 1581 ExpectedType ToNamedTypeOrErr = import(T->getNamedType()); 1582 if (!ToNamedTypeOrErr) 1583 return ToNamedTypeOrErr.takeError(); 1584 1585 Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl()); 1586 if (!ToOwnedTagDeclOrErr) 1587 return ToOwnedTagDeclOrErr.takeError(); 1588 1589 return Importer.getToContext().getElaboratedType(T->getKeyword(), 1590 *ToQualifierOrErr, 1591 *ToNamedTypeOrErr, 1592 *ToOwnedTagDeclOrErr); 1593 } 1594 1595 ExpectedType 1596 ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) { 1597 ExpectedType ToPatternOrErr = import(T->getPattern()); 1598 if (!ToPatternOrErr) 1599 return ToPatternOrErr.takeError(); 1600 1601 return Importer.getToContext().getPackExpansionType(*ToPatternOrErr, 1602 T->getNumExpansions(), 1603 /*ExpactPack=*/false); 1604 } 1605 1606 ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType( 1607 const DependentTemplateSpecializationType *T) { 1608 auto ToQualifierOrErr = import(T->getQualifier()); 1609 if (!ToQualifierOrErr) 1610 return ToQualifierOrErr.takeError(); 1611 1612 IdentifierInfo *ToName = Importer.Import(T->getIdentifier()); 1613 1614 SmallVector<TemplateArgument, 2> ToPack; 1615 ToPack.reserve(T->getNumArgs()); 1616 if (Error Err = ImportTemplateArguments( 1617 T->getArgs(), T->getNumArgs(), ToPack)) 1618 return std::move(Err); 1619 1620 return Importer.getToContext().getDependentTemplateSpecializationType( 1621 T->getKeyword(), *ToQualifierOrErr, ToName, ToPack); 1622 } 1623 1624 ExpectedType 1625 ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) { 1626 auto ToQualifierOrErr = import(T->getQualifier()); 1627 if (!ToQualifierOrErr) 1628 return ToQualifierOrErr.takeError(); 1629 1630 IdentifierInfo *Name = Importer.Import(T->getIdentifier()); 1631 1632 QualType Canon; 1633 if (T != T->getCanonicalTypeInternal().getTypePtr()) { 1634 if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal())) 1635 Canon = (*TyOrErr).getCanonicalType(); 1636 else 1637 return TyOrErr.takeError(); 1638 } 1639 1640 return Importer.getToContext().getDependentNameType(T->getKeyword(), 1641 *ToQualifierOrErr, 1642 Name, Canon); 1643 } 1644 1645 ExpectedType 1646 ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) { 1647 Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl()); 1648 if (!ToDeclOrErr) 1649 return ToDeclOrErr.takeError(); 1650 1651 return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr); 1652 } 1653 1654 ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) { 1655 ExpectedType ToBaseTypeOrErr = import(T->getBaseType()); 1656 if (!ToBaseTypeOrErr) 1657 return ToBaseTypeOrErr.takeError(); 1658 1659 SmallVector<QualType, 4> TypeArgs; 1660 for (auto TypeArg : T->getTypeArgsAsWritten()) { 1661 if (ExpectedType TyOrErr = import(TypeArg)) 1662 TypeArgs.push_back(*TyOrErr); 1663 else 1664 return TyOrErr.takeError(); 1665 } 1666 1667 SmallVector<ObjCProtocolDecl *, 4> Protocols; 1668 for (auto *P : T->quals()) { 1669 if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P)) 1670 Protocols.push_back(*ProtocolOrErr); 1671 else 1672 return ProtocolOrErr.takeError(); 1673 1674 } 1675 1676 return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs, 1677 Protocols, 1678 T->isKindOfTypeAsWritten()); 1679 } 1680 1681 ExpectedType 1682 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { 1683 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); 1684 if (!ToPointeeTypeOrErr) 1685 return ToPointeeTypeOrErr.takeError(); 1686 1687 return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr); 1688 } 1689 1690 //---------------------------------------------------------------------------- 1691 // Import Declarations 1692 //---------------------------------------------------------------------------- 1693 Error ASTNodeImporter::ImportDeclParts( 1694 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC, 1695 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) { 1696 // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop. 1697 // example: int struct_in_proto(struct data_t{int a;int b;} *d); 1698 // FIXME: We could support these constructs by importing a different type of 1699 // this parameter and by importing the original type of the parameter only 1700 // after the FunctionDecl is created. See 1701 // VisitFunctionDecl::UsedDifferentProtoType. 1702 DeclContext *OrigDC = D->getDeclContext(); 1703 FunctionDecl *FunDecl; 1704 if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) && 1705 FunDecl->hasBody()) { 1706 auto getLeafPointeeType = [](const Type *T) { 1707 while (T->isPointerType() || T->isArrayType()) { 1708 T = T->getPointeeOrArrayElementType(); 1709 } 1710 return T; 1711 }; 1712 for (const ParmVarDecl *P : FunDecl->parameters()) { 1713 const Type *LeafT = 1714 getLeafPointeeType(P->getType().getCanonicalType().getTypePtr()); 1715 auto *RT = dyn_cast<RecordType>(LeafT); 1716 if (RT && RT->getDecl() == D) { 1717 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node) 1718 << D->getDeclKindName(); 1719 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 1720 } 1721 } 1722 } 1723 1724 // Import the context of this declaration. 1725 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 1726 return Err; 1727 1728 // Import the name of this declaration. 1729 if (Error Err = importInto(Name, D->getDeclName())) 1730 return Err; 1731 1732 // Import the location of this declaration. 1733 if (Error Err = importInto(Loc, D->getLocation())) 1734 return Err; 1735 1736 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D)); 1737 if (ToD) 1738 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD)) 1739 return Err; 1740 1741 return Error::success(); 1742 } 1743 1744 Error ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclarationName &Name, 1745 NamedDecl *&ToD, SourceLocation &Loc) { 1746 1747 // Import the name of this declaration. 1748 if (Error Err = importInto(Name, D->getDeclName())) 1749 return Err; 1750 1751 // Import the location of this declaration. 1752 if (Error Err = importInto(Loc, D->getLocation())) 1753 return Err; 1754 1755 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D)); 1756 if (ToD) 1757 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD)) 1758 return Err; 1759 1760 return Error::success(); 1761 } 1762 1763 Error ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) { 1764 if (!FromD) 1765 return Error::success(); 1766 1767 if (!ToD) 1768 if (Error Err = importInto(ToD, FromD)) 1769 return Err; 1770 1771 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) { 1772 if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) { 1773 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && 1774 !ToRecord->getDefinition()) { 1775 if (Error Err = ImportDefinition(FromRecord, ToRecord)) 1776 return Err; 1777 } 1778 } 1779 return Error::success(); 1780 } 1781 1782 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) { 1783 if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) { 1784 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) { 1785 if (Error Err = ImportDefinition(FromEnum, ToEnum)) 1786 return Err; 1787 } 1788 } 1789 return Error::success(); 1790 } 1791 1792 return Error::success(); 1793 } 1794 1795 Error 1796 ASTNodeImporter::ImportDeclarationNameLoc( 1797 const DeclarationNameInfo &From, DeclarationNameInfo& To) { 1798 // NOTE: To.Name and To.Loc are already imported. 1799 // We only have to import To.LocInfo. 1800 switch (To.getName().getNameKind()) { 1801 case DeclarationName::Identifier: 1802 case DeclarationName::ObjCZeroArgSelector: 1803 case DeclarationName::ObjCOneArgSelector: 1804 case DeclarationName::ObjCMultiArgSelector: 1805 case DeclarationName::CXXUsingDirective: 1806 case DeclarationName::CXXDeductionGuideName: 1807 return Error::success(); 1808 1809 case DeclarationName::CXXOperatorName: { 1810 if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange())) 1811 To.setCXXOperatorNameRange(*ToRangeOrErr); 1812 else 1813 return ToRangeOrErr.takeError(); 1814 return Error::success(); 1815 } 1816 case DeclarationName::CXXLiteralOperatorName: { 1817 if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc())) 1818 To.setCXXLiteralOperatorNameLoc(*LocOrErr); 1819 else 1820 return LocOrErr.takeError(); 1821 return Error::success(); 1822 } 1823 case DeclarationName::CXXConstructorName: 1824 case DeclarationName::CXXDestructorName: 1825 case DeclarationName::CXXConversionFunctionName: { 1826 if (auto ToTInfoOrErr = import(From.getNamedTypeInfo())) 1827 To.setNamedTypeInfo(*ToTInfoOrErr); 1828 else 1829 return ToTInfoOrErr.takeError(); 1830 return Error::success(); 1831 } 1832 } 1833 llvm_unreachable("Unknown name kind."); 1834 } 1835 1836 Error 1837 ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) { 1838 if (Importer.isMinimalImport() && !ForceImport) { 1839 auto ToDCOrErr = Importer.ImportContext(FromDC); 1840 return ToDCOrErr.takeError(); 1841 } 1842 1843 // We use strict error handling in case of records and enums, but not 1844 // with e.g. namespaces. 1845 // 1846 // FIXME Clients of the ASTImporter should be able to choose an 1847 // appropriate error handling strategy for their needs. For instance, 1848 // they may not want to mark an entire namespace as erroneous merely 1849 // because there is an ODR error with two typedefs. As another example, 1850 // the client may allow EnumConstantDecls with same names but with 1851 // different values in two distinct translation units. 1852 ChildErrorHandlingStrategy HandleChildErrors(FromDC); 1853 1854 Error ChildErrors = Error::success(); 1855 for (auto *From : FromDC->decls()) { 1856 ExpectedDecl ImportedOrErr = import(From); 1857 1858 // If we are in the process of ImportDefinition(...) for a RecordDecl we 1859 // want to make sure that we are also completing each FieldDecl. There 1860 // are currently cases where this does not happen and this is correctness 1861 // fix since operations such as code generation will expect this to be so. 1862 if (ImportedOrErr) { 1863 FieldDecl *FieldFrom = dyn_cast_or_null<FieldDecl>(From); 1864 Decl *ImportedDecl = *ImportedOrErr; 1865 FieldDecl *FieldTo = dyn_cast_or_null<FieldDecl>(ImportedDecl); 1866 if (FieldFrom && FieldTo) { 1867 RecordDecl *FromRecordDecl = nullptr; 1868 RecordDecl *ToRecordDecl = nullptr; 1869 // If we have a field that is an ArrayType we need to check if the array 1870 // element is a RecordDecl and if so we need to import the definition. 1871 if (FieldFrom->getType()->isArrayType()) { 1872 // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us. 1873 FromRecordDecl = FieldFrom->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl(); 1874 ToRecordDecl = FieldTo->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl(); 1875 } 1876 1877 if (!FromRecordDecl || !ToRecordDecl) { 1878 const RecordType *RecordFrom = 1879 FieldFrom->getType()->getAs<RecordType>(); 1880 const RecordType *RecordTo = FieldTo->getType()->getAs<RecordType>(); 1881 1882 if (RecordFrom && RecordTo) { 1883 FromRecordDecl = RecordFrom->getDecl(); 1884 ToRecordDecl = RecordTo->getDecl(); 1885 } 1886 } 1887 1888 if (FromRecordDecl && ToRecordDecl) { 1889 if (FromRecordDecl->isCompleteDefinition() && 1890 !ToRecordDecl->isCompleteDefinition()) { 1891 Error Err = ImportDefinition(FromRecordDecl, ToRecordDecl); 1892 HandleChildErrors.handleChildImportResult(ChildErrors, 1893 std::move(Err)); 1894 } 1895 } 1896 } 1897 } else { 1898 HandleChildErrors.handleChildImportResult(ChildErrors, 1899 ImportedOrErr.takeError()); 1900 } 1901 } 1902 1903 // We reorder declarations in RecordDecls because they may have another order 1904 // in the "to" context than they have in the "from" context. This may happen 1905 // e.g when we import a class like this: 1906 // struct declToImport { 1907 // int a = c + b; 1908 // int b = 1; 1909 // int c = 2; 1910 // }; 1911 // During the import of `a` we import first the dependencies in sequence, 1912 // thus the order would be `c`, `b`, `a`. We will get the normal order by 1913 // first removing the already imported members and then adding them in the 1914 // order as they apper in the "from" context. 1915 // 1916 // Keeping field order is vital because it determines structure layout. 1917 // 1918 // Here and below, we cannot call field_begin() method and its callers on 1919 // ToDC if it has an external storage. Calling field_begin() will 1920 // automatically load all the fields by calling 1921 // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would 1922 // call ASTImporter::Import(). This is because the ExternalASTSource 1923 // interface in LLDB is implemented by the means of the ASTImporter. However, 1924 // calling an import at this point would result in an uncontrolled import, we 1925 // must avoid that. 1926 const auto *FromRD = dyn_cast<RecordDecl>(FromDC); 1927 if (!FromRD) 1928 return ChildErrors; 1929 1930 auto ToDCOrErr = Importer.ImportContext(FromDC); 1931 if (!ToDCOrErr) { 1932 consumeError(std::move(ChildErrors)); 1933 return ToDCOrErr.takeError(); 1934 } 1935 1936 DeclContext *ToDC = *ToDCOrErr; 1937 // Remove all declarations, which may be in wrong order in the 1938 // lexical DeclContext and then add them in the proper order. 1939 for (auto *D : FromRD->decls()) { 1940 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<FriendDecl>(D)) { 1941 assert(D && "DC contains a null decl"); 1942 Decl *ToD = Importer.GetAlreadyImportedOrNull(D); 1943 // Remove only the decls which we successfully imported. 1944 if (ToD) { 1945 assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD)); 1946 // Remove the decl from its wrong place in the linked list. 1947 ToDC->removeDecl(ToD); 1948 // Add the decl to the end of the linked list. 1949 // This time it will be at the proper place because the enclosing for 1950 // loop iterates in the original (good) order of the decls. 1951 ToDC->addDeclInternal(ToD); 1952 } 1953 } 1954 } 1955 1956 return ChildErrors; 1957 } 1958 1959 Error ASTNodeImporter::ImportDeclContext( 1960 Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) { 1961 auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext()); 1962 if (!ToDCOrErr) 1963 return ToDCOrErr.takeError(); 1964 ToDC = *ToDCOrErr; 1965 1966 if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) { 1967 auto ToLexicalDCOrErr = Importer.ImportContext( 1968 FromD->getLexicalDeclContext()); 1969 if (!ToLexicalDCOrErr) 1970 return ToLexicalDCOrErr.takeError(); 1971 ToLexicalDC = *ToLexicalDCOrErr; 1972 } else 1973 ToLexicalDC = ToDC; 1974 1975 return Error::success(); 1976 } 1977 1978 Error ASTNodeImporter::ImportImplicitMethods( 1979 const CXXRecordDecl *From, CXXRecordDecl *To) { 1980 assert(From->isCompleteDefinition() && To->getDefinition() == To && 1981 "Import implicit methods to or from non-definition"); 1982 1983 for (CXXMethodDecl *FromM : From->methods()) 1984 if (FromM->isImplicit()) { 1985 Expected<CXXMethodDecl *> ToMOrErr = import(FromM); 1986 if (!ToMOrErr) 1987 return ToMOrErr.takeError(); 1988 } 1989 1990 return Error::success(); 1991 } 1992 1993 static Error setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To, 1994 ASTImporter &Importer) { 1995 if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) { 1996 if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef)) 1997 To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr)); 1998 else 1999 return ToTypedefOrErr.takeError(); 2000 } 2001 return Error::success(); 2002 } 2003 2004 Error ASTNodeImporter::ImportDefinition( 2005 RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) { 2006 auto DefinitionCompleter = [To]() { 2007 // There are cases in LLDB when we first import a class without its 2008 // members. The class will have DefinitionData, but no members. Then, 2009 // importDefinition is called from LLDB, which tries to get the members, so 2010 // when we get here, the class already has the DefinitionData set, so we 2011 // must unset the CompleteDefinition here to be able to complete again the 2012 // definition. 2013 To->setCompleteDefinition(false); 2014 To->completeDefinition(); 2015 }; 2016 2017 if (To->getDefinition() || To->isBeingDefined()) { 2018 if (Kind == IDK_Everything || 2019 // In case of lambdas, the class already has a definition ptr set, but 2020 // the contained decls are not imported yet. Also, isBeingDefined was 2021 // set in CXXRecordDecl::CreateLambda. We must import the contained 2022 // decls here and finish the definition. 2023 (To->isLambda() && shouldForceImportDeclContext(Kind))) { 2024 if (To->isLambda()) { 2025 auto *FromCXXRD = cast<CXXRecordDecl>(From); 2026 SmallVector<LambdaCapture, 8> ToCaptures; 2027 ToCaptures.reserve(FromCXXRD->capture_size()); 2028 for (const auto &FromCapture : FromCXXRD->captures()) { 2029 if (auto ToCaptureOrErr = import(FromCapture)) 2030 ToCaptures.push_back(*ToCaptureOrErr); 2031 else 2032 return ToCaptureOrErr.takeError(); 2033 } 2034 cast<CXXRecordDecl>(To)->setCaptures(Importer.getToContext(), 2035 ToCaptures); 2036 } 2037 2038 Error Result = ImportDeclContext(From, /*ForceImport=*/true); 2039 // Finish the definition of the lambda, set isBeingDefined to false. 2040 if (To->isLambda()) 2041 DefinitionCompleter(); 2042 return Result; 2043 } 2044 2045 return Error::success(); 2046 } 2047 2048 To->startDefinition(); 2049 // Set the definition to complete even if it is really not complete during 2050 // import. Some AST constructs (expressions) require the record layout 2051 // to be calculated (see 'clang::computeDependence') at the time they are 2052 // constructed. Import of such AST node is possible during import of the 2053 // same record, there is no way to have a completely defined record (all 2054 // fields imported) at that time without multiple AST import passes. 2055 if (!Importer.isMinimalImport()) 2056 To->setCompleteDefinition(true); 2057 // Complete the definition even if error is returned. 2058 // The RecordDecl may be already part of the AST so it is better to 2059 // have it in complete state even if something is wrong with it. 2060 auto DefinitionCompleterScopeExit = 2061 llvm::make_scope_exit(DefinitionCompleter); 2062 2063 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer)) 2064 return Err; 2065 2066 // Add base classes. 2067 auto *ToCXX = dyn_cast<CXXRecordDecl>(To); 2068 auto *FromCXX = dyn_cast<CXXRecordDecl>(From); 2069 if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) { 2070 2071 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data(); 2072 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data(); 2073 2074 #define FIELD(Name, Width, Merge) \ 2075 ToData.Name = FromData.Name; 2076 #include "clang/AST/CXXRecordDeclDefinitionBits.def" 2077 2078 // Copy over the data stored in RecordDeclBits 2079 ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions()); 2080 2081 SmallVector<CXXBaseSpecifier *, 4> Bases; 2082 for (const auto &Base1 : FromCXX->bases()) { 2083 ExpectedType TyOrErr = import(Base1.getType()); 2084 if (!TyOrErr) 2085 return TyOrErr.takeError(); 2086 2087 SourceLocation EllipsisLoc; 2088 if (Base1.isPackExpansion()) { 2089 if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc())) 2090 EllipsisLoc = *LocOrErr; 2091 else 2092 return LocOrErr.takeError(); 2093 } 2094 2095 // Ensure that we have a definition for the base. 2096 if (Error Err = 2097 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl())) 2098 return Err; 2099 2100 auto RangeOrErr = import(Base1.getSourceRange()); 2101 if (!RangeOrErr) 2102 return RangeOrErr.takeError(); 2103 2104 auto TSIOrErr = import(Base1.getTypeSourceInfo()); 2105 if (!TSIOrErr) 2106 return TSIOrErr.takeError(); 2107 2108 Bases.push_back( 2109 new (Importer.getToContext()) CXXBaseSpecifier( 2110 *RangeOrErr, 2111 Base1.isVirtual(), 2112 Base1.isBaseOfClass(), 2113 Base1.getAccessSpecifierAsWritten(), 2114 *TSIOrErr, 2115 EllipsisLoc)); 2116 } 2117 if (!Bases.empty()) 2118 ToCXX->setBases(Bases.data(), Bases.size()); 2119 } 2120 2121 if (shouldForceImportDeclContext(Kind)) { 2122 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) 2123 return Err; 2124 } 2125 2126 return Error::success(); 2127 } 2128 2129 Error ASTNodeImporter::ImportInitializer(VarDecl *From, VarDecl *To) { 2130 if (To->getAnyInitializer()) 2131 return Error::success(); 2132 2133 Expr *FromInit = From->getInit(); 2134 if (!FromInit) 2135 return Error::success(); 2136 2137 ExpectedExpr ToInitOrErr = import(FromInit); 2138 if (!ToInitOrErr) 2139 return ToInitOrErr.takeError(); 2140 2141 To->setInit(*ToInitOrErr); 2142 if (EvaluatedStmt *FromEval = From->getEvaluatedStmt()) { 2143 EvaluatedStmt *ToEval = To->ensureEvaluatedStmt(); 2144 ToEval->HasConstantInitialization = FromEval->HasConstantInitialization; 2145 ToEval->HasConstantDestruction = FromEval->HasConstantDestruction; 2146 // FIXME: Also import the initializer value. 2147 } 2148 2149 // FIXME: Other bits to merge? 2150 return Error::success(); 2151 } 2152 2153 Error ASTNodeImporter::ImportDefinition( 2154 EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) { 2155 if (To->getDefinition() || To->isBeingDefined()) { 2156 if (Kind == IDK_Everything) 2157 return ImportDeclContext(From, /*ForceImport=*/true); 2158 return Error::success(); 2159 } 2160 2161 To->startDefinition(); 2162 2163 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer)) 2164 return Err; 2165 2166 ExpectedType ToTypeOrErr = 2167 import(Importer.getFromContext().getTypeDeclType(From)); 2168 if (!ToTypeOrErr) 2169 return ToTypeOrErr.takeError(); 2170 2171 ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType()); 2172 if (!ToPromotionTypeOrErr) 2173 return ToPromotionTypeOrErr.takeError(); 2174 2175 if (shouldForceImportDeclContext(Kind)) 2176 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) 2177 return Err; 2178 2179 // FIXME: we might need to merge the number of positive or negative bits 2180 // if the enumerator lists don't match. 2181 To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr, 2182 From->getNumPositiveBits(), 2183 From->getNumNegativeBits()); 2184 return Error::success(); 2185 } 2186 2187 Error ASTNodeImporter::ImportTemplateArguments( 2188 const TemplateArgument *FromArgs, unsigned NumFromArgs, 2189 SmallVectorImpl<TemplateArgument> &ToArgs) { 2190 for (unsigned I = 0; I != NumFromArgs; ++I) { 2191 if (auto ToOrErr = import(FromArgs[I])) 2192 ToArgs.push_back(*ToOrErr); 2193 else 2194 return ToOrErr.takeError(); 2195 } 2196 2197 return Error::success(); 2198 } 2199 2200 // FIXME: Do not forget to remove this and use only 'import'. 2201 Expected<TemplateArgument> 2202 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) { 2203 return import(From); 2204 } 2205 2206 template <typename InContainerTy> 2207 Error ASTNodeImporter::ImportTemplateArgumentListInfo( 2208 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) { 2209 for (const auto &FromLoc : Container) { 2210 if (auto ToLocOrErr = import(FromLoc)) 2211 ToTAInfo.addArgument(*ToLocOrErr); 2212 else 2213 return ToLocOrErr.takeError(); 2214 } 2215 return Error::success(); 2216 } 2217 2218 static StructuralEquivalenceKind 2219 getStructuralEquivalenceKind(const ASTImporter &Importer) { 2220 return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal 2221 : StructuralEquivalenceKind::Default; 2222 } 2223 2224 bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) { 2225 // Eliminate a potential failure point where we attempt to re-import 2226 // something we're trying to import while completing ToRecord. 2227 Decl *ToOrigin = Importer.GetOriginalDecl(To); 2228 if (ToOrigin) { 2229 To = ToOrigin; 2230 } 2231 2232 StructuralEquivalenceContext Ctx( 2233 Importer.getFromContext(), Importer.getToContext(), 2234 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer), 2235 false, Complain); 2236 return Ctx.IsEquivalent(From, To); 2237 } 2238 2239 ExpectedDecl ASTNodeImporter::VisitDecl(Decl *D) { 2240 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node) 2241 << D->getDeclKindName(); 2242 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 2243 } 2244 2245 ExpectedDecl ASTNodeImporter::VisitImportDecl(ImportDecl *D) { 2246 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node) 2247 << D->getDeclKindName(); 2248 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 2249 } 2250 2251 ExpectedDecl ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) { 2252 // Import the context of this declaration. 2253 DeclContext *DC, *LexicalDC; 2254 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 2255 return std::move(Err); 2256 2257 // Import the location of this declaration. 2258 ExpectedSLoc LocOrErr = import(D->getLocation()); 2259 if (!LocOrErr) 2260 return LocOrErr.takeError(); 2261 2262 EmptyDecl *ToD; 2263 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr)) 2264 return ToD; 2265 2266 ToD->setLexicalDeclContext(LexicalDC); 2267 LexicalDC->addDeclInternal(ToD); 2268 return ToD; 2269 } 2270 2271 ExpectedDecl ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 2272 TranslationUnitDecl *ToD = 2273 Importer.getToContext().getTranslationUnitDecl(); 2274 2275 Importer.MapImported(D, ToD); 2276 2277 return ToD; 2278 } 2279 2280 ExpectedDecl ASTNodeImporter::VisitBindingDecl(BindingDecl *D) { 2281 DeclContext *DC, *LexicalDC; 2282 DeclarationName Name; 2283 SourceLocation Loc; 2284 NamedDecl *ToND; 2285 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToND, Loc)) 2286 return std::move(Err); 2287 if (ToND) 2288 return ToND; 2289 2290 BindingDecl *ToD; 2291 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, Loc, 2292 Name.getAsIdentifierInfo())) 2293 return ToD; 2294 2295 Error Err = Error::success(); 2296 QualType ToType = importChecked(Err, D->getType()); 2297 Expr *ToBinding = importChecked(Err, D->getBinding()); 2298 ValueDecl *ToDecomposedDecl = importChecked(Err, D->getDecomposedDecl()); 2299 if (Err) 2300 return std::move(Err); 2301 2302 ToD->setBinding(ToType, ToBinding); 2303 ToD->setDecomposedDecl(ToDecomposedDecl); 2304 addDeclToContexts(D, ToD); 2305 2306 return ToD; 2307 } 2308 2309 ExpectedDecl ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) { 2310 ExpectedSLoc LocOrErr = import(D->getLocation()); 2311 if (!LocOrErr) 2312 return LocOrErr.takeError(); 2313 auto ColonLocOrErr = import(D->getColonLoc()); 2314 if (!ColonLocOrErr) 2315 return ColonLocOrErr.takeError(); 2316 2317 // Import the context of this declaration. 2318 auto DCOrErr = Importer.ImportContext(D->getDeclContext()); 2319 if (!DCOrErr) 2320 return DCOrErr.takeError(); 2321 DeclContext *DC = *DCOrErr; 2322 2323 AccessSpecDecl *ToD; 2324 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(), 2325 DC, *LocOrErr, *ColonLocOrErr)) 2326 return ToD; 2327 2328 // Lexical DeclContext and Semantic DeclContext 2329 // is always the same for the accessSpec. 2330 ToD->setLexicalDeclContext(DC); 2331 DC->addDeclInternal(ToD); 2332 2333 return ToD; 2334 } 2335 2336 ExpectedDecl ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) { 2337 auto DCOrErr = Importer.ImportContext(D->getDeclContext()); 2338 if (!DCOrErr) 2339 return DCOrErr.takeError(); 2340 DeclContext *DC = *DCOrErr; 2341 DeclContext *LexicalDC = DC; 2342 2343 Error Err = Error::success(); 2344 auto ToLocation = importChecked(Err, D->getLocation()); 2345 auto ToRParenLoc = importChecked(Err, D->getRParenLoc()); 2346 auto ToAssertExpr = importChecked(Err, D->getAssertExpr()); 2347 auto ToMessage = importChecked(Err, D->getMessage()); 2348 if (Err) 2349 return std::move(Err); 2350 2351 StaticAssertDecl *ToD; 2352 if (GetImportedOrCreateDecl( 2353 ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage, 2354 ToRParenLoc, D->isFailed())) 2355 return ToD; 2356 2357 ToD->setLexicalDeclContext(LexicalDC); 2358 LexicalDC->addDeclInternal(ToD); 2359 return ToD; 2360 } 2361 2362 ExpectedDecl ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) { 2363 // Import the major distinguishing characteristics of this namespace. 2364 DeclContext *DC, *LexicalDC; 2365 DeclarationName Name; 2366 SourceLocation Loc; 2367 NamedDecl *ToD; 2368 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 2369 return std::move(Err); 2370 if (ToD) 2371 return ToD; 2372 2373 NamespaceDecl *MergeWithNamespace = nullptr; 2374 if (!Name) { 2375 // This is an anonymous namespace. Adopt an existing anonymous 2376 // namespace if we can. 2377 // FIXME: Not testable. 2378 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC)) 2379 MergeWithNamespace = TU->getAnonymousNamespace(); 2380 else 2381 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace(); 2382 } else { 2383 SmallVector<NamedDecl *, 4> ConflictingDecls; 2384 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 2385 for (auto *FoundDecl : FoundDecls) { 2386 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace)) 2387 continue; 2388 2389 if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) { 2390 MergeWithNamespace = FoundNS; 2391 ConflictingDecls.clear(); 2392 break; 2393 } 2394 2395 ConflictingDecls.push_back(FoundDecl); 2396 } 2397 2398 if (!ConflictingDecls.empty()) { 2399 ExpectedName NameOrErr = Importer.HandleNameConflict( 2400 Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(), 2401 ConflictingDecls.size()); 2402 if (NameOrErr) 2403 Name = NameOrErr.get(); 2404 else 2405 return NameOrErr.takeError(); 2406 } 2407 } 2408 2409 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 2410 if (!BeginLocOrErr) 2411 return BeginLocOrErr.takeError(); 2412 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc()); 2413 if (!RBraceLocOrErr) 2414 return RBraceLocOrErr.takeError(); 2415 2416 // Create the "to" namespace, if needed. 2417 NamespaceDecl *ToNamespace = MergeWithNamespace; 2418 if (!ToNamespace) { 2419 if (GetImportedOrCreateDecl( 2420 ToNamespace, D, Importer.getToContext(), DC, D->isInline(), 2421 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(), 2422 /*PrevDecl=*/nullptr)) 2423 return ToNamespace; 2424 ToNamespace->setRBraceLoc(*RBraceLocOrErr); 2425 ToNamespace->setLexicalDeclContext(LexicalDC); 2426 LexicalDC->addDeclInternal(ToNamespace); 2427 2428 // If this is an anonymous namespace, register it as the anonymous 2429 // namespace within its context. 2430 if (!Name) { 2431 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC)) 2432 TU->setAnonymousNamespace(ToNamespace); 2433 else 2434 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace); 2435 } 2436 } 2437 Importer.MapImported(D, ToNamespace); 2438 2439 if (Error Err = ImportDeclContext(D)) 2440 return std::move(Err); 2441 2442 return ToNamespace; 2443 } 2444 2445 ExpectedDecl ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 2446 // Import the major distinguishing characteristics of this namespace. 2447 DeclContext *DC, *LexicalDC; 2448 DeclarationName Name; 2449 SourceLocation Loc; 2450 NamedDecl *LookupD; 2451 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc)) 2452 return std::move(Err); 2453 if (LookupD) 2454 return LookupD; 2455 2456 // NOTE: No conflict resolution is done for namespace aliases now. 2457 2458 Error Err = Error::success(); 2459 auto ToNamespaceLoc = importChecked(Err, D->getNamespaceLoc()); 2460 auto ToAliasLoc = importChecked(Err, D->getAliasLoc()); 2461 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 2462 auto ToTargetNameLoc = importChecked(Err, D->getTargetNameLoc()); 2463 auto ToNamespace = importChecked(Err, D->getNamespace()); 2464 if (Err) 2465 return std::move(Err); 2466 2467 IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier()); 2468 2469 NamespaceAliasDecl *ToD; 2470 if (GetImportedOrCreateDecl( 2471 ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc, 2472 ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace)) 2473 return ToD; 2474 2475 ToD->setLexicalDeclContext(LexicalDC); 2476 LexicalDC->addDeclInternal(ToD); 2477 2478 return ToD; 2479 } 2480 2481 ExpectedDecl 2482 ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) { 2483 // Import the major distinguishing characteristics of this typedef. 2484 DeclarationName Name; 2485 SourceLocation Loc; 2486 NamedDecl *ToD; 2487 // Do not import the DeclContext, we will import it once the TypedefNameDecl 2488 // is created. 2489 if (Error Err = ImportDeclParts(D, Name, ToD, Loc)) 2490 return std::move(Err); 2491 if (ToD) 2492 return ToD; 2493 2494 DeclContext *DC = cast_or_null<DeclContext>( 2495 Importer.GetAlreadyImportedOrNull(cast<Decl>(D->getDeclContext()))); 2496 DeclContext *LexicalDC = 2497 cast_or_null<DeclContext>(Importer.GetAlreadyImportedOrNull( 2498 cast<Decl>(D->getLexicalDeclContext()))); 2499 2500 // If this typedef is not in block scope, determine whether we've 2501 // seen a typedef with the same name (that we can merge with) or any 2502 // other entity by that name (which name lookup could conflict with). 2503 // Note: Repeated typedefs are not valid in C99: 2504 // 'typedef int T; typedef int T;' is invalid 2505 // We do not care about this now. 2506 if (DC && !DC->isFunctionOrMethod()) { 2507 SmallVector<NamedDecl *, 4> ConflictingDecls; 2508 unsigned IDNS = Decl::IDNS_Ordinary; 2509 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 2510 for (auto *FoundDecl : FoundDecls) { 2511 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 2512 continue; 2513 if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) { 2514 if (!hasSameVisibilityContextAndLinkage(FoundTypedef, D)) 2515 continue; 2516 2517 QualType FromUT = D->getUnderlyingType(); 2518 QualType FoundUT = FoundTypedef->getUnderlyingType(); 2519 if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) { 2520 // If the "From" context has a complete underlying type but we 2521 // already have a complete underlying type then return with that. 2522 if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType()) 2523 return Importer.MapImported(D, FoundTypedef); 2524 // FIXME Handle redecl chain. When you do that make consistent changes 2525 // in ASTImporterLookupTable too. 2526 } else { 2527 ConflictingDecls.push_back(FoundDecl); 2528 } 2529 } 2530 } 2531 2532 if (!ConflictingDecls.empty()) { 2533 ExpectedName NameOrErr = Importer.HandleNameConflict( 2534 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); 2535 if (NameOrErr) 2536 Name = NameOrErr.get(); 2537 else 2538 return NameOrErr.takeError(); 2539 } 2540 } 2541 2542 Error Err = Error::success(); 2543 auto ToUnderlyingType = importChecked(Err, D->getUnderlyingType()); 2544 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo()); 2545 auto ToBeginLoc = importChecked(Err, D->getBeginLoc()); 2546 if (Err) 2547 return std::move(Err); 2548 2549 // Create the new typedef node. 2550 // FIXME: ToUnderlyingType is not used. 2551 (void)ToUnderlyingType; 2552 TypedefNameDecl *ToTypedef; 2553 if (IsAlias) { 2554 if (GetImportedOrCreateDecl<TypeAliasDecl>( 2555 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc, 2556 Name.getAsIdentifierInfo(), ToTypeSourceInfo)) 2557 return ToTypedef; 2558 } else if (GetImportedOrCreateDecl<TypedefDecl>( 2559 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc, 2560 Name.getAsIdentifierInfo(), ToTypeSourceInfo)) 2561 return ToTypedef; 2562 2563 // Import the DeclContext and set it to the Typedef. 2564 if ((Err = ImportDeclContext(D, DC, LexicalDC))) 2565 return std::move(Err); 2566 ToTypedef->setDeclContext(DC); 2567 ToTypedef->setLexicalDeclContext(LexicalDC); 2568 // Add to the lookupTable because we could not do that in MapImported. 2569 Importer.AddToLookupTable(ToTypedef); 2570 2571 ToTypedef->setAccess(D->getAccess()); 2572 2573 // Templated declarations should not appear in DeclContext. 2574 TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr; 2575 if (!FromAlias || !FromAlias->getDescribedAliasTemplate()) 2576 LexicalDC->addDeclInternal(ToTypedef); 2577 2578 return ToTypedef; 2579 } 2580 2581 ExpectedDecl ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) { 2582 return VisitTypedefNameDecl(D, /*IsAlias=*/false); 2583 } 2584 2585 ExpectedDecl ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) { 2586 return VisitTypedefNameDecl(D, /*IsAlias=*/true); 2587 } 2588 2589 ExpectedDecl 2590 ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 2591 // Import the major distinguishing characteristics of this typedef. 2592 DeclContext *DC, *LexicalDC; 2593 DeclarationName Name; 2594 SourceLocation Loc; 2595 NamedDecl *FoundD; 2596 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc)) 2597 return std::move(Err); 2598 if (FoundD) 2599 return FoundD; 2600 2601 // If this typedef is not in block scope, determine whether we've 2602 // seen a typedef with the same name (that we can merge with) or any 2603 // other entity by that name (which name lookup could conflict with). 2604 if (!DC->isFunctionOrMethod()) { 2605 SmallVector<NamedDecl *, 4> ConflictingDecls; 2606 unsigned IDNS = Decl::IDNS_Ordinary; 2607 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 2608 for (auto *FoundDecl : FoundDecls) { 2609 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 2610 continue; 2611 if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl)) 2612 return Importer.MapImported(D, FoundAlias); 2613 ConflictingDecls.push_back(FoundDecl); 2614 } 2615 2616 if (!ConflictingDecls.empty()) { 2617 ExpectedName NameOrErr = Importer.HandleNameConflict( 2618 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); 2619 if (NameOrErr) 2620 Name = NameOrErr.get(); 2621 else 2622 return NameOrErr.takeError(); 2623 } 2624 } 2625 2626 Error Err = Error::success(); 2627 auto ToTemplateParameters = importChecked(Err, D->getTemplateParameters()); 2628 auto ToTemplatedDecl = importChecked(Err, D->getTemplatedDecl()); 2629 if (Err) 2630 return std::move(Err); 2631 2632 TypeAliasTemplateDecl *ToAlias; 2633 if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc, 2634 Name, ToTemplateParameters, ToTemplatedDecl)) 2635 return ToAlias; 2636 2637 ToTemplatedDecl->setDescribedAliasTemplate(ToAlias); 2638 2639 ToAlias->setAccess(D->getAccess()); 2640 ToAlias->setLexicalDeclContext(LexicalDC); 2641 LexicalDC->addDeclInternal(ToAlias); 2642 if (DC != Importer.getToContext().getTranslationUnitDecl()) 2643 updateLookupTableForTemplateParameters(*ToTemplateParameters); 2644 return ToAlias; 2645 } 2646 2647 ExpectedDecl ASTNodeImporter::VisitLabelDecl(LabelDecl *D) { 2648 // Import the major distinguishing characteristics of this label. 2649 DeclContext *DC, *LexicalDC; 2650 DeclarationName Name; 2651 SourceLocation Loc; 2652 NamedDecl *ToD; 2653 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 2654 return std::move(Err); 2655 if (ToD) 2656 return ToD; 2657 2658 assert(LexicalDC->isFunctionOrMethod()); 2659 2660 LabelDecl *ToLabel; 2661 if (D->isGnuLocal()) { 2662 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 2663 if (!BeginLocOrErr) 2664 return BeginLocOrErr.takeError(); 2665 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc, 2666 Name.getAsIdentifierInfo(), *BeginLocOrErr)) 2667 return ToLabel; 2668 2669 } else { 2670 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc, 2671 Name.getAsIdentifierInfo())) 2672 return ToLabel; 2673 2674 } 2675 2676 Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt()); 2677 if (!ToStmtOrErr) 2678 return ToStmtOrErr.takeError(); 2679 2680 ToLabel->setStmt(*ToStmtOrErr); 2681 ToLabel->setLexicalDeclContext(LexicalDC); 2682 LexicalDC->addDeclInternal(ToLabel); 2683 return ToLabel; 2684 } 2685 2686 ExpectedDecl ASTNodeImporter::VisitEnumDecl(EnumDecl *D) { 2687 // Import the major distinguishing characteristics of this enum. 2688 DeclContext *DC, *LexicalDC; 2689 DeclarationName Name; 2690 SourceLocation Loc; 2691 NamedDecl *ToD; 2692 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 2693 return std::move(Err); 2694 if (ToD) 2695 return ToD; 2696 2697 // Figure out what enum name we're looking for. 2698 unsigned IDNS = Decl::IDNS_Tag; 2699 DeclarationName SearchName = Name; 2700 if (!SearchName && D->getTypedefNameForAnonDecl()) { 2701 if (Error Err = importInto( 2702 SearchName, D->getTypedefNameForAnonDecl()->getDeclName())) 2703 return std::move(Err); 2704 IDNS = Decl::IDNS_Ordinary; 2705 } else if (Importer.getToContext().getLangOpts().CPlusPlus) 2706 IDNS |= Decl::IDNS_Ordinary; 2707 2708 // We may already have an enum of the same name; try to find and match it. 2709 EnumDecl *PrevDecl = nullptr; 2710 if (!DC->isFunctionOrMethod() && SearchName) { 2711 SmallVector<NamedDecl *, 4> ConflictingDecls; 2712 auto FoundDecls = 2713 Importer.findDeclsInToCtx(DC, SearchName); 2714 for (auto *FoundDecl : FoundDecls) { 2715 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 2716 continue; 2717 2718 if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) { 2719 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>()) 2720 FoundDecl = Tag->getDecl(); 2721 } 2722 2723 if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) { 2724 if (!hasSameVisibilityContextAndLinkage(FoundEnum, D)) 2725 continue; 2726 if (IsStructuralMatch(D, FoundEnum)) { 2727 EnumDecl *FoundDef = FoundEnum->getDefinition(); 2728 if (D->isThisDeclarationADefinition() && FoundDef) 2729 return Importer.MapImported(D, FoundDef); 2730 PrevDecl = FoundEnum->getMostRecentDecl(); 2731 break; 2732 } 2733 ConflictingDecls.push_back(FoundDecl); 2734 } 2735 } 2736 2737 if (!ConflictingDecls.empty()) { 2738 ExpectedName NameOrErr = Importer.HandleNameConflict( 2739 SearchName, DC, IDNS, ConflictingDecls.data(), 2740 ConflictingDecls.size()); 2741 if (NameOrErr) 2742 Name = NameOrErr.get(); 2743 else 2744 return NameOrErr.takeError(); 2745 } 2746 } 2747 2748 Error Err = Error::success(); 2749 auto ToBeginLoc = importChecked(Err, D->getBeginLoc()); 2750 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 2751 auto ToIntegerType = importChecked(Err, D->getIntegerType()); 2752 auto ToBraceRange = importChecked(Err, D->getBraceRange()); 2753 if (Err) 2754 return std::move(Err); 2755 2756 // Create the enum declaration. 2757 EnumDecl *D2; 2758 if (GetImportedOrCreateDecl( 2759 D2, D, Importer.getToContext(), DC, ToBeginLoc, 2760 Loc, Name.getAsIdentifierInfo(), PrevDecl, D->isScoped(), 2761 D->isScopedUsingClassTag(), D->isFixed())) 2762 return D2; 2763 2764 D2->setQualifierInfo(ToQualifierLoc); 2765 D2->setIntegerType(ToIntegerType); 2766 D2->setBraceRange(ToBraceRange); 2767 D2->setAccess(D->getAccess()); 2768 D2->setLexicalDeclContext(LexicalDC); 2769 addDeclToContexts(D, D2); 2770 2771 if (MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo()) { 2772 TemplateSpecializationKind SK = MemberInfo->getTemplateSpecializationKind(); 2773 EnumDecl *FromInst = D->getInstantiatedFromMemberEnum(); 2774 if (Expected<EnumDecl *> ToInstOrErr = import(FromInst)) 2775 D2->setInstantiationOfMemberEnum(*ToInstOrErr, SK); 2776 else 2777 return ToInstOrErr.takeError(); 2778 if (ExpectedSLoc POIOrErr = import(MemberInfo->getPointOfInstantiation())) 2779 D2->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr); 2780 else 2781 return POIOrErr.takeError(); 2782 } 2783 2784 // Import the definition 2785 if (D->isCompleteDefinition()) 2786 if (Error Err = ImportDefinition(D, D2)) 2787 return std::move(Err); 2788 2789 return D2; 2790 } 2791 2792 ExpectedDecl ASTNodeImporter::VisitRecordDecl(RecordDecl *D) { 2793 bool IsFriendTemplate = false; 2794 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) { 2795 IsFriendTemplate = 2796 DCXX->getDescribedClassTemplate() && 2797 DCXX->getDescribedClassTemplate()->getFriendObjectKind() != 2798 Decl::FOK_None; 2799 } 2800 2801 // Import the major distinguishing characteristics of this record. 2802 DeclContext *DC = nullptr, *LexicalDC = nullptr; 2803 DeclarationName Name; 2804 SourceLocation Loc; 2805 NamedDecl *ToD = nullptr; 2806 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 2807 return std::move(Err); 2808 if (ToD) 2809 return ToD; 2810 2811 // Figure out what structure name we're looking for. 2812 unsigned IDNS = Decl::IDNS_Tag; 2813 DeclarationName SearchName = Name; 2814 if (!SearchName && D->getTypedefNameForAnonDecl()) { 2815 if (Error Err = importInto( 2816 SearchName, D->getTypedefNameForAnonDecl()->getDeclName())) 2817 return std::move(Err); 2818 IDNS = Decl::IDNS_Ordinary; 2819 } else if (Importer.getToContext().getLangOpts().CPlusPlus) 2820 IDNS |= Decl::IDNS_Ordinary | Decl::IDNS_TagFriend; 2821 2822 // We may already have a record of the same name; try to find and match it. 2823 RecordDecl *PrevDecl = nullptr; 2824 if (!DC->isFunctionOrMethod() && !D->isLambda()) { 2825 SmallVector<NamedDecl *, 4> ConflictingDecls; 2826 auto FoundDecls = 2827 Importer.findDeclsInToCtx(DC, SearchName); 2828 if (!FoundDecls.empty()) { 2829 // We're going to have to compare D against potentially conflicting Decls, 2830 // so complete it. 2831 if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition()) 2832 D->getASTContext().getExternalSource()->CompleteType(D); 2833 } 2834 2835 for (auto *FoundDecl : FoundDecls) { 2836 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 2837 continue; 2838 2839 Decl *Found = FoundDecl; 2840 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) { 2841 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>()) 2842 Found = Tag->getDecl(); 2843 } 2844 2845 if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) { 2846 // Do not emit false positive diagnostic in case of unnamed 2847 // struct/union and in case of anonymous structs. Would be false 2848 // because there may be several anonymous/unnamed structs in a class. 2849 // E.g. these are both valid: 2850 // struct A { // unnamed structs 2851 // struct { struct A *next; } entry0; 2852 // struct { struct A *next; } entry1; 2853 // }; 2854 // struct X { struct { int a; }; struct { int b; }; }; // anon structs 2855 if (!SearchName) 2856 if (!IsStructuralMatch(D, FoundRecord, false)) 2857 continue; 2858 2859 if (!hasSameVisibilityContextAndLinkage(FoundRecord, D)) 2860 continue; 2861 2862 if (IsStructuralMatch(D, FoundRecord)) { 2863 RecordDecl *FoundDef = FoundRecord->getDefinition(); 2864 if (D->isThisDeclarationADefinition() && FoundDef) { 2865 // FIXME: Structural equivalence check should check for same 2866 // user-defined methods. 2867 Importer.MapImported(D, FoundDef); 2868 if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) { 2869 auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef); 2870 assert(FoundCXX && "Record type mismatch"); 2871 2872 if (!Importer.isMinimalImport()) 2873 // FoundDef may not have every implicit method that D has 2874 // because implicit methods are created only if they are used. 2875 if (Error Err = ImportImplicitMethods(DCXX, FoundCXX)) 2876 return std::move(Err); 2877 } 2878 } 2879 PrevDecl = FoundRecord->getMostRecentDecl(); 2880 break; 2881 } 2882 ConflictingDecls.push_back(FoundDecl); 2883 } // kind is RecordDecl 2884 } // for 2885 2886 if (!ConflictingDecls.empty() && SearchName) { 2887 ExpectedName NameOrErr = Importer.HandleNameConflict( 2888 SearchName, DC, IDNS, ConflictingDecls.data(), 2889 ConflictingDecls.size()); 2890 if (NameOrErr) 2891 Name = NameOrErr.get(); 2892 else 2893 return NameOrErr.takeError(); 2894 } 2895 } 2896 2897 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 2898 if (!BeginLocOrErr) 2899 return BeginLocOrErr.takeError(); 2900 2901 // Create the record declaration. 2902 RecordDecl *D2 = nullptr; 2903 CXXRecordDecl *D2CXX = nullptr; 2904 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) { 2905 if (DCXX->isLambda()) { 2906 auto TInfoOrErr = import(DCXX->getLambdaTypeInfo()); 2907 if (!TInfoOrErr) 2908 return TInfoOrErr.takeError(); 2909 if (GetImportedOrCreateSpecialDecl( 2910 D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(), 2911 DC, *TInfoOrErr, Loc, DCXX->getLambdaDependencyKind(), 2912 DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault())) 2913 return D2CXX; 2914 ExpectedDecl CDeclOrErr = import(DCXX->getLambdaContextDecl()); 2915 if (!CDeclOrErr) 2916 return CDeclOrErr.takeError(); 2917 D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), *CDeclOrErr, 2918 DCXX->hasKnownLambdaInternalLinkage()); 2919 D2CXX->setDeviceLambdaManglingNumber( 2920 DCXX->getDeviceLambdaManglingNumber()); 2921 } else if (DCXX->isInjectedClassName()) { 2922 // We have to be careful to do a similar dance to the one in 2923 // Sema::ActOnStartCXXMemberDeclarations 2924 const bool DelayTypeCreation = true; 2925 if (GetImportedOrCreateDecl( 2926 D2CXX, D, Importer.getToContext(), D->getTagKind(), DC, 2927 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(), 2928 cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation)) 2929 return D2CXX; 2930 Importer.getToContext().getTypeDeclType( 2931 D2CXX, dyn_cast<CXXRecordDecl>(DC)); 2932 } else { 2933 if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(), 2934 D->getTagKind(), DC, *BeginLocOrErr, Loc, 2935 Name.getAsIdentifierInfo(), 2936 cast_or_null<CXXRecordDecl>(PrevDecl))) 2937 return D2CXX; 2938 } 2939 2940 D2 = D2CXX; 2941 D2->setAccess(D->getAccess()); 2942 D2->setLexicalDeclContext(LexicalDC); 2943 addDeclToContexts(D, D2); 2944 2945 if (ClassTemplateDecl *FromDescribed = 2946 DCXX->getDescribedClassTemplate()) { 2947 ClassTemplateDecl *ToDescribed; 2948 if (Error Err = importInto(ToDescribed, FromDescribed)) 2949 return std::move(Err); 2950 D2CXX->setDescribedClassTemplate(ToDescribed); 2951 if (!DCXX->isInjectedClassName() && !IsFriendTemplate) { 2952 // In a record describing a template the type should be an 2953 // InjectedClassNameType (see Sema::CheckClassTemplate). Update the 2954 // previously set type to the correct value here (ToDescribed is not 2955 // available at record create). 2956 // FIXME: The previous type is cleared but not removed from 2957 // ASTContext's internal storage. 2958 CXXRecordDecl *Injected = nullptr; 2959 for (NamedDecl *Found : D2CXX->noload_lookup(Name)) { 2960 auto *Record = dyn_cast<CXXRecordDecl>(Found); 2961 if (Record && Record->isInjectedClassName()) { 2962 Injected = Record; 2963 break; 2964 } 2965 } 2966 // Create an injected type for the whole redecl chain. 2967 SmallVector<Decl *, 2> Redecls = 2968 getCanonicalForwardRedeclChain(D2CXX); 2969 for (auto *R : Redecls) { 2970 auto *RI = cast<CXXRecordDecl>(R); 2971 RI->setTypeForDecl(nullptr); 2972 // Below we create a new injected type and assign that to the 2973 // canonical decl, subsequent declarations in the chain will reuse 2974 // that type. 2975 Importer.getToContext().getInjectedClassNameType( 2976 RI, ToDescribed->getInjectedClassNameSpecialization()); 2977 } 2978 // Set the new type for the previous injected decl too. 2979 if (Injected) { 2980 Injected->setTypeForDecl(nullptr); 2981 Importer.getToContext().getTypeDeclType(Injected, D2CXX); 2982 } 2983 } 2984 } else if (MemberSpecializationInfo *MemberInfo = 2985 DCXX->getMemberSpecializationInfo()) { 2986 TemplateSpecializationKind SK = 2987 MemberInfo->getTemplateSpecializationKind(); 2988 CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass(); 2989 2990 if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst)) 2991 D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK); 2992 else 2993 return ToInstOrErr.takeError(); 2994 2995 if (ExpectedSLoc POIOrErr = 2996 import(MemberInfo->getPointOfInstantiation())) 2997 D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation( 2998 *POIOrErr); 2999 else 3000 return POIOrErr.takeError(); 3001 } 3002 3003 } else { 3004 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), 3005 D->getTagKind(), DC, *BeginLocOrErr, Loc, 3006 Name.getAsIdentifierInfo(), PrevDecl)) 3007 return D2; 3008 D2->setLexicalDeclContext(LexicalDC); 3009 addDeclToContexts(D, D2); 3010 } 3011 3012 if (auto BraceRangeOrErr = import(D->getBraceRange())) 3013 D2->setBraceRange(*BraceRangeOrErr); 3014 else 3015 return BraceRangeOrErr.takeError(); 3016 if (auto QualifierLocOrErr = import(D->getQualifierLoc())) 3017 D2->setQualifierInfo(*QualifierLocOrErr); 3018 else 3019 return QualifierLocOrErr.takeError(); 3020 3021 if (D->isAnonymousStructOrUnion()) 3022 D2->setAnonymousStructOrUnion(true); 3023 3024 if (D->isCompleteDefinition()) 3025 if (Error Err = ImportDefinition(D, D2, IDK_Default)) 3026 return std::move(Err); 3027 3028 return D2; 3029 } 3030 3031 ExpectedDecl ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) { 3032 // Import the major distinguishing characteristics of this enumerator. 3033 DeclContext *DC, *LexicalDC; 3034 DeclarationName Name; 3035 SourceLocation Loc; 3036 NamedDecl *ToD; 3037 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 3038 return std::move(Err); 3039 if (ToD) 3040 return ToD; 3041 3042 // Determine whether there are any other declarations with the same name and 3043 // in the same context. 3044 if (!LexicalDC->isFunctionOrMethod()) { 3045 SmallVector<NamedDecl *, 4> ConflictingDecls; 3046 unsigned IDNS = Decl::IDNS_Ordinary; 3047 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 3048 for (auto *FoundDecl : FoundDecls) { 3049 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 3050 continue; 3051 3052 if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) { 3053 if (IsStructuralMatch(D, FoundEnumConstant)) 3054 return Importer.MapImported(D, FoundEnumConstant); 3055 ConflictingDecls.push_back(FoundDecl); 3056 } 3057 } 3058 3059 if (!ConflictingDecls.empty()) { 3060 ExpectedName NameOrErr = Importer.HandleNameConflict( 3061 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); 3062 if (NameOrErr) 3063 Name = NameOrErr.get(); 3064 else 3065 return NameOrErr.takeError(); 3066 } 3067 } 3068 3069 ExpectedType TypeOrErr = import(D->getType()); 3070 if (!TypeOrErr) 3071 return TypeOrErr.takeError(); 3072 3073 ExpectedExpr InitOrErr = import(D->getInitExpr()); 3074 if (!InitOrErr) 3075 return InitOrErr.takeError(); 3076 3077 EnumConstantDecl *ToEnumerator; 3078 if (GetImportedOrCreateDecl( 3079 ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc, 3080 Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal())) 3081 return ToEnumerator; 3082 3083 ToEnumerator->setAccess(D->getAccess()); 3084 ToEnumerator->setLexicalDeclContext(LexicalDC); 3085 LexicalDC->addDeclInternal(ToEnumerator); 3086 return ToEnumerator; 3087 } 3088 3089 Error ASTNodeImporter::ImportTemplateParameterLists(const DeclaratorDecl *FromD, 3090 DeclaratorDecl *ToD) { 3091 unsigned int Num = FromD->getNumTemplateParameterLists(); 3092 if (Num == 0) 3093 return Error::success(); 3094 SmallVector<TemplateParameterList *, 2> ToTPLists(Num); 3095 for (unsigned int I = 0; I < Num; ++I) 3096 if (Expected<TemplateParameterList *> ToTPListOrErr = 3097 import(FromD->getTemplateParameterList(I))) 3098 ToTPLists[I] = *ToTPListOrErr; 3099 else 3100 return ToTPListOrErr.takeError(); 3101 ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists); 3102 return Error::success(); 3103 } 3104 3105 Error ASTNodeImporter::ImportTemplateInformation( 3106 FunctionDecl *FromFD, FunctionDecl *ToFD) { 3107 switch (FromFD->getTemplatedKind()) { 3108 case FunctionDecl::TK_NonTemplate: 3109 case FunctionDecl::TK_FunctionTemplate: 3110 return Error::success(); 3111 3112 case FunctionDecl::TK_DependentNonTemplate: 3113 if (Expected<FunctionDecl *> InstFDOrErr = 3114 import(FromFD->getInstantiatedFromDecl())) 3115 ToFD->setInstantiatedFromDecl(*InstFDOrErr); 3116 return Error::success(); 3117 case FunctionDecl::TK_MemberSpecialization: { 3118 TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind(); 3119 3120 if (Expected<FunctionDecl *> InstFDOrErr = 3121 import(FromFD->getInstantiatedFromMemberFunction())) 3122 ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK); 3123 else 3124 return InstFDOrErr.takeError(); 3125 3126 if (ExpectedSLoc POIOrErr = import( 3127 FromFD->getMemberSpecializationInfo()->getPointOfInstantiation())) 3128 ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr); 3129 else 3130 return POIOrErr.takeError(); 3131 3132 return Error::success(); 3133 } 3134 3135 case FunctionDecl::TK_FunctionTemplateSpecialization: { 3136 auto FunctionAndArgsOrErr = 3137 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD); 3138 if (!FunctionAndArgsOrErr) 3139 return FunctionAndArgsOrErr.takeError(); 3140 3141 TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy( 3142 Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr)); 3143 3144 auto *FTSInfo = FromFD->getTemplateSpecializationInfo(); 3145 TemplateArgumentListInfo ToTAInfo; 3146 const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten; 3147 if (FromTAArgsAsWritten) 3148 if (Error Err = ImportTemplateArgumentListInfo( 3149 *FromTAArgsAsWritten, ToTAInfo)) 3150 return Err; 3151 3152 ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation()); 3153 if (!POIOrErr) 3154 return POIOrErr.takeError(); 3155 3156 if (Error Err = ImportTemplateParameterLists(FromFD, ToFD)) 3157 return Err; 3158 3159 TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind(); 3160 ToFD->setFunctionTemplateSpecialization( 3161 std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr, 3162 TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr); 3163 return Error::success(); 3164 } 3165 3166 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: { 3167 auto *FromInfo = FromFD->getDependentSpecializationInfo(); 3168 UnresolvedSet<8> TemplDecls; 3169 unsigned NumTemplates = FromInfo->getNumTemplates(); 3170 for (unsigned I = 0; I < NumTemplates; I++) { 3171 if (Expected<FunctionTemplateDecl *> ToFTDOrErr = 3172 import(FromInfo->getTemplate(I))) 3173 TemplDecls.addDecl(*ToFTDOrErr); 3174 else 3175 return ToFTDOrErr.takeError(); 3176 } 3177 3178 // Import TemplateArgumentListInfo. 3179 TemplateArgumentListInfo ToTAInfo; 3180 if (Error Err = ImportTemplateArgumentListInfo( 3181 FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(), 3182 llvm::makeArrayRef( 3183 FromInfo->getTemplateArgs(), FromInfo->getNumTemplateArgs()), 3184 ToTAInfo)) 3185 return Err; 3186 3187 ToFD->setDependentTemplateSpecialization(Importer.getToContext(), 3188 TemplDecls, ToTAInfo); 3189 return Error::success(); 3190 } 3191 } 3192 llvm_unreachable("All cases should be covered!"); 3193 } 3194 3195 Expected<FunctionDecl *> 3196 ASTNodeImporter::FindFunctionTemplateSpecialization(FunctionDecl *FromFD) { 3197 auto FunctionAndArgsOrErr = 3198 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD); 3199 if (!FunctionAndArgsOrErr) 3200 return FunctionAndArgsOrErr.takeError(); 3201 3202 FunctionTemplateDecl *Template; 3203 TemplateArgsTy ToTemplArgs; 3204 std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr; 3205 void *InsertPos = nullptr; 3206 auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos); 3207 return FoundSpec; 3208 } 3209 3210 Error ASTNodeImporter::ImportFunctionDeclBody(FunctionDecl *FromFD, 3211 FunctionDecl *ToFD) { 3212 if (Stmt *FromBody = FromFD->getBody()) { 3213 if (ExpectedStmt ToBodyOrErr = import(FromBody)) 3214 ToFD->setBody(*ToBodyOrErr); 3215 else 3216 return ToBodyOrErr.takeError(); 3217 } 3218 return Error::success(); 3219 } 3220 3221 // Returns true if the given D has a DeclContext up to the TranslationUnitDecl 3222 // which is equal to the given DC. 3223 static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) { 3224 const DeclContext *DCi = D->getDeclContext(); 3225 while (DCi != D->getTranslationUnitDecl()) { 3226 if (DCi == DC) 3227 return true; 3228 DCi = DCi->getParent(); 3229 } 3230 return false; 3231 } 3232 3233 static bool hasTypeDeclaredInsideFunction(QualType T, const FunctionDecl *FD) { 3234 if (T.isNull()) 3235 return false; 3236 if (const auto *RecordT = T->getAs<RecordType>()) { 3237 const RecordDecl *RD = RecordT->getDecl(); 3238 assert(RD); 3239 if (isAncestorDeclContextOf(FD, RD)) { 3240 assert(RD->getLexicalDeclContext() == RD->getDeclContext()); 3241 return true; 3242 } 3243 if (const auto *RDTempl = dyn_cast<ClassTemplateSpecializationDecl>(RD)) 3244 return llvm::count_if(RDTempl->getTemplateArgs().asArray(), 3245 [FD](const TemplateArgument &Arg) { 3246 return hasTypeDeclaredInsideFunction( 3247 Arg.getAsType(), FD); 3248 }); 3249 } 3250 return false; 3251 } 3252 3253 bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) { 3254 QualType FromTy = D->getType(); 3255 const auto *FromFPT = FromTy->getAs<FunctionProtoType>(); 3256 assert(FromFPT && "Must be called on FunctionProtoType"); 3257 if (const AutoType *AutoT = FromFPT->getReturnType()->getContainedAutoType()) 3258 return hasTypeDeclaredInsideFunction(AutoT->getDeducedType(), D); 3259 if (const auto *TypedefT = FromFPT->getReturnType()->getAs<TypedefType>()) { 3260 const TypedefNameDecl *TD = TypedefT->getDecl(); 3261 assert(TD); 3262 if (isAncestorDeclContextOf(D, TD)) { 3263 assert(TD->getLexicalDeclContext() == TD->getDeclContext()); 3264 return true; 3265 } 3266 } 3267 return false; 3268 } 3269 3270 ExplicitSpecifier 3271 ASTNodeImporter::importExplicitSpecifier(Error &Err, ExplicitSpecifier ESpec) { 3272 Expr *ExplicitExpr = ESpec.getExpr(); 3273 if (ExplicitExpr) 3274 ExplicitExpr = importChecked(Err, ESpec.getExpr()); 3275 return ExplicitSpecifier(ExplicitExpr, ESpec.getKind()); 3276 } 3277 3278 ExpectedDecl ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) { 3279 3280 SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D); 3281 auto RedeclIt = Redecls.begin(); 3282 // Import the first part of the decl chain. I.e. import all previous 3283 // declarations starting from the canonical decl. 3284 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) { 3285 ExpectedDecl ToRedeclOrErr = import(*RedeclIt); 3286 if (!ToRedeclOrErr) 3287 return ToRedeclOrErr.takeError(); 3288 } 3289 assert(*RedeclIt == D); 3290 3291 // Import the major distinguishing characteristics of this function. 3292 DeclContext *DC, *LexicalDC; 3293 DeclarationName Name; 3294 SourceLocation Loc; 3295 NamedDecl *ToD; 3296 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 3297 return std::move(Err); 3298 if (ToD) 3299 return ToD; 3300 3301 FunctionDecl *FoundByLookup = nullptr; 3302 FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate(); 3303 3304 // If this is a function template specialization, then try to find the same 3305 // existing specialization in the "to" context. The lookup below will not 3306 // find any specialization, but would find the primary template; thus, we 3307 // have to skip normal lookup in case of specializations. 3308 // FIXME handle member function templates (TK_MemberSpecialization) similarly? 3309 if (D->getTemplatedKind() == 3310 FunctionDecl::TK_FunctionTemplateSpecialization) { 3311 auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D); 3312 if (!FoundFunctionOrErr) 3313 return FoundFunctionOrErr.takeError(); 3314 if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) { 3315 if (Decl *Def = FindAndMapDefinition(D, FoundFunction)) 3316 return Def; 3317 FoundByLookup = FoundFunction; 3318 } 3319 } 3320 // Try to find a function in our own ("to") context with the same name, same 3321 // type, and in the same context as the function we're importing. 3322 else if (!LexicalDC->isFunctionOrMethod()) { 3323 SmallVector<NamedDecl *, 4> ConflictingDecls; 3324 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend; 3325 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 3326 for (auto *FoundDecl : FoundDecls) { 3327 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 3328 continue; 3329 3330 if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) { 3331 if (!hasSameVisibilityContextAndLinkage(FoundFunction, D)) 3332 continue; 3333 3334 if (IsStructuralMatch(D, FoundFunction)) { 3335 if (Decl *Def = FindAndMapDefinition(D, FoundFunction)) 3336 return Def; 3337 FoundByLookup = FoundFunction; 3338 break; 3339 } 3340 // FIXME: Check for overloading more carefully, e.g., by boosting 3341 // Sema::IsOverload out to the AST library. 3342 3343 // Function overloading is okay in C++. 3344 if (Importer.getToContext().getLangOpts().CPlusPlus) 3345 continue; 3346 3347 // Complain about inconsistent function types. 3348 Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent) 3349 << Name << D->getType() << FoundFunction->getType(); 3350 Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here) 3351 << FoundFunction->getType(); 3352 ConflictingDecls.push_back(FoundDecl); 3353 } 3354 } 3355 3356 if (!ConflictingDecls.empty()) { 3357 ExpectedName NameOrErr = Importer.HandleNameConflict( 3358 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); 3359 if (NameOrErr) 3360 Name = NameOrErr.get(); 3361 else 3362 return NameOrErr.takeError(); 3363 } 3364 } 3365 3366 // We do not allow more than one in-class declaration of a function. This is 3367 // because AST clients like VTableBuilder asserts on this. VTableBuilder 3368 // assumes there is only one in-class declaration. Building a redecl 3369 // chain would result in more than one in-class declaration for 3370 // overrides (even if they are part of the same redecl chain inside the 3371 // derived class.) 3372 if (FoundByLookup) { 3373 if (isa<CXXMethodDecl>(FoundByLookup)) { 3374 if (D->getLexicalDeclContext() == D->getDeclContext()) { 3375 if (!D->doesThisDeclarationHaveABody()) { 3376 if (FunctionTemplateDecl *DescribedD = 3377 D->getDescribedFunctionTemplate()) { 3378 // Handle a "templated" function together with its described 3379 // template. This avoids need for a similar check at import of the 3380 // described template. 3381 assert(FoundByLookup->getDescribedFunctionTemplate() && 3382 "Templated function mapped to non-templated?"); 3383 Importer.MapImported(DescribedD, 3384 FoundByLookup->getDescribedFunctionTemplate()); 3385 } 3386 return Importer.MapImported(D, FoundByLookup); 3387 } else { 3388 // Let's continue and build up the redecl chain in this case. 3389 // FIXME Merge the functions into one decl. 3390 } 3391 } 3392 } 3393 } 3394 3395 DeclarationNameInfo NameInfo(Name, Loc); 3396 // Import additional name location/type info. 3397 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo)) 3398 return std::move(Err); 3399 3400 QualType FromTy = D->getType(); 3401 TypeSourceInfo *FromTSI = D->getTypeSourceInfo(); 3402 // Set to true if we do not import the type of the function as is. There are 3403 // cases when the original type would result in an infinite recursion during 3404 // the import. To avoid an infinite recursion when importing, we create the 3405 // FunctionDecl with a simplified function type and update it only after the 3406 // relevant AST nodes are already imported. 3407 // The type is related to TypeSourceInfo (it references the type), so we must 3408 // do the same with TypeSourceInfo. 3409 bool UsedDifferentProtoType = false; 3410 if (const auto *FromFPT = FromTy->getAs<FunctionProtoType>()) { 3411 QualType FromReturnTy = FromFPT->getReturnType(); 3412 // Functions with auto return type may define a struct inside their body 3413 // and the return type could refer to that struct. 3414 // E.g.: auto foo() { struct X{}; return X(); } 3415 // To avoid an infinite recursion when importing, create the FunctionDecl 3416 // with a simplified return type. 3417 if (hasAutoReturnTypeDeclaredInside(D)) { 3418 FromReturnTy = Importer.getFromContext().VoidTy; 3419 UsedDifferentProtoType = true; 3420 } 3421 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo(); 3422 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the 3423 // FunctionDecl that we are importing the FunctionProtoType for. 3424 // To avoid an infinite recursion when importing, create the FunctionDecl 3425 // with a simplified function type. 3426 if (FromEPI.ExceptionSpec.SourceDecl || 3427 FromEPI.ExceptionSpec.SourceTemplate || 3428 FromEPI.ExceptionSpec.NoexceptExpr) { 3429 FunctionProtoType::ExtProtoInfo DefaultEPI; 3430 FromEPI = DefaultEPI; 3431 UsedDifferentProtoType = true; 3432 } 3433 FromTy = Importer.getFromContext().getFunctionType( 3434 FromReturnTy, FromFPT->getParamTypes(), FromEPI); 3435 FromTSI = Importer.getFromContext().getTrivialTypeSourceInfo( 3436 FromTy, D->getBeginLoc()); 3437 } 3438 3439 Error Err = Error::success(); 3440 auto T = importChecked(Err, FromTy); 3441 auto TInfo = importChecked(Err, FromTSI); 3442 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart()); 3443 auto ToEndLoc = importChecked(Err, D->getEndLoc()); 3444 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 3445 auto TrailingRequiresClause = 3446 importChecked(Err, D->getTrailingRequiresClause()); 3447 if (Err) 3448 return std::move(Err); 3449 3450 // Import the function parameters. 3451 SmallVector<ParmVarDecl *, 8> Parameters; 3452 for (auto P : D->parameters()) { 3453 if (Expected<ParmVarDecl *> ToPOrErr = import(P)) 3454 Parameters.push_back(*ToPOrErr); 3455 else 3456 return ToPOrErr.takeError(); 3457 } 3458 3459 // Create the imported function. 3460 FunctionDecl *ToFunction = nullptr; 3461 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) { 3462 ExplicitSpecifier ESpec = 3463 importExplicitSpecifier(Err, FromConstructor->getExplicitSpecifier()); 3464 if (Err) 3465 return std::move(Err); 3466 auto ToInheritedConstructor = InheritedConstructor(); 3467 if (FromConstructor->isInheritingConstructor()) { 3468 Expected<InheritedConstructor> ImportedInheritedCtor = 3469 import(FromConstructor->getInheritedConstructor()); 3470 if (!ImportedInheritedCtor) 3471 return ImportedInheritedCtor.takeError(); 3472 ToInheritedConstructor = *ImportedInheritedCtor; 3473 } 3474 if (GetImportedOrCreateDecl<CXXConstructorDecl>( 3475 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), 3476 ToInnerLocStart, NameInfo, T, TInfo, ESpec, D->UsesFPIntrin(), 3477 D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind(), 3478 ToInheritedConstructor, TrailingRequiresClause)) 3479 return ToFunction; 3480 } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) { 3481 3482 Error Err = Error::success(); 3483 auto ToOperatorDelete = importChecked( 3484 Err, const_cast<FunctionDecl *>(FromDtor->getOperatorDelete())); 3485 auto ToThisArg = importChecked(Err, FromDtor->getOperatorDeleteThisArg()); 3486 if (Err) 3487 return std::move(Err); 3488 3489 if (GetImportedOrCreateDecl<CXXDestructorDecl>( 3490 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), 3491 ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(), 3492 D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind(), 3493 TrailingRequiresClause)) 3494 return ToFunction; 3495 3496 CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction); 3497 3498 ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg); 3499 } else if (CXXConversionDecl *FromConversion = 3500 dyn_cast<CXXConversionDecl>(D)) { 3501 ExplicitSpecifier ESpec = 3502 importExplicitSpecifier(Err, FromConversion->getExplicitSpecifier()); 3503 if (Err) 3504 return std::move(Err); 3505 if (GetImportedOrCreateDecl<CXXConversionDecl>( 3506 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), 3507 ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(), 3508 D->isInlineSpecified(), ESpec, D->getConstexprKind(), 3509 SourceLocation(), TrailingRequiresClause)) 3510 return ToFunction; 3511 } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) { 3512 if (GetImportedOrCreateDecl<CXXMethodDecl>( 3513 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), 3514 ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(), 3515 Method->UsesFPIntrin(), Method->isInlineSpecified(), 3516 D->getConstexprKind(), SourceLocation(), TrailingRequiresClause)) 3517 return ToFunction; 3518 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(D)) { 3519 ExplicitSpecifier ESpec = 3520 importExplicitSpecifier(Err, Guide->getExplicitSpecifier()); 3521 CXXConstructorDecl *Ctor = 3522 importChecked(Err, Guide->getCorrespondingConstructor()); 3523 if (Err) 3524 return std::move(Err); 3525 if (GetImportedOrCreateDecl<CXXDeductionGuideDecl>( 3526 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, ESpec, 3527 NameInfo, T, TInfo, ToEndLoc, Ctor)) 3528 return ToFunction; 3529 cast<CXXDeductionGuideDecl>(ToFunction) 3530 ->setIsCopyDeductionCandidate(Guide->isCopyDeductionCandidate()); 3531 } else { 3532 if (GetImportedOrCreateDecl( 3533 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, 3534 NameInfo, T, TInfo, D->getStorageClass(), D->UsesFPIntrin(), 3535 D->isInlineSpecified(), D->hasWrittenPrototype(), 3536 D->getConstexprKind(), TrailingRequiresClause)) 3537 return ToFunction; 3538 } 3539 3540 // Connect the redecl chain. 3541 if (FoundByLookup) { 3542 auto *Recent = const_cast<FunctionDecl *>( 3543 FoundByLookup->getMostRecentDecl()); 3544 ToFunction->setPreviousDecl(Recent); 3545 // FIXME Probably we should merge exception specifications. E.g. In the 3546 // "To" context the existing function may have exception specification with 3547 // noexcept-unevaluated, while the newly imported function may have an 3548 // evaluated noexcept. A call to adjustExceptionSpec() on the imported 3549 // decl and its redeclarations may be required. 3550 } 3551 3552 ToFunction->setQualifierInfo(ToQualifierLoc); 3553 ToFunction->setAccess(D->getAccess()); 3554 ToFunction->setLexicalDeclContext(LexicalDC); 3555 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten()); 3556 ToFunction->setTrivial(D->isTrivial()); 3557 ToFunction->setPure(D->isPure()); 3558 ToFunction->setDefaulted(D->isDefaulted()); 3559 ToFunction->setExplicitlyDefaulted(D->isExplicitlyDefaulted()); 3560 ToFunction->setDeletedAsWritten(D->isDeletedAsWritten()); 3561 ToFunction->setRangeEnd(ToEndLoc); 3562 3563 // Set the parameters. 3564 for (auto *Param : Parameters) { 3565 Param->setOwningFunction(ToFunction); 3566 ToFunction->addDeclInternal(Param); 3567 if (ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable()) 3568 LT->update(Param, Importer.getToContext().getTranslationUnitDecl()); 3569 } 3570 ToFunction->setParams(Parameters); 3571 3572 // We need to complete creation of FunctionProtoTypeLoc manually with setting 3573 // params it refers to. 3574 if (TInfo) { 3575 if (auto ProtoLoc = 3576 TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) { 3577 for (unsigned I = 0, N = Parameters.size(); I != N; ++I) 3578 ProtoLoc.setParam(I, Parameters[I]); 3579 } 3580 } 3581 3582 // Import the describing template function, if any. 3583 if (FromFT) { 3584 auto ToFTOrErr = import(FromFT); 3585 if (!ToFTOrErr) 3586 return ToFTOrErr.takeError(); 3587 } 3588 3589 // Import Ctor initializers. 3590 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) { 3591 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) { 3592 SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers); 3593 // Import first, then allocate memory and copy if there was no error. 3594 if (Error Err = ImportContainerChecked( 3595 FromConstructor->inits(), CtorInitializers)) 3596 return std::move(Err); 3597 auto **Memory = 3598 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers]; 3599 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory); 3600 auto *ToCtor = cast<CXXConstructorDecl>(ToFunction); 3601 ToCtor->setCtorInitializers(Memory); 3602 ToCtor->setNumCtorInitializers(NumInitializers); 3603 } 3604 } 3605 3606 if (D->doesThisDeclarationHaveABody()) { 3607 Error Err = ImportFunctionDeclBody(D, ToFunction); 3608 3609 if (Err) 3610 return std::move(Err); 3611 } 3612 3613 // Import and set the original type in case we used another type. 3614 if (UsedDifferentProtoType) { 3615 if (ExpectedType TyOrErr = import(D->getType())) 3616 ToFunction->setType(*TyOrErr); 3617 else 3618 return TyOrErr.takeError(); 3619 if (Expected<TypeSourceInfo *> TSIOrErr = import(D->getTypeSourceInfo())) 3620 ToFunction->setTypeSourceInfo(*TSIOrErr); 3621 else 3622 return TSIOrErr.takeError(); 3623 } 3624 3625 // FIXME: Other bits to merge? 3626 3627 // If it is a template, import all related things. 3628 if (Error Err = ImportTemplateInformation(D, ToFunction)) 3629 return std::move(Err); 3630 3631 addDeclToContexts(D, ToFunction); 3632 3633 if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D)) 3634 if (Error Err = ImportOverriddenMethods(cast<CXXMethodDecl>(ToFunction), 3635 FromCXXMethod)) 3636 return std::move(Err); 3637 3638 // Import the rest of the chain. I.e. import all subsequent declarations. 3639 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) { 3640 ExpectedDecl ToRedeclOrErr = import(*RedeclIt); 3641 if (!ToRedeclOrErr) 3642 return ToRedeclOrErr.takeError(); 3643 } 3644 3645 return ToFunction; 3646 } 3647 3648 ExpectedDecl ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) { 3649 return VisitFunctionDecl(D); 3650 } 3651 3652 ExpectedDecl ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 3653 return VisitCXXMethodDecl(D); 3654 } 3655 3656 ExpectedDecl ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 3657 return VisitCXXMethodDecl(D); 3658 } 3659 3660 ExpectedDecl ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) { 3661 return VisitCXXMethodDecl(D); 3662 } 3663 3664 ExpectedDecl 3665 ASTNodeImporter::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) { 3666 return VisitFunctionDecl(D); 3667 } 3668 3669 ExpectedDecl ASTNodeImporter::VisitFieldDecl(FieldDecl *D) { 3670 // Import the major distinguishing characteristics of a variable. 3671 DeclContext *DC, *LexicalDC; 3672 DeclarationName Name; 3673 SourceLocation Loc; 3674 NamedDecl *ToD; 3675 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 3676 return std::move(Err); 3677 if (ToD) 3678 return ToD; 3679 3680 // Determine whether we've already imported this field. 3681 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 3682 for (auto *FoundDecl : FoundDecls) { 3683 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) { 3684 // For anonymous fields, match up by index. 3685 if (!Name && 3686 ASTImporter::getFieldIndex(D) != 3687 ASTImporter::getFieldIndex(FoundField)) 3688 continue; 3689 3690 if (Importer.IsStructurallyEquivalent(D->getType(), 3691 FoundField->getType())) { 3692 Importer.MapImported(D, FoundField); 3693 // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the 3694 // initializer of a FieldDecl might not had been instantiated in the 3695 // "To" context. However, the "From" context might instantiated that, 3696 // thus we have to merge that. 3697 // Note: `hasInClassInitializer()` is not the same as non-null 3698 // `getInClassInitializer()` value. 3699 if (Expr *FromInitializer = D->getInClassInitializer()) { 3700 if (ExpectedExpr ToInitializerOrErr = import(FromInitializer)) { 3701 // Import of the FromInitializer may result in the setting of 3702 // InClassInitializer. If not, set it here. 3703 assert(FoundField->hasInClassInitializer() && 3704 "Field should have an in-class initializer if it has an " 3705 "expression for it."); 3706 if (!FoundField->getInClassInitializer()) 3707 FoundField->setInClassInitializer(*ToInitializerOrErr); 3708 } else { 3709 return ToInitializerOrErr.takeError(); 3710 } 3711 } 3712 return FoundField; 3713 } 3714 3715 // FIXME: Why is this case not handled with calling HandleNameConflict? 3716 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent) 3717 << Name << D->getType() << FoundField->getType(); 3718 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here) 3719 << FoundField->getType(); 3720 3721 return make_error<ASTImportError>(ASTImportError::NameConflict); 3722 } 3723 } 3724 3725 Error Err = Error::success(); 3726 auto ToType = importChecked(Err, D->getType()); 3727 auto ToTInfo = importChecked(Err, D->getTypeSourceInfo()); 3728 auto ToBitWidth = importChecked(Err, D->getBitWidth()); 3729 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart()); 3730 auto ToInitializer = importChecked(Err, D->getInClassInitializer()); 3731 if (Err) 3732 return std::move(Err); 3733 const Type *ToCapturedVLAType = nullptr; 3734 if (Error Err = Importer.importInto( 3735 ToCapturedVLAType, cast_or_null<Type>(D->getCapturedVLAType()))) 3736 return std::move(Err); 3737 3738 FieldDecl *ToField; 3739 if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC, 3740 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(), 3741 ToType, ToTInfo, ToBitWidth, D->isMutable(), 3742 D->getInClassInitStyle())) 3743 return ToField; 3744 3745 ToField->setAccess(D->getAccess()); 3746 ToField->setLexicalDeclContext(LexicalDC); 3747 if (ToInitializer) 3748 ToField->setInClassInitializer(ToInitializer); 3749 ToField->setImplicit(D->isImplicit()); 3750 if (ToCapturedVLAType) 3751 ToField->setCapturedVLAType(cast<VariableArrayType>(ToCapturedVLAType)); 3752 LexicalDC->addDeclInternal(ToField); 3753 return ToField; 3754 } 3755 3756 ExpectedDecl ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) { 3757 // Import the major distinguishing characteristics of a variable. 3758 DeclContext *DC, *LexicalDC; 3759 DeclarationName Name; 3760 SourceLocation Loc; 3761 NamedDecl *ToD; 3762 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 3763 return std::move(Err); 3764 if (ToD) 3765 return ToD; 3766 3767 // Determine whether we've already imported this field. 3768 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 3769 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { 3770 if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) { 3771 // For anonymous indirect fields, match up by index. 3772 if (!Name && 3773 ASTImporter::getFieldIndex(D) != 3774 ASTImporter::getFieldIndex(FoundField)) 3775 continue; 3776 3777 if (Importer.IsStructurallyEquivalent(D->getType(), 3778 FoundField->getType(), 3779 !Name.isEmpty())) { 3780 Importer.MapImported(D, FoundField); 3781 return FoundField; 3782 } 3783 3784 // If there are more anonymous fields to check, continue. 3785 if (!Name && I < N-1) 3786 continue; 3787 3788 // FIXME: Why is this case not handled with calling HandleNameConflict? 3789 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent) 3790 << Name << D->getType() << FoundField->getType(); 3791 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here) 3792 << FoundField->getType(); 3793 3794 return make_error<ASTImportError>(ASTImportError::NameConflict); 3795 } 3796 } 3797 3798 // Import the type. 3799 auto TypeOrErr = import(D->getType()); 3800 if (!TypeOrErr) 3801 return TypeOrErr.takeError(); 3802 3803 auto **NamedChain = 3804 new (Importer.getToContext()) NamedDecl*[D->getChainingSize()]; 3805 3806 unsigned i = 0; 3807 for (auto *PI : D->chain()) 3808 if (Expected<NamedDecl *> ToD = import(PI)) 3809 NamedChain[i++] = *ToD; 3810 else 3811 return ToD.takeError(); 3812 3813 llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()}; 3814 IndirectFieldDecl *ToIndirectField; 3815 if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC, 3816 Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH)) 3817 // FIXME here we leak `NamedChain` which is allocated before 3818 return ToIndirectField; 3819 3820 ToIndirectField->setAccess(D->getAccess()); 3821 ToIndirectField->setLexicalDeclContext(LexicalDC); 3822 LexicalDC->addDeclInternal(ToIndirectField); 3823 return ToIndirectField; 3824 } 3825 3826 /// Used as return type of getFriendCountAndPosition. 3827 struct FriendCountAndPosition { 3828 /// Number of similar looking friends. 3829 unsigned int TotalCount; 3830 /// Index of the specific FriendDecl. 3831 unsigned int IndexOfDecl; 3832 }; 3833 3834 template <class T> 3835 static FriendCountAndPosition getFriendCountAndPosition( 3836 const FriendDecl *FD, 3837 llvm::function_ref<T(const FriendDecl *)> GetCanTypeOrDecl) { 3838 unsigned int FriendCount = 0; 3839 llvm::Optional<unsigned int> FriendPosition; 3840 const auto *RD = cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 3841 3842 T TypeOrDecl = GetCanTypeOrDecl(FD); 3843 3844 for (const FriendDecl *FoundFriend : RD->friends()) { 3845 if (FoundFriend == FD) { 3846 FriendPosition = FriendCount; 3847 ++FriendCount; 3848 } else if (!FoundFriend->getFriendDecl() == !FD->getFriendDecl() && 3849 GetCanTypeOrDecl(FoundFriend) == TypeOrDecl) { 3850 ++FriendCount; 3851 } 3852 } 3853 3854 assert(FriendPosition && "Friend decl not found in own parent."); 3855 3856 return {FriendCount, *FriendPosition}; 3857 } 3858 3859 static FriendCountAndPosition getFriendCountAndPosition(const FriendDecl *FD) { 3860 if (FD->getFriendType()) 3861 return getFriendCountAndPosition<QualType>(FD, [](const FriendDecl *F) { 3862 if (TypeSourceInfo *TSI = F->getFriendType()) 3863 return TSI->getType().getCanonicalType(); 3864 llvm_unreachable("Wrong friend object type."); 3865 }); 3866 else 3867 return getFriendCountAndPosition<Decl *>(FD, [](const FriendDecl *F) { 3868 if (Decl *D = F->getFriendDecl()) 3869 return D->getCanonicalDecl(); 3870 llvm_unreachable("Wrong friend object type."); 3871 }); 3872 } 3873 3874 ExpectedDecl ASTNodeImporter::VisitFriendDecl(FriendDecl *D) { 3875 // Import the major distinguishing characteristics of a declaration. 3876 DeclContext *DC, *LexicalDC; 3877 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 3878 return std::move(Err); 3879 3880 // Determine whether we've already imported this decl. 3881 // FriendDecl is not a NamedDecl so we cannot use lookup. 3882 // We try to maintain order and count of redundant friend declarations. 3883 const auto *RD = cast<CXXRecordDecl>(DC); 3884 FriendDecl *ImportedFriend = RD->getFirstFriend(); 3885 SmallVector<FriendDecl *, 2> ImportedEquivalentFriends; 3886 3887 while (ImportedFriend) { 3888 bool Match = false; 3889 if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) { 3890 Match = 3891 IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(), 3892 /*Complain=*/false); 3893 } else if (D->getFriendType() && ImportedFriend->getFriendType()) { 3894 Match = Importer.IsStructurallyEquivalent( 3895 D->getFriendType()->getType(), 3896 ImportedFriend->getFriendType()->getType(), /*Complain=*/false); 3897 } 3898 if (Match) 3899 ImportedEquivalentFriends.push_back(ImportedFriend); 3900 3901 ImportedFriend = ImportedFriend->getNextFriend(); 3902 } 3903 FriendCountAndPosition CountAndPosition = getFriendCountAndPosition(D); 3904 3905 assert(ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount && 3906 "Class with non-matching friends is imported, ODR check wrong?"); 3907 if (ImportedEquivalentFriends.size() == CountAndPosition.TotalCount) 3908 return Importer.MapImported( 3909 D, ImportedEquivalentFriends[CountAndPosition.IndexOfDecl]); 3910 3911 // Not found. Create it. 3912 // The declarations will be put into order later by ImportDeclContext. 3913 FriendDecl::FriendUnion ToFU; 3914 if (NamedDecl *FriendD = D->getFriendDecl()) { 3915 NamedDecl *ToFriendD; 3916 if (Error Err = importInto(ToFriendD, FriendD)) 3917 return std::move(Err); 3918 3919 if (FriendD->getFriendObjectKind() != Decl::FOK_None && 3920 !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator))) 3921 ToFriendD->setObjectOfFriendDecl(false); 3922 3923 ToFU = ToFriendD; 3924 } else { // The friend is a type, not a decl. 3925 if (auto TSIOrErr = import(D->getFriendType())) 3926 ToFU = *TSIOrErr; 3927 else 3928 return TSIOrErr.takeError(); 3929 } 3930 3931 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists); 3932 auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>(); 3933 for (unsigned I = 0; I < D->NumTPLists; I++) { 3934 if (auto ListOrErr = import(FromTPLists[I])) 3935 ToTPLists[I] = *ListOrErr; 3936 else 3937 return ListOrErr.takeError(); 3938 } 3939 3940 auto LocationOrErr = import(D->getLocation()); 3941 if (!LocationOrErr) 3942 return LocationOrErr.takeError(); 3943 auto FriendLocOrErr = import(D->getFriendLoc()); 3944 if (!FriendLocOrErr) 3945 return FriendLocOrErr.takeError(); 3946 3947 FriendDecl *FrD; 3948 if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC, 3949 *LocationOrErr, ToFU, 3950 *FriendLocOrErr, ToTPLists)) 3951 return FrD; 3952 3953 FrD->setAccess(D->getAccess()); 3954 FrD->setLexicalDeclContext(LexicalDC); 3955 LexicalDC->addDeclInternal(FrD); 3956 return FrD; 3957 } 3958 3959 ExpectedDecl ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) { 3960 // Import the major distinguishing characteristics of an ivar. 3961 DeclContext *DC, *LexicalDC; 3962 DeclarationName Name; 3963 SourceLocation Loc; 3964 NamedDecl *ToD; 3965 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 3966 return std::move(Err); 3967 if (ToD) 3968 return ToD; 3969 3970 // Determine whether we've already imported this ivar 3971 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 3972 for (auto *FoundDecl : FoundDecls) { 3973 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) { 3974 if (Importer.IsStructurallyEquivalent(D->getType(), 3975 FoundIvar->getType())) { 3976 Importer.MapImported(D, FoundIvar); 3977 return FoundIvar; 3978 } 3979 3980 Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent) 3981 << Name << D->getType() << FoundIvar->getType(); 3982 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here) 3983 << FoundIvar->getType(); 3984 3985 return make_error<ASTImportError>(ASTImportError::NameConflict); 3986 } 3987 } 3988 3989 Error Err = Error::success(); 3990 auto ToType = importChecked(Err, D->getType()); 3991 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo()); 3992 auto ToBitWidth = importChecked(Err, D->getBitWidth()); 3993 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart()); 3994 if (Err) 3995 return std::move(Err); 3996 3997 ObjCIvarDecl *ToIvar; 3998 if (GetImportedOrCreateDecl( 3999 ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC), 4000 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(), 4001 ToType, ToTypeSourceInfo, 4002 D->getAccessControl(),ToBitWidth, D->getSynthesize())) 4003 return ToIvar; 4004 4005 ToIvar->setLexicalDeclContext(LexicalDC); 4006 LexicalDC->addDeclInternal(ToIvar); 4007 return ToIvar; 4008 } 4009 4010 ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) { 4011 4012 SmallVector<Decl*, 2> Redecls = getCanonicalForwardRedeclChain(D); 4013 auto RedeclIt = Redecls.begin(); 4014 // Import the first part of the decl chain. I.e. import all previous 4015 // declarations starting from the canonical decl. 4016 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) { 4017 ExpectedDecl RedeclOrErr = import(*RedeclIt); 4018 if (!RedeclOrErr) 4019 return RedeclOrErr.takeError(); 4020 } 4021 assert(*RedeclIt == D); 4022 4023 // Import the major distinguishing characteristics of a variable. 4024 DeclContext *DC, *LexicalDC; 4025 DeclarationName Name; 4026 SourceLocation Loc; 4027 NamedDecl *ToD; 4028 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4029 return std::move(Err); 4030 if (ToD) 4031 return ToD; 4032 4033 // Try to find a variable in our own ("to") context with the same name and 4034 // in the same context as the variable we're importing. 4035 VarDecl *FoundByLookup = nullptr; 4036 if (D->isFileVarDecl()) { 4037 SmallVector<NamedDecl *, 4> ConflictingDecls; 4038 unsigned IDNS = Decl::IDNS_Ordinary; 4039 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 4040 for (auto *FoundDecl : FoundDecls) { 4041 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 4042 continue; 4043 4044 if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) { 4045 if (!hasSameVisibilityContextAndLinkage(FoundVar, D)) 4046 continue; 4047 if (Importer.IsStructurallyEquivalent(D->getType(), 4048 FoundVar->getType())) { 4049 4050 // The VarDecl in the "From" context has a definition, but in the 4051 // "To" context we already have a definition. 4052 VarDecl *FoundDef = FoundVar->getDefinition(); 4053 if (D->isThisDeclarationADefinition() && FoundDef) 4054 // FIXME Check for ODR error if the two definitions have 4055 // different initializers? 4056 return Importer.MapImported(D, FoundDef); 4057 4058 // The VarDecl in the "From" context has an initializer, but in the 4059 // "To" context we already have an initializer. 4060 const VarDecl *FoundDInit = nullptr; 4061 if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit)) 4062 // FIXME Diagnose ODR error if the two initializers are different? 4063 return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit)); 4064 4065 FoundByLookup = FoundVar; 4066 break; 4067 } 4068 4069 const ArrayType *FoundArray 4070 = Importer.getToContext().getAsArrayType(FoundVar->getType()); 4071 const ArrayType *TArray 4072 = Importer.getToContext().getAsArrayType(D->getType()); 4073 if (FoundArray && TArray) { 4074 if (isa<IncompleteArrayType>(FoundArray) && 4075 isa<ConstantArrayType>(TArray)) { 4076 // Import the type. 4077 if (auto TyOrErr = import(D->getType())) 4078 FoundVar->setType(*TyOrErr); 4079 else 4080 return TyOrErr.takeError(); 4081 4082 FoundByLookup = FoundVar; 4083 break; 4084 } else if (isa<IncompleteArrayType>(TArray) && 4085 isa<ConstantArrayType>(FoundArray)) { 4086 FoundByLookup = FoundVar; 4087 break; 4088 } 4089 } 4090 4091 Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent) 4092 << Name << D->getType() << FoundVar->getType(); 4093 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here) 4094 << FoundVar->getType(); 4095 ConflictingDecls.push_back(FoundDecl); 4096 } 4097 } 4098 4099 if (!ConflictingDecls.empty()) { 4100 ExpectedName NameOrErr = Importer.HandleNameConflict( 4101 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); 4102 if (NameOrErr) 4103 Name = NameOrErr.get(); 4104 else 4105 return NameOrErr.takeError(); 4106 } 4107 } 4108 4109 Error Err = Error::success(); 4110 auto ToType = importChecked(Err, D->getType()); 4111 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo()); 4112 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart()); 4113 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 4114 if (Err) 4115 return std::move(Err); 4116 4117 VarDecl *ToVar; 4118 if (auto *FromDecomp = dyn_cast<DecompositionDecl>(D)) { 4119 SmallVector<BindingDecl *> Bindings(FromDecomp->bindings().size()); 4120 if (Error Err = 4121 ImportArrayChecked(FromDecomp->bindings(), Bindings.begin())) 4122 return std::move(Err); 4123 DecompositionDecl *ToDecomp; 4124 if (GetImportedOrCreateDecl( 4125 ToDecomp, FromDecomp, Importer.getToContext(), DC, ToInnerLocStart, 4126 Loc, ToType, ToTypeSourceInfo, D->getStorageClass(), Bindings)) 4127 return ToDecomp; 4128 ToVar = ToDecomp; 4129 } else { 4130 // Create the imported variable. 4131 if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC, 4132 ToInnerLocStart, Loc, 4133 Name.getAsIdentifierInfo(), ToType, 4134 ToTypeSourceInfo, D->getStorageClass())) 4135 return ToVar; 4136 } 4137 4138 ToVar->setTSCSpec(D->getTSCSpec()); 4139 ToVar->setQualifierInfo(ToQualifierLoc); 4140 ToVar->setAccess(D->getAccess()); 4141 ToVar->setLexicalDeclContext(LexicalDC); 4142 4143 if (FoundByLookup) { 4144 auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl()); 4145 ToVar->setPreviousDecl(Recent); 4146 } 4147 4148 // Import the described template, if any. 4149 if (D->getDescribedVarTemplate()) { 4150 auto ToVTOrErr = import(D->getDescribedVarTemplate()); 4151 if (!ToVTOrErr) 4152 return ToVTOrErr.takeError(); 4153 } 4154 4155 if (Error Err = ImportInitializer(D, ToVar)) 4156 return std::move(Err); 4157 4158 if (D->isConstexpr()) 4159 ToVar->setConstexpr(true); 4160 4161 addDeclToContexts(D, ToVar); 4162 4163 // Import the rest of the chain. I.e. import all subsequent declarations. 4164 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) { 4165 ExpectedDecl RedeclOrErr = import(*RedeclIt); 4166 if (!RedeclOrErr) 4167 return RedeclOrErr.takeError(); 4168 } 4169 4170 return ToVar; 4171 } 4172 4173 ExpectedDecl ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) { 4174 // Parameters are created in the translation unit's context, then moved 4175 // into the function declaration's context afterward. 4176 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl(); 4177 4178 Error Err = Error::success(); 4179 auto ToDeclName = importChecked(Err, D->getDeclName()); 4180 auto ToLocation = importChecked(Err, D->getLocation()); 4181 auto ToType = importChecked(Err, D->getType()); 4182 if (Err) 4183 return std::move(Err); 4184 4185 // Create the imported parameter. 4186 ImplicitParamDecl *ToParm = nullptr; 4187 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC, 4188 ToLocation, ToDeclName.getAsIdentifierInfo(), 4189 ToType, D->getParameterKind())) 4190 return ToParm; 4191 return ToParm; 4192 } 4193 4194 Error ASTNodeImporter::ImportDefaultArgOfParmVarDecl( 4195 const ParmVarDecl *FromParam, ParmVarDecl *ToParam) { 4196 ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg()); 4197 ToParam->setKNRPromoted(FromParam->isKNRPromoted()); 4198 4199 if (FromParam->hasUninstantiatedDefaultArg()) { 4200 if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg())) 4201 ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr); 4202 else 4203 return ToDefArgOrErr.takeError(); 4204 } else if (FromParam->hasUnparsedDefaultArg()) { 4205 ToParam->setUnparsedDefaultArg(); 4206 } else if (FromParam->hasDefaultArg()) { 4207 if (auto ToDefArgOrErr = import(FromParam->getDefaultArg())) 4208 ToParam->setDefaultArg(*ToDefArgOrErr); 4209 else 4210 return ToDefArgOrErr.takeError(); 4211 } 4212 4213 return Error::success(); 4214 } 4215 4216 Expected<InheritedConstructor> 4217 ASTNodeImporter::ImportInheritedConstructor(const InheritedConstructor &From) { 4218 Error Err = Error::success(); 4219 CXXConstructorDecl *ToBaseCtor = importChecked(Err, From.getConstructor()); 4220 ConstructorUsingShadowDecl *ToShadow = 4221 importChecked(Err, From.getShadowDecl()); 4222 if (Err) 4223 return std::move(Err); 4224 return InheritedConstructor(ToShadow, ToBaseCtor); 4225 } 4226 4227 ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) { 4228 // Parameters are created in the translation unit's context, then moved 4229 // into the function declaration's context afterward. 4230 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl(); 4231 4232 Error Err = Error::success(); 4233 auto ToDeclName = importChecked(Err, D->getDeclName()); 4234 auto ToLocation = importChecked(Err, D->getLocation()); 4235 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart()); 4236 auto ToType = importChecked(Err, D->getType()); 4237 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo()); 4238 if (Err) 4239 return std::move(Err); 4240 4241 ParmVarDecl *ToParm; 4242 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC, 4243 ToInnerLocStart, ToLocation, 4244 ToDeclName.getAsIdentifierInfo(), ToType, 4245 ToTypeSourceInfo, D->getStorageClass(), 4246 /*DefaultArg*/ nullptr)) 4247 return ToParm; 4248 4249 // Set the default argument. It should be no problem if it was already done. 4250 // Do not import the default expression before GetImportedOrCreateDecl call 4251 // to avoid possible infinite import loop because circular dependency. 4252 if (Error Err = ImportDefaultArgOfParmVarDecl(D, ToParm)) 4253 return std::move(Err); 4254 4255 if (D->isObjCMethodParameter()) { 4256 ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex()); 4257 ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier()); 4258 } else { 4259 ToParm->setScopeInfo(D->getFunctionScopeDepth(), 4260 D->getFunctionScopeIndex()); 4261 } 4262 4263 return ToParm; 4264 } 4265 4266 ExpectedDecl ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) { 4267 // Import the major distinguishing characteristics of a method. 4268 DeclContext *DC, *LexicalDC; 4269 DeclarationName Name; 4270 SourceLocation Loc; 4271 NamedDecl *ToD; 4272 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4273 return std::move(Err); 4274 if (ToD) 4275 return ToD; 4276 4277 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 4278 for (auto *FoundDecl : FoundDecls) { 4279 if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) { 4280 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod()) 4281 continue; 4282 4283 // Check return types. 4284 if (!Importer.IsStructurallyEquivalent(D->getReturnType(), 4285 FoundMethod->getReturnType())) { 4286 Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent) 4287 << D->isInstanceMethod() << Name << D->getReturnType() 4288 << FoundMethod->getReturnType(); 4289 Importer.ToDiag(FoundMethod->getLocation(), 4290 diag::note_odr_objc_method_here) 4291 << D->isInstanceMethod() << Name; 4292 4293 return make_error<ASTImportError>(ASTImportError::NameConflict); 4294 } 4295 4296 // Check the number of parameters. 4297 if (D->param_size() != FoundMethod->param_size()) { 4298 Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent) 4299 << D->isInstanceMethod() << Name 4300 << D->param_size() << FoundMethod->param_size(); 4301 Importer.ToDiag(FoundMethod->getLocation(), 4302 diag::note_odr_objc_method_here) 4303 << D->isInstanceMethod() << Name; 4304 4305 return make_error<ASTImportError>(ASTImportError::NameConflict); 4306 } 4307 4308 // Check parameter types. 4309 for (ObjCMethodDecl::param_iterator P = D->param_begin(), 4310 PEnd = D->param_end(), FoundP = FoundMethod->param_begin(); 4311 P != PEnd; ++P, ++FoundP) { 4312 if (!Importer.IsStructurallyEquivalent((*P)->getType(), 4313 (*FoundP)->getType())) { 4314 Importer.FromDiag((*P)->getLocation(), 4315 diag::warn_odr_objc_method_param_type_inconsistent) 4316 << D->isInstanceMethod() << Name 4317 << (*P)->getType() << (*FoundP)->getType(); 4318 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here) 4319 << (*FoundP)->getType(); 4320 4321 return make_error<ASTImportError>(ASTImportError::NameConflict); 4322 } 4323 } 4324 4325 // Check variadic/non-variadic. 4326 // Check the number of parameters. 4327 if (D->isVariadic() != FoundMethod->isVariadic()) { 4328 Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent) 4329 << D->isInstanceMethod() << Name; 4330 Importer.ToDiag(FoundMethod->getLocation(), 4331 diag::note_odr_objc_method_here) 4332 << D->isInstanceMethod() << Name; 4333 4334 return make_error<ASTImportError>(ASTImportError::NameConflict); 4335 } 4336 4337 // FIXME: Any other bits we need to merge? 4338 return Importer.MapImported(D, FoundMethod); 4339 } 4340 } 4341 4342 Error Err = Error::success(); 4343 auto ToEndLoc = importChecked(Err, D->getEndLoc()); 4344 auto ToReturnType = importChecked(Err, D->getReturnType()); 4345 auto ToReturnTypeSourceInfo = 4346 importChecked(Err, D->getReturnTypeSourceInfo()); 4347 if (Err) 4348 return std::move(Err); 4349 4350 ObjCMethodDecl *ToMethod; 4351 if (GetImportedOrCreateDecl( 4352 ToMethod, D, Importer.getToContext(), Loc, ToEndLoc, 4353 Name.getObjCSelector(), ToReturnType, ToReturnTypeSourceInfo, DC, 4354 D->isInstanceMethod(), D->isVariadic(), D->isPropertyAccessor(), 4355 D->isSynthesizedAccessorStub(), D->isImplicit(), D->isDefined(), 4356 D->getImplementationControl(), D->hasRelatedResultType())) 4357 return ToMethod; 4358 4359 // FIXME: When we decide to merge method definitions, we'll need to 4360 // deal with implicit parameters. 4361 4362 // Import the parameters 4363 SmallVector<ParmVarDecl *, 5> ToParams; 4364 for (auto *FromP : D->parameters()) { 4365 if (Expected<ParmVarDecl *> ToPOrErr = import(FromP)) 4366 ToParams.push_back(*ToPOrErr); 4367 else 4368 return ToPOrErr.takeError(); 4369 } 4370 4371 // Set the parameters. 4372 for (auto *ToParam : ToParams) { 4373 ToParam->setOwningFunction(ToMethod); 4374 ToMethod->addDeclInternal(ToParam); 4375 } 4376 4377 SmallVector<SourceLocation, 12> FromSelLocs; 4378 D->getSelectorLocs(FromSelLocs); 4379 SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size()); 4380 if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs)) 4381 return std::move(Err); 4382 4383 ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs); 4384 4385 ToMethod->setLexicalDeclContext(LexicalDC); 4386 LexicalDC->addDeclInternal(ToMethod); 4387 4388 // Implicit params are declared when Sema encounters the definition but this 4389 // never happens when the method is imported. Manually declare the implicit 4390 // params now that the MethodDecl knows its class interface. 4391 if (D->getSelfDecl()) 4392 ToMethod->createImplicitParams(Importer.getToContext(), 4393 ToMethod->getClassInterface()); 4394 4395 return ToMethod; 4396 } 4397 4398 ExpectedDecl ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) { 4399 // Import the major distinguishing characteristics of a category. 4400 DeclContext *DC, *LexicalDC; 4401 DeclarationName Name; 4402 SourceLocation Loc; 4403 NamedDecl *ToD; 4404 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4405 return std::move(Err); 4406 if (ToD) 4407 return ToD; 4408 4409 Error Err = Error::success(); 4410 auto ToVarianceLoc = importChecked(Err, D->getVarianceLoc()); 4411 auto ToLocation = importChecked(Err, D->getLocation()); 4412 auto ToColonLoc = importChecked(Err, D->getColonLoc()); 4413 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo()); 4414 if (Err) 4415 return std::move(Err); 4416 4417 ObjCTypeParamDecl *Result; 4418 if (GetImportedOrCreateDecl( 4419 Result, D, Importer.getToContext(), DC, D->getVariance(), 4420 ToVarianceLoc, D->getIndex(), 4421 ToLocation, Name.getAsIdentifierInfo(), 4422 ToColonLoc, ToTypeSourceInfo)) 4423 return Result; 4424 4425 Result->setLexicalDeclContext(LexicalDC); 4426 return Result; 4427 } 4428 4429 ExpectedDecl ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) { 4430 // Import the major distinguishing characteristics of a category. 4431 DeclContext *DC, *LexicalDC; 4432 DeclarationName Name; 4433 SourceLocation Loc; 4434 NamedDecl *ToD; 4435 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4436 return std::move(Err); 4437 if (ToD) 4438 return ToD; 4439 4440 ObjCInterfaceDecl *ToInterface; 4441 if (Error Err = importInto(ToInterface, D->getClassInterface())) 4442 return std::move(Err); 4443 4444 // Determine if we've already encountered this category. 4445 ObjCCategoryDecl *MergeWithCategory 4446 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo()); 4447 ObjCCategoryDecl *ToCategory = MergeWithCategory; 4448 if (!ToCategory) { 4449 4450 Error Err = Error::success(); 4451 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc()); 4452 auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc()); 4453 auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc()); 4454 auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc()); 4455 if (Err) 4456 return std::move(Err); 4457 4458 if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC, 4459 ToAtStartLoc, Loc, 4460 ToCategoryNameLoc, 4461 Name.getAsIdentifierInfo(), ToInterface, 4462 /*TypeParamList=*/nullptr, 4463 ToIvarLBraceLoc, 4464 ToIvarRBraceLoc)) 4465 return ToCategory; 4466 4467 ToCategory->setLexicalDeclContext(LexicalDC); 4468 LexicalDC->addDeclInternal(ToCategory); 4469 // Import the type parameter list after MapImported, to avoid 4470 // loops when bringing in their DeclContext. 4471 if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList())) 4472 ToCategory->setTypeParamList(*PListOrErr); 4473 else 4474 return PListOrErr.takeError(); 4475 4476 // Import protocols 4477 SmallVector<ObjCProtocolDecl *, 4> Protocols; 4478 SmallVector<SourceLocation, 4> ProtocolLocs; 4479 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc 4480 = D->protocol_loc_begin(); 4481 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(), 4482 FromProtoEnd = D->protocol_end(); 4483 FromProto != FromProtoEnd; 4484 ++FromProto, ++FromProtoLoc) { 4485 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto)) 4486 Protocols.push_back(*ToProtoOrErr); 4487 else 4488 return ToProtoOrErr.takeError(); 4489 4490 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc)) 4491 ProtocolLocs.push_back(*ToProtoLocOrErr); 4492 else 4493 return ToProtoLocOrErr.takeError(); 4494 } 4495 4496 // FIXME: If we're merging, make sure that the protocol list is the same. 4497 ToCategory->setProtocolList(Protocols.data(), Protocols.size(), 4498 ProtocolLocs.data(), Importer.getToContext()); 4499 4500 } else { 4501 Importer.MapImported(D, ToCategory); 4502 } 4503 4504 // Import all of the members of this category. 4505 if (Error Err = ImportDeclContext(D)) 4506 return std::move(Err); 4507 4508 // If we have an implementation, import it as well. 4509 if (D->getImplementation()) { 4510 if (Expected<ObjCCategoryImplDecl *> ToImplOrErr = 4511 import(D->getImplementation())) 4512 ToCategory->setImplementation(*ToImplOrErr); 4513 else 4514 return ToImplOrErr.takeError(); 4515 } 4516 4517 return ToCategory; 4518 } 4519 4520 Error ASTNodeImporter::ImportDefinition( 4521 ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) { 4522 if (To->getDefinition()) { 4523 if (shouldForceImportDeclContext(Kind)) 4524 if (Error Err = ImportDeclContext(From)) 4525 return Err; 4526 return Error::success(); 4527 } 4528 4529 // Start the protocol definition 4530 To->startDefinition(); 4531 4532 // Import protocols 4533 SmallVector<ObjCProtocolDecl *, 4> Protocols; 4534 SmallVector<SourceLocation, 4> ProtocolLocs; 4535 ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc = 4536 From->protocol_loc_begin(); 4537 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(), 4538 FromProtoEnd = From->protocol_end(); 4539 FromProto != FromProtoEnd; 4540 ++FromProto, ++FromProtoLoc) { 4541 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto)) 4542 Protocols.push_back(*ToProtoOrErr); 4543 else 4544 return ToProtoOrErr.takeError(); 4545 4546 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc)) 4547 ProtocolLocs.push_back(*ToProtoLocOrErr); 4548 else 4549 return ToProtoLocOrErr.takeError(); 4550 4551 } 4552 4553 // FIXME: If we're merging, make sure that the protocol list is the same. 4554 To->setProtocolList(Protocols.data(), Protocols.size(), 4555 ProtocolLocs.data(), Importer.getToContext()); 4556 4557 if (shouldForceImportDeclContext(Kind)) { 4558 // Import all of the members of this protocol. 4559 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) 4560 return Err; 4561 } 4562 return Error::success(); 4563 } 4564 4565 ExpectedDecl ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) { 4566 // If this protocol has a definition in the translation unit we're coming 4567 // from, but this particular declaration is not that definition, import the 4568 // definition and map to that. 4569 ObjCProtocolDecl *Definition = D->getDefinition(); 4570 if (Definition && Definition != D) { 4571 if (ExpectedDecl ImportedDefOrErr = import(Definition)) 4572 return Importer.MapImported(D, *ImportedDefOrErr); 4573 else 4574 return ImportedDefOrErr.takeError(); 4575 } 4576 4577 // Import the major distinguishing characteristics of a protocol. 4578 DeclContext *DC, *LexicalDC; 4579 DeclarationName Name; 4580 SourceLocation Loc; 4581 NamedDecl *ToD; 4582 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4583 return std::move(Err); 4584 if (ToD) 4585 return ToD; 4586 4587 ObjCProtocolDecl *MergeWithProtocol = nullptr; 4588 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 4589 for (auto *FoundDecl : FoundDecls) { 4590 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol)) 4591 continue; 4592 4593 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl))) 4594 break; 4595 } 4596 4597 ObjCProtocolDecl *ToProto = MergeWithProtocol; 4598 if (!ToProto) { 4599 auto ToAtBeginLocOrErr = import(D->getAtStartLoc()); 4600 if (!ToAtBeginLocOrErr) 4601 return ToAtBeginLocOrErr.takeError(); 4602 4603 if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC, 4604 Name.getAsIdentifierInfo(), Loc, 4605 *ToAtBeginLocOrErr, 4606 /*PrevDecl=*/nullptr)) 4607 return ToProto; 4608 ToProto->setLexicalDeclContext(LexicalDC); 4609 LexicalDC->addDeclInternal(ToProto); 4610 } 4611 4612 Importer.MapImported(D, ToProto); 4613 4614 if (D->isThisDeclarationADefinition()) 4615 if (Error Err = ImportDefinition(D, ToProto)) 4616 return std::move(Err); 4617 4618 return ToProto; 4619 } 4620 4621 ExpectedDecl ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 4622 DeclContext *DC, *LexicalDC; 4623 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 4624 return std::move(Err); 4625 4626 ExpectedSLoc ExternLocOrErr = import(D->getExternLoc()); 4627 if (!ExternLocOrErr) 4628 return ExternLocOrErr.takeError(); 4629 4630 ExpectedSLoc LangLocOrErr = import(D->getLocation()); 4631 if (!LangLocOrErr) 4632 return LangLocOrErr.takeError(); 4633 4634 bool HasBraces = D->hasBraces(); 4635 4636 LinkageSpecDecl *ToLinkageSpec; 4637 if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC, 4638 *ExternLocOrErr, *LangLocOrErr, 4639 D->getLanguage(), HasBraces)) 4640 return ToLinkageSpec; 4641 4642 if (HasBraces) { 4643 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc()); 4644 if (!RBraceLocOrErr) 4645 return RBraceLocOrErr.takeError(); 4646 ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr); 4647 } 4648 4649 ToLinkageSpec->setLexicalDeclContext(LexicalDC); 4650 LexicalDC->addDeclInternal(ToLinkageSpec); 4651 4652 return ToLinkageSpec; 4653 } 4654 4655 ExpectedDecl ASTNodeImporter::ImportUsingShadowDecls(BaseUsingDecl *D, 4656 BaseUsingDecl *ToSI) { 4657 for (UsingShadowDecl *FromShadow : D->shadows()) { 4658 if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow)) 4659 ToSI->addShadowDecl(*ToShadowOrErr); 4660 else 4661 // FIXME: We return error here but the definition is already created 4662 // and available with lookups. How to fix this?.. 4663 return ToShadowOrErr.takeError(); 4664 } 4665 return ToSI; 4666 } 4667 4668 ExpectedDecl ASTNodeImporter::VisitUsingDecl(UsingDecl *D) { 4669 DeclContext *DC, *LexicalDC; 4670 DeclarationName Name; 4671 SourceLocation Loc; 4672 NamedDecl *ToD = nullptr; 4673 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4674 return std::move(Err); 4675 if (ToD) 4676 return ToD; 4677 4678 Error Err = Error::success(); 4679 auto ToLoc = importChecked(Err, D->getNameInfo().getLoc()); 4680 auto ToUsingLoc = importChecked(Err, D->getUsingLoc()); 4681 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 4682 if (Err) 4683 return std::move(Err); 4684 4685 DeclarationNameInfo NameInfo(Name, ToLoc); 4686 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo)) 4687 return std::move(Err); 4688 4689 UsingDecl *ToUsing; 4690 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC, 4691 ToUsingLoc, ToQualifierLoc, NameInfo, 4692 D->hasTypename())) 4693 return ToUsing; 4694 4695 ToUsing->setLexicalDeclContext(LexicalDC); 4696 LexicalDC->addDeclInternal(ToUsing); 4697 4698 if (NamedDecl *FromPattern = 4699 Importer.getFromContext().getInstantiatedFromUsingDecl(D)) { 4700 if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern)) 4701 Importer.getToContext().setInstantiatedFromUsingDecl( 4702 ToUsing, *ToPatternOrErr); 4703 else 4704 return ToPatternOrErr.takeError(); 4705 } 4706 4707 return ImportUsingShadowDecls(D, ToUsing); 4708 } 4709 4710 ExpectedDecl ASTNodeImporter::VisitUsingEnumDecl(UsingEnumDecl *D) { 4711 DeclContext *DC, *LexicalDC; 4712 DeclarationName Name; 4713 SourceLocation Loc; 4714 NamedDecl *ToD = nullptr; 4715 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4716 return std::move(Err); 4717 if (ToD) 4718 return ToD; 4719 4720 Error Err = Error::success(); 4721 auto ToUsingLoc = importChecked(Err, D->getUsingLoc()); 4722 auto ToEnumLoc = importChecked(Err, D->getEnumLoc()); 4723 auto ToEnumDecl = importChecked(Err, D->getEnumDecl()); 4724 if (Err) 4725 return std::move(Err); 4726 4727 UsingEnumDecl *ToUsingEnum; 4728 if (GetImportedOrCreateDecl(ToUsingEnum, D, Importer.getToContext(), DC, 4729 ToUsingLoc, ToEnumLoc, Loc, ToEnumDecl)) 4730 return ToUsingEnum; 4731 4732 ToUsingEnum->setLexicalDeclContext(LexicalDC); 4733 LexicalDC->addDeclInternal(ToUsingEnum); 4734 4735 if (UsingEnumDecl *FromPattern = 4736 Importer.getFromContext().getInstantiatedFromUsingEnumDecl(D)) { 4737 if (Expected<UsingEnumDecl *> ToPatternOrErr = import(FromPattern)) 4738 Importer.getToContext().setInstantiatedFromUsingEnumDecl(ToUsingEnum, 4739 *ToPatternOrErr); 4740 else 4741 return ToPatternOrErr.takeError(); 4742 } 4743 4744 return ImportUsingShadowDecls(D, ToUsingEnum); 4745 } 4746 4747 ExpectedDecl ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) { 4748 DeclContext *DC, *LexicalDC; 4749 DeclarationName Name; 4750 SourceLocation Loc; 4751 NamedDecl *ToD = nullptr; 4752 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4753 return std::move(Err); 4754 if (ToD) 4755 return ToD; 4756 4757 Expected<BaseUsingDecl *> ToIntroducerOrErr = import(D->getIntroducer()); 4758 if (!ToIntroducerOrErr) 4759 return ToIntroducerOrErr.takeError(); 4760 4761 Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl()); 4762 if (!ToTargetOrErr) 4763 return ToTargetOrErr.takeError(); 4764 4765 UsingShadowDecl *ToShadow; 4766 if (auto *FromConstructorUsingShadow = 4767 dyn_cast<ConstructorUsingShadowDecl>(D)) { 4768 Error Err = Error::success(); 4769 ConstructorUsingShadowDecl *Nominated = importChecked( 4770 Err, FromConstructorUsingShadow->getNominatedBaseClassShadowDecl()); 4771 if (Err) 4772 return std::move(Err); 4773 // The 'Target' parameter of ConstructorUsingShadowDecl constructor 4774 // is really the "NominatedBaseClassShadowDecl" value if it exists 4775 // (see code of ConstructorUsingShadowDecl::ConstructorUsingShadowDecl). 4776 // We should pass the NominatedBaseClassShadowDecl to it (if non-null) to 4777 // get the correct values. 4778 if (GetImportedOrCreateDecl<ConstructorUsingShadowDecl>( 4779 ToShadow, D, Importer.getToContext(), DC, Loc, 4780 cast<UsingDecl>(*ToIntroducerOrErr), 4781 Nominated ? Nominated : *ToTargetOrErr, 4782 FromConstructorUsingShadow->constructsVirtualBase())) 4783 return ToShadow; 4784 } else { 4785 if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc, 4786 Name, *ToIntroducerOrErr, *ToTargetOrErr)) 4787 return ToShadow; 4788 } 4789 4790 ToShadow->setLexicalDeclContext(LexicalDC); 4791 ToShadow->setAccess(D->getAccess()); 4792 4793 if (UsingShadowDecl *FromPattern = 4794 Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) { 4795 if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern)) 4796 Importer.getToContext().setInstantiatedFromUsingShadowDecl( 4797 ToShadow, *ToPatternOrErr); 4798 else 4799 // FIXME: We return error here but the definition is already created 4800 // and available with lookups. How to fix this?.. 4801 return ToPatternOrErr.takeError(); 4802 } 4803 4804 LexicalDC->addDeclInternal(ToShadow); 4805 4806 return ToShadow; 4807 } 4808 4809 ExpectedDecl ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 4810 DeclContext *DC, *LexicalDC; 4811 DeclarationName Name; 4812 SourceLocation Loc; 4813 NamedDecl *ToD = nullptr; 4814 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4815 return std::move(Err); 4816 if (ToD) 4817 return ToD; 4818 4819 auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor()); 4820 if (!ToComAncestorOrErr) 4821 return ToComAncestorOrErr.takeError(); 4822 4823 Error Err = Error::success(); 4824 auto ToNominatedNamespace = importChecked(Err, D->getNominatedNamespace()); 4825 auto ToUsingLoc = importChecked(Err, D->getUsingLoc()); 4826 auto ToNamespaceKeyLocation = 4827 importChecked(Err, D->getNamespaceKeyLocation()); 4828 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 4829 auto ToIdentLocation = importChecked(Err, D->getIdentLocation()); 4830 if (Err) 4831 return std::move(Err); 4832 4833 UsingDirectiveDecl *ToUsingDir; 4834 if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC, 4835 ToUsingLoc, 4836 ToNamespaceKeyLocation, 4837 ToQualifierLoc, 4838 ToIdentLocation, 4839 ToNominatedNamespace, *ToComAncestorOrErr)) 4840 return ToUsingDir; 4841 4842 ToUsingDir->setLexicalDeclContext(LexicalDC); 4843 LexicalDC->addDeclInternal(ToUsingDir); 4844 4845 return ToUsingDir; 4846 } 4847 4848 ExpectedDecl ASTNodeImporter::VisitUsingPackDecl(UsingPackDecl *D) { 4849 DeclContext *DC, *LexicalDC; 4850 DeclarationName Name; 4851 SourceLocation Loc; 4852 NamedDecl *ToD = nullptr; 4853 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4854 return std::move(Err); 4855 if (ToD) 4856 return ToD; 4857 4858 auto ToInstantiatedFromUsingOrErr = 4859 Importer.Import(D->getInstantiatedFromUsingDecl()); 4860 if (!ToInstantiatedFromUsingOrErr) 4861 return ToInstantiatedFromUsingOrErr.takeError(); 4862 SmallVector<NamedDecl *, 4> Expansions(D->expansions().size()); 4863 if (Error Err = ImportArrayChecked(D->expansions(), Expansions.begin())) 4864 return std::move(Err); 4865 4866 UsingPackDecl *ToUsingPack; 4867 if (GetImportedOrCreateDecl(ToUsingPack, D, Importer.getToContext(), DC, 4868 cast<NamedDecl>(*ToInstantiatedFromUsingOrErr), 4869 Expansions)) 4870 return ToUsingPack; 4871 4872 addDeclToContexts(D, ToUsingPack); 4873 4874 return ToUsingPack; 4875 } 4876 4877 ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl( 4878 UnresolvedUsingValueDecl *D) { 4879 DeclContext *DC, *LexicalDC; 4880 DeclarationName Name; 4881 SourceLocation Loc; 4882 NamedDecl *ToD = nullptr; 4883 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4884 return std::move(Err); 4885 if (ToD) 4886 return ToD; 4887 4888 Error Err = Error::success(); 4889 auto ToLoc = importChecked(Err, D->getNameInfo().getLoc()); 4890 auto ToUsingLoc = importChecked(Err, D->getUsingLoc()); 4891 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 4892 auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc()); 4893 if (Err) 4894 return std::move(Err); 4895 4896 DeclarationNameInfo NameInfo(Name, ToLoc); 4897 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo)) 4898 return std::move(Err); 4899 4900 UnresolvedUsingValueDecl *ToUsingValue; 4901 if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC, 4902 ToUsingLoc, ToQualifierLoc, NameInfo, 4903 ToEllipsisLoc)) 4904 return ToUsingValue; 4905 4906 ToUsingValue->setAccess(D->getAccess()); 4907 ToUsingValue->setLexicalDeclContext(LexicalDC); 4908 LexicalDC->addDeclInternal(ToUsingValue); 4909 4910 return ToUsingValue; 4911 } 4912 4913 ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingTypenameDecl( 4914 UnresolvedUsingTypenameDecl *D) { 4915 DeclContext *DC, *LexicalDC; 4916 DeclarationName Name; 4917 SourceLocation Loc; 4918 NamedDecl *ToD = nullptr; 4919 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4920 return std::move(Err); 4921 if (ToD) 4922 return ToD; 4923 4924 Error Err = Error::success(); 4925 auto ToUsingLoc = importChecked(Err, D->getUsingLoc()); 4926 auto ToTypenameLoc = importChecked(Err, D->getTypenameLoc()); 4927 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc()); 4928 auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc()); 4929 if (Err) 4930 return std::move(Err); 4931 4932 UnresolvedUsingTypenameDecl *ToUsing; 4933 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC, 4934 ToUsingLoc, ToTypenameLoc, 4935 ToQualifierLoc, Loc, Name, ToEllipsisLoc)) 4936 return ToUsing; 4937 4938 ToUsing->setAccess(D->getAccess()); 4939 ToUsing->setLexicalDeclContext(LexicalDC); 4940 LexicalDC->addDeclInternal(ToUsing); 4941 4942 return ToUsing; 4943 } 4944 4945 ExpectedDecl ASTNodeImporter::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) { 4946 Decl* ToD = nullptr; 4947 switch (D->getBuiltinTemplateKind()) { 4948 case BuiltinTemplateKind::BTK__make_integer_seq: 4949 ToD = Importer.getToContext().getMakeIntegerSeqDecl(); 4950 break; 4951 case BuiltinTemplateKind::BTK__type_pack_element: 4952 ToD = Importer.getToContext().getTypePackElementDecl(); 4953 break; 4954 } 4955 assert(ToD && "BuiltinTemplateDecl of unsupported kind!"); 4956 Importer.MapImported(D, ToD); 4957 return ToD; 4958 } 4959 4960 Error ASTNodeImporter::ImportDefinition( 4961 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) { 4962 if (To->getDefinition()) { 4963 // Check consistency of superclass. 4964 ObjCInterfaceDecl *FromSuper = From->getSuperClass(); 4965 if (FromSuper) { 4966 if (auto FromSuperOrErr = import(FromSuper)) 4967 FromSuper = *FromSuperOrErr; 4968 else 4969 return FromSuperOrErr.takeError(); 4970 } 4971 4972 ObjCInterfaceDecl *ToSuper = To->getSuperClass(); 4973 if ((bool)FromSuper != (bool)ToSuper || 4974 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) { 4975 Importer.ToDiag(To->getLocation(), 4976 diag::warn_odr_objc_superclass_inconsistent) 4977 << To->getDeclName(); 4978 if (ToSuper) 4979 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass) 4980 << To->getSuperClass()->getDeclName(); 4981 else 4982 Importer.ToDiag(To->getLocation(), 4983 diag::note_odr_objc_missing_superclass); 4984 if (From->getSuperClass()) 4985 Importer.FromDiag(From->getSuperClassLoc(), 4986 diag::note_odr_objc_superclass) 4987 << From->getSuperClass()->getDeclName(); 4988 else 4989 Importer.FromDiag(From->getLocation(), 4990 diag::note_odr_objc_missing_superclass); 4991 } 4992 4993 if (shouldForceImportDeclContext(Kind)) 4994 if (Error Err = ImportDeclContext(From)) 4995 return Err; 4996 return Error::success(); 4997 } 4998 4999 // Start the definition. 5000 To->startDefinition(); 5001 5002 // If this class has a superclass, import it. 5003 if (From->getSuperClass()) { 5004 if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo())) 5005 To->setSuperClass(*SuperTInfoOrErr); 5006 else 5007 return SuperTInfoOrErr.takeError(); 5008 } 5009 5010 // Import protocols 5011 SmallVector<ObjCProtocolDecl *, 4> Protocols; 5012 SmallVector<SourceLocation, 4> ProtocolLocs; 5013 ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc = 5014 From->protocol_loc_begin(); 5015 5016 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(), 5017 FromProtoEnd = From->protocol_end(); 5018 FromProto != FromProtoEnd; 5019 ++FromProto, ++FromProtoLoc) { 5020 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto)) 5021 Protocols.push_back(*ToProtoOrErr); 5022 else 5023 return ToProtoOrErr.takeError(); 5024 5025 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc)) 5026 ProtocolLocs.push_back(*ToProtoLocOrErr); 5027 else 5028 return ToProtoLocOrErr.takeError(); 5029 5030 } 5031 5032 // FIXME: If we're merging, make sure that the protocol list is the same. 5033 To->setProtocolList(Protocols.data(), Protocols.size(), 5034 ProtocolLocs.data(), Importer.getToContext()); 5035 5036 // Import categories. When the categories themselves are imported, they'll 5037 // hook themselves into this interface. 5038 for (auto *Cat : From->known_categories()) { 5039 auto ToCatOrErr = import(Cat); 5040 if (!ToCatOrErr) 5041 return ToCatOrErr.takeError(); 5042 } 5043 5044 // If we have an @implementation, import it as well. 5045 if (From->getImplementation()) { 5046 if (Expected<ObjCImplementationDecl *> ToImplOrErr = 5047 import(From->getImplementation())) 5048 To->setImplementation(*ToImplOrErr); 5049 else 5050 return ToImplOrErr.takeError(); 5051 } 5052 5053 // Import all of the members of this class. 5054 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) 5055 return Err; 5056 5057 return Error::success(); 5058 } 5059 5060 Expected<ObjCTypeParamList *> 5061 ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) { 5062 if (!list) 5063 return nullptr; 5064 5065 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams; 5066 for (auto *fromTypeParam : *list) { 5067 if (auto toTypeParamOrErr = import(fromTypeParam)) 5068 toTypeParams.push_back(*toTypeParamOrErr); 5069 else 5070 return toTypeParamOrErr.takeError(); 5071 } 5072 5073 auto LAngleLocOrErr = import(list->getLAngleLoc()); 5074 if (!LAngleLocOrErr) 5075 return LAngleLocOrErr.takeError(); 5076 5077 auto RAngleLocOrErr = import(list->getRAngleLoc()); 5078 if (!RAngleLocOrErr) 5079 return RAngleLocOrErr.takeError(); 5080 5081 return ObjCTypeParamList::create(Importer.getToContext(), 5082 *LAngleLocOrErr, 5083 toTypeParams, 5084 *RAngleLocOrErr); 5085 } 5086 5087 ExpectedDecl ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { 5088 // If this class has a definition in the translation unit we're coming from, 5089 // but this particular declaration is not that definition, import the 5090 // definition and map to that. 5091 ObjCInterfaceDecl *Definition = D->getDefinition(); 5092 if (Definition && Definition != D) { 5093 if (ExpectedDecl ImportedDefOrErr = import(Definition)) 5094 return Importer.MapImported(D, *ImportedDefOrErr); 5095 else 5096 return ImportedDefOrErr.takeError(); 5097 } 5098 5099 // Import the major distinguishing characteristics of an @interface. 5100 DeclContext *DC, *LexicalDC; 5101 DeclarationName Name; 5102 SourceLocation Loc; 5103 NamedDecl *ToD; 5104 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 5105 return std::move(Err); 5106 if (ToD) 5107 return ToD; 5108 5109 // Look for an existing interface with the same name. 5110 ObjCInterfaceDecl *MergeWithIface = nullptr; 5111 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 5112 for (auto *FoundDecl : FoundDecls) { 5113 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 5114 continue; 5115 5116 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl))) 5117 break; 5118 } 5119 5120 // Create an interface declaration, if one does not already exist. 5121 ObjCInterfaceDecl *ToIface = MergeWithIface; 5122 if (!ToIface) { 5123 ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc()); 5124 if (!AtBeginLocOrErr) 5125 return AtBeginLocOrErr.takeError(); 5126 5127 if (GetImportedOrCreateDecl( 5128 ToIface, D, Importer.getToContext(), DC, 5129 *AtBeginLocOrErr, Name.getAsIdentifierInfo(), 5130 /*TypeParamList=*/nullptr, 5131 /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl())) 5132 return ToIface; 5133 ToIface->setLexicalDeclContext(LexicalDC); 5134 LexicalDC->addDeclInternal(ToIface); 5135 } 5136 Importer.MapImported(D, ToIface); 5137 // Import the type parameter list after MapImported, to avoid 5138 // loops when bringing in their DeclContext. 5139 if (auto ToPListOrErr = 5140 ImportObjCTypeParamList(D->getTypeParamListAsWritten())) 5141 ToIface->setTypeParamList(*ToPListOrErr); 5142 else 5143 return ToPListOrErr.takeError(); 5144 5145 if (D->isThisDeclarationADefinition()) 5146 if (Error Err = ImportDefinition(D, ToIface)) 5147 return std::move(Err); 5148 5149 return ToIface; 5150 } 5151 5152 ExpectedDecl 5153 ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { 5154 ObjCCategoryDecl *Category; 5155 if (Error Err = importInto(Category, D->getCategoryDecl())) 5156 return std::move(Err); 5157 5158 ObjCCategoryImplDecl *ToImpl = Category->getImplementation(); 5159 if (!ToImpl) { 5160 DeclContext *DC, *LexicalDC; 5161 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 5162 return std::move(Err); 5163 5164 Error Err = Error::success(); 5165 auto ToLocation = importChecked(Err, D->getLocation()); 5166 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc()); 5167 auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc()); 5168 if (Err) 5169 return std::move(Err); 5170 5171 if (GetImportedOrCreateDecl( 5172 ToImpl, D, Importer.getToContext(), DC, 5173 Importer.Import(D->getIdentifier()), Category->getClassInterface(), 5174 ToLocation, ToAtStartLoc, ToCategoryNameLoc)) 5175 return ToImpl; 5176 5177 ToImpl->setLexicalDeclContext(LexicalDC); 5178 LexicalDC->addDeclInternal(ToImpl); 5179 Category->setImplementation(ToImpl); 5180 } 5181 5182 Importer.MapImported(D, ToImpl); 5183 if (Error Err = ImportDeclContext(D)) 5184 return std::move(Err); 5185 5186 return ToImpl; 5187 } 5188 5189 ExpectedDecl 5190 ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { 5191 // Find the corresponding interface. 5192 ObjCInterfaceDecl *Iface; 5193 if (Error Err = importInto(Iface, D->getClassInterface())) 5194 return std::move(Err); 5195 5196 // Import the superclass, if any. 5197 ObjCInterfaceDecl *Super; 5198 if (Error Err = importInto(Super, D->getSuperClass())) 5199 return std::move(Err); 5200 5201 ObjCImplementationDecl *Impl = Iface->getImplementation(); 5202 if (!Impl) { 5203 // We haven't imported an implementation yet. Create a new @implementation 5204 // now. 5205 DeclContext *DC, *LexicalDC; 5206 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 5207 return std::move(Err); 5208 5209 Error Err = Error::success(); 5210 auto ToLocation = importChecked(Err, D->getLocation()); 5211 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc()); 5212 auto ToSuperClassLoc = importChecked(Err, D->getSuperClassLoc()); 5213 auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc()); 5214 auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc()); 5215 if (Err) 5216 return std::move(Err); 5217 5218 if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(), 5219 DC, Iface, Super, 5220 ToLocation, 5221 ToAtStartLoc, 5222 ToSuperClassLoc, 5223 ToIvarLBraceLoc, 5224 ToIvarRBraceLoc)) 5225 return Impl; 5226 5227 Impl->setLexicalDeclContext(LexicalDC); 5228 5229 // Associate the implementation with the class it implements. 5230 Iface->setImplementation(Impl); 5231 Importer.MapImported(D, Iface->getImplementation()); 5232 } else { 5233 Importer.MapImported(D, Iface->getImplementation()); 5234 5235 // Verify that the existing @implementation has the same superclass. 5236 if ((Super && !Impl->getSuperClass()) || 5237 (!Super && Impl->getSuperClass()) || 5238 (Super && Impl->getSuperClass() && 5239 !declaresSameEntity(Super->getCanonicalDecl(), 5240 Impl->getSuperClass()))) { 5241 Importer.ToDiag(Impl->getLocation(), 5242 diag::warn_odr_objc_superclass_inconsistent) 5243 << Iface->getDeclName(); 5244 // FIXME: It would be nice to have the location of the superclass 5245 // below. 5246 if (Impl->getSuperClass()) 5247 Importer.ToDiag(Impl->getLocation(), 5248 diag::note_odr_objc_superclass) 5249 << Impl->getSuperClass()->getDeclName(); 5250 else 5251 Importer.ToDiag(Impl->getLocation(), 5252 diag::note_odr_objc_missing_superclass); 5253 if (D->getSuperClass()) 5254 Importer.FromDiag(D->getLocation(), 5255 diag::note_odr_objc_superclass) 5256 << D->getSuperClass()->getDeclName(); 5257 else 5258 Importer.FromDiag(D->getLocation(), 5259 diag::note_odr_objc_missing_superclass); 5260 5261 return make_error<ASTImportError>(ASTImportError::NameConflict); 5262 } 5263 } 5264 5265 // Import all of the members of this @implementation. 5266 if (Error Err = ImportDeclContext(D)) 5267 return std::move(Err); 5268 5269 return Impl; 5270 } 5271 5272 ExpectedDecl ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) { 5273 // Import the major distinguishing characteristics of an @property. 5274 DeclContext *DC, *LexicalDC; 5275 DeclarationName Name; 5276 SourceLocation Loc; 5277 NamedDecl *ToD; 5278 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 5279 return std::move(Err); 5280 if (ToD) 5281 return ToD; 5282 5283 // Check whether we have already imported this property. 5284 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 5285 for (auto *FoundDecl : FoundDecls) { 5286 if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) { 5287 // Instance and class properties can share the same name but are different 5288 // declarations. 5289 if (FoundProp->isInstanceProperty() != D->isInstanceProperty()) 5290 continue; 5291 5292 // Check property types. 5293 if (!Importer.IsStructurallyEquivalent(D->getType(), 5294 FoundProp->getType())) { 5295 Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent) 5296 << Name << D->getType() << FoundProp->getType(); 5297 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here) 5298 << FoundProp->getType(); 5299 5300 return make_error<ASTImportError>(ASTImportError::NameConflict); 5301 } 5302 5303 // FIXME: Check property attributes, getters, setters, etc.? 5304 5305 // Consider these properties to be equivalent. 5306 Importer.MapImported(D, FoundProp); 5307 return FoundProp; 5308 } 5309 } 5310 5311 Error Err = Error::success(); 5312 auto ToType = importChecked(Err, D->getType()); 5313 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo()); 5314 auto ToAtLoc = importChecked(Err, D->getAtLoc()); 5315 auto ToLParenLoc = importChecked(Err, D->getLParenLoc()); 5316 if (Err) 5317 return std::move(Err); 5318 5319 // Create the new property. 5320 ObjCPropertyDecl *ToProperty; 5321 if (GetImportedOrCreateDecl( 5322 ToProperty, D, Importer.getToContext(), DC, Loc, 5323 Name.getAsIdentifierInfo(), ToAtLoc, 5324 ToLParenLoc, ToType, 5325 ToTypeSourceInfo, D->getPropertyImplementation())) 5326 return ToProperty; 5327 5328 auto ToGetterName = importChecked(Err, D->getGetterName()); 5329 auto ToSetterName = importChecked(Err, D->getSetterName()); 5330 auto ToGetterNameLoc = importChecked(Err, D->getGetterNameLoc()); 5331 auto ToSetterNameLoc = importChecked(Err, D->getSetterNameLoc()); 5332 auto ToGetterMethodDecl = importChecked(Err, D->getGetterMethodDecl()); 5333 auto ToSetterMethodDecl = importChecked(Err, D->getSetterMethodDecl()); 5334 auto ToPropertyIvarDecl = importChecked(Err, D->getPropertyIvarDecl()); 5335 if (Err) 5336 return std::move(Err); 5337 5338 ToProperty->setLexicalDeclContext(LexicalDC); 5339 LexicalDC->addDeclInternal(ToProperty); 5340 5341 ToProperty->setPropertyAttributes(D->getPropertyAttributes()); 5342 ToProperty->setPropertyAttributesAsWritten( 5343 D->getPropertyAttributesAsWritten()); 5344 ToProperty->setGetterName(ToGetterName, ToGetterNameLoc); 5345 ToProperty->setSetterName(ToSetterName, ToSetterNameLoc); 5346 ToProperty->setGetterMethodDecl(ToGetterMethodDecl); 5347 ToProperty->setSetterMethodDecl(ToSetterMethodDecl); 5348 ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl); 5349 return ToProperty; 5350 } 5351 5352 ExpectedDecl 5353 ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) { 5354 ObjCPropertyDecl *Property; 5355 if (Error Err = importInto(Property, D->getPropertyDecl())) 5356 return std::move(Err); 5357 5358 DeclContext *DC, *LexicalDC; 5359 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 5360 return std::move(Err); 5361 5362 auto *InImpl = cast<ObjCImplDecl>(LexicalDC); 5363 5364 // Import the ivar (for an @synthesize). 5365 ObjCIvarDecl *Ivar = nullptr; 5366 if (Error Err = importInto(Ivar, D->getPropertyIvarDecl())) 5367 return std::move(Err); 5368 5369 ObjCPropertyImplDecl *ToImpl 5370 = InImpl->FindPropertyImplDecl(Property->getIdentifier(), 5371 Property->getQueryKind()); 5372 if (!ToImpl) { 5373 5374 Error Err = Error::success(); 5375 auto ToBeginLoc = importChecked(Err, D->getBeginLoc()); 5376 auto ToLocation = importChecked(Err, D->getLocation()); 5377 auto ToPropertyIvarDeclLoc = 5378 importChecked(Err, D->getPropertyIvarDeclLoc()); 5379 if (Err) 5380 return std::move(Err); 5381 5382 if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC, 5383 ToBeginLoc, 5384 ToLocation, Property, 5385 D->getPropertyImplementation(), Ivar, 5386 ToPropertyIvarDeclLoc)) 5387 return ToImpl; 5388 5389 ToImpl->setLexicalDeclContext(LexicalDC); 5390 LexicalDC->addDeclInternal(ToImpl); 5391 } else { 5392 // Check that we have the same kind of property implementation (@synthesize 5393 // vs. @dynamic). 5394 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) { 5395 Importer.ToDiag(ToImpl->getLocation(), 5396 diag::warn_odr_objc_property_impl_kind_inconsistent) 5397 << Property->getDeclName() 5398 << (ToImpl->getPropertyImplementation() 5399 == ObjCPropertyImplDecl::Dynamic); 5400 Importer.FromDiag(D->getLocation(), 5401 diag::note_odr_objc_property_impl_kind) 5402 << D->getPropertyDecl()->getDeclName() 5403 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic); 5404 5405 return make_error<ASTImportError>(ASTImportError::NameConflict); 5406 } 5407 5408 // For @synthesize, check that we have the same 5409 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize && 5410 Ivar != ToImpl->getPropertyIvarDecl()) { 5411 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(), 5412 diag::warn_odr_objc_synthesize_ivar_inconsistent) 5413 << Property->getDeclName() 5414 << ToImpl->getPropertyIvarDecl()->getDeclName() 5415 << Ivar->getDeclName(); 5416 Importer.FromDiag(D->getPropertyIvarDeclLoc(), 5417 diag::note_odr_objc_synthesize_ivar_here) 5418 << D->getPropertyIvarDecl()->getDeclName(); 5419 5420 return make_error<ASTImportError>(ASTImportError::NameConflict); 5421 } 5422 5423 // Merge the existing implementation with the new implementation. 5424 Importer.MapImported(D, ToImpl); 5425 } 5426 5427 return ToImpl; 5428 } 5429 5430 ExpectedDecl 5431 ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { 5432 // For template arguments, we adopt the translation unit as our declaration 5433 // context. This context will be fixed when the actual template declaration 5434 // is created. 5435 5436 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 5437 if (!BeginLocOrErr) 5438 return BeginLocOrErr.takeError(); 5439 5440 ExpectedSLoc LocationOrErr = import(D->getLocation()); 5441 if (!LocationOrErr) 5442 return LocationOrErr.takeError(); 5443 5444 TemplateTypeParmDecl *ToD = nullptr; 5445 if (GetImportedOrCreateDecl( 5446 ToD, D, Importer.getToContext(), 5447 Importer.getToContext().getTranslationUnitDecl(), 5448 *BeginLocOrErr, *LocationOrErr, 5449 D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()), 5450 D->wasDeclaredWithTypename(), D->isParameterPack(), 5451 D->hasTypeConstraint())) 5452 return ToD; 5453 5454 // Import the type-constraint 5455 if (const TypeConstraint *TC = D->getTypeConstraint()) { 5456 5457 Error Err = Error::success(); 5458 auto ToNNS = importChecked(Err, TC->getNestedNameSpecifierLoc()); 5459 auto ToName = importChecked(Err, TC->getConceptNameInfo().getName()); 5460 auto ToNameLoc = importChecked(Err, TC->getConceptNameInfo().getLoc()); 5461 auto ToFoundDecl = importChecked(Err, TC->getFoundDecl()); 5462 auto ToNamedConcept = importChecked(Err, TC->getNamedConcept()); 5463 auto ToIDC = importChecked(Err, TC->getImmediatelyDeclaredConstraint()); 5464 if (Err) 5465 return std::move(Err); 5466 5467 TemplateArgumentListInfo ToTAInfo; 5468 const auto *ASTTemplateArgs = TC->getTemplateArgsAsWritten(); 5469 if (ASTTemplateArgs) 5470 if (Error Err = ImportTemplateArgumentListInfo(*ASTTemplateArgs, 5471 ToTAInfo)) 5472 return std::move(Err); 5473 5474 ToD->setTypeConstraint(ToNNS, DeclarationNameInfo(ToName, ToNameLoc), 5475 ToFoundDecl, ToNamedConcept, 5476 ASTTemplateArgs ? 5477 ASTTemplateArgumentListInfo::Create(Importer.getToContext(), 5478 ToTAInfo) : nullptr, 5479 ToIDC); 5480 } 5481 5482 if (D->hasDefaultArgument()) { 5483 Expected<TypeSourceInfo *> ToDefaultArgOrErr = 5484 import(D->getDefaultArgumentInfo()); 5485 if (!ToDefaultArgOrErr) 5486 return ToDefaultArgOrErr.takeError(); 5487 ToD->setDefaultArgument(*ToDefaultArgOrErr); 5488 } 5489 5490 return ToD; 5491 } 5492 5493 ExpectedDecl 5494 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { 5495 5496 Error Err = Error::success(); 5497 auto ToDeclName = importChecked(Err, D->getDeclName()); 5498 auto ToLocation = importChecked(Err, D->getLocation()); 5499 auto ToType = importChecked(Err, D->getType()); 5500 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo()); 5501 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart()); 5502 if (Err) 5503 return std::move(Err); 5504 5505 NonTypeTemplateParmDecl *ToD = nullptr; 5506 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), 5507 Importer.getToContext().getTranslationUnitDecl(), 5508 ToInnerLocStart, ToLocation, D->getDepth(), 5509 D->getPosition(), 5510 ToDeclName.getAsIdentifierInfo(), ToType, 5511 D->isParameterPack(), ToTypeSourceInfo)) 5512 return ToD; 5513 5514 if (D->hasDefaultArgument()) { 5515 ExpectedExpr ToDefaultArgOrErr = import(D->getDefaultArgument()); 5516 if (!ToDefaultArgOrErr) 5517 return ToDefaultArgOrErr.takeError(); 5518 ToD->setDefaultArgument(*ToDefaultArgOrErr); 5519 } 5520 5521 return ToD; 5522 } 5523 5524 ExpectedDecl 5525 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { 5526 // Import the name of this declaration. 5527 auto NameOrErr = import(D->getDeclName()); 5528 if (!NameOrErr) 5529 return NameOrErr.takeError(); 5530 5531 // Import the location of this declaration. 5532 ExpectedSLoc LocationOrErr = import(D->getLocation()); 5533 if (!LocationOrErr) 5534 return LocationOrErr.takeError(); 5535 5536 // Import template parameters. 5537 auto TemplateParamsOrErr = import(D->getTemplateParameters()); 5538 if (!TemplateParamsOrErr) 5539 return TemplateParamsOrErr.takeError(); 5540 5541 TemplateTemplateParmDecl *ToD = nullptr; 5542 if (GetImportedOrCreateDecl( 5543 ToD, D, Importer.getToContext(), 5544 Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr, 5545 D->getDepth(), D->getPosition(), D->isParameterPack(), 5546 (*NameOrErr).getAsIdentifierInfo(), *TemplateParamsOrErr)) 5547 return ToD; 5548 5549 if (D->hasDefaultArgument()) { 5550 Expected<TemplateArgumentLoc> ToDefaultArgOrErr = 5551 import(D->getDefaultArgument()); 5552 if (!ToDefaultArgOrErr) 5553 return ToDefaultArgOrErr.takeError(); 5554 ToD->setDefaultArgument(Importer.getToContext(), *ToDefaultArgOrErr); 5555 } 5556 5557 return ToD; 5558 } 5559 5560 // Returns the definition for a (forward) declaration of a TemplateDecl, if 5561 // it has any definition in the redecl chain. 5562 template <typename T> static auto getTemplateDefinition(T *D) -> T * { 5563 assert(D->getTemplatedDecl() && "Should be called on templates only"); 5564 auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition(); 5565 if (!ToTemplatedDef) 5566 return nullptr; 5567 auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate(); 5568 return cast_or_null<T>(TemplateWithDef); 5569 } 5570 5571 ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) { 5572 5573 // Import the major distinguishing characteristics of this class template. 5574 DeclContext *DC, *LexicalDC; 5575 DeclarationName Name; 5576 SourceLocation Loc; 5577 NamedDecl *ToD; 5578 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 5579 return std::move(Err); 5580 if (ToD) 5581 return ToD; 5582 5583 ClassTemplateDecl *FoundByLookup = nullptr; 5584 5585 // We may already have a template of the same name; try to find and match it. 5586 if (!DC->isFunctionOrMethod()) { 5587 SmallVector<NamedDecl *, 4> ConflictingDecls; 5588 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 5589 for (auto *FoundDecl : FoundDecls) { 5590 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary | 5591 Decl::IDNS_TagFriend)) 5592 continue; 5593 5594 Decl *Found = FoundDecl; 5595 auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found); 5596 if (FoundTemplate) { 5597 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D)) 5598 continue; 5599 5600 if (IsStructuralMatch(D, FoundTemplate)) { 5601 ClassTemplateDecl *TemplateWithDef = 5602 getTemplateDefinition(FoundTemplate); 5603 if (D->isThisDeclarationADefinition() && TemplateWithDef) 5604 return Importer.MapImported(D, TemplateWithDef); 5605 if (!FoundByLookup) 5606 FoundByLookup = FoundTemplate; 5607 // Search in all matches because there may be multiple decl chains, 5608 // see ASTTests test ImportExistingFriendClassTemplateDef. 5609 continue; 5610 } 5611 ConflictingDecls.push_back(FoundDecl); 5612 } 5613 } 5614 5615 if (!ConflictingDecls.empty()) { 5616 ExpectedName NameOrErr = Importer.HandleNameConflict( 5617 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(), 5618 ConflictingDecls.size()); 5619 if (NameOrErr) 5620 Name = NameOrErr.get(); 5621 else 5622 return NameOrErr.takeError(); 5623 } 5624 } 5625 5626 CXXRecordDecl *FromTemplated = D->getTemplatedDecl(); 5627 5628 auto TemplateParamsOrErr = import(D->getTemplateParameters()); 5629 if (!TemplateParamsOrErr) 5630 return TemplateParamsOrErr.takeError(); 5631 5632 // Create the declaration that is being templated. 5633 CXXRecordDecl *ToTemplated; 5634 if (Error Err = importInto(ToTemplated, FromTemplated)) 5635 return std::move(Err); 5636 5637 // Create the class template declaration itself. 5638 ClassTemplateDecl *D2; 5639 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name, 5640 *TemplateParamsOrErr, ToTemplated)) 5641 return D2; 5642 5643 ToTemplated->setDescribedClassTemplate(D2); 5644 5645 D2->setAccess(D->getAccess()); 5646 D2->setLexicalDeclContext(LexicalDC); 5647 5648 addDeclToContexts(D, D2); 5649 updateLookupTableForTemplateParameters(**TemplateParamsOrErr); 5650 5651 if (FoundByLookup) { 5652 auto *Recent = 5653 const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl()); 5654 5655 // It is possible that during the import of the class template definition 5656 // we start the import of a fwd friend decl of the very same class template 5657 // and we add the fwd friend decl to the lookup table. But the ToTemplated 5658 // had been created earlier and by that time the lookup could not find 5659 // anything existing, so it has no previous decl. Later, (still during the 5660 // import of the fwd friend decl) we start to import the definition again 5661 // and this time the lookup finds the previous fwd friend class template. 5662 // In this case we must set up the previous decl for the templated decl. 5663 if (!ToTemplated->getPreviousDecl()) { 5664 assert(FoundByLookup->getTemplatedDecl() && 5665 "Found decl must have its templated decl set"); 5666 CXXRecordDecl *PrevTemplated = 5667 FoundByLookup->getTemplatedDecl()->getMostRecentDecl(); 5668 if (ToTemplated != PrevTemplated) 5669 ToTemplated->setPreviousDecl(PrevTemplated); 5670 } 5671 5672 D2->setPreviousDecl(Recent); 5673 } 5674 5675 return D2; 5676 } 5677 5678 ExpectedDecl ASTNodeImporter::VisitClassTemplateSpecializationDecl( 5679 ClassTemplateSpecializationDecl *D) { 5680 ClassTemplateDecl *ClassTemplate; 5681 if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate())) 5682 return std::move(Err); 5683 5684 // Import the context of this declaration. 5685 DeclContext *DC, *LexicalDC; 5686 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 5687 return std::move(Err); 5688 5689 // Import template arguments. 5690 SmallVector<TemplateArgument, 2> TemplateArgs; 5691 if (Error Err = ImportTemplateArguments( 5692 D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs)) 5693 return std::move(Err); 5694 // Try to find an existing specialization with these template arguments and 5695 // template parameter list. 5696 void *InsertPos = nullptr; 5697 ClassTemplateSpecializationDecl *PrevDecl = nullptr; 5698 ClassTemplatePartialSpecializationDecl *PartialSpec = 5699 dyn_cast<ClassTemplatePartialSpecializationDecl>(D); 5700 5701 // Import template parameters. 5702 TemplateParameterList *ToTPList = nullptr; 5703 5704 if (PartialSpec) { 5705 auto ToTPListOrErr = import(PartialSpec->getTemplateParameters()); 5706 if (!ToTPListOrErr) 5707 return ToTPListOrErr.takeError(); 5708 ToTPList = *ToTPListOrErr; 5709 PrevDecl = ClassTemplate->findPartialSpecialization(TemplateArgs, 5710 *ToTPListOrErr, 5711 InsertPos); 5712 } else 5713 PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos); 5714 5715 if (PrevDecl) { 5716 if (IsStructuralMatch(D, PrevDecl)) { 5717 CXXRecordDecl *PrevDefinition = PrevDecl->getDefinition(); 5718 if (D->isThisDeclarationADefinition() && PrevDefinition) { 5719 Importer.MapImported(D, PrevDefinition); 5720 // Import those default field initializers which have been 5721 // instantiated in the "From" context, but not in the "To" context. 5722 for (auto *FromField : D->fields()) { 5723 auto ToOrErr = import(FromField); 5724 if (!ToOrErr) 5725 return ToOrErr.takeError(); 5726 } 5727 5728 // Import those methods which have been instantiated in the 5729 // "From" context, but not in the "To" context. 5730 for (CXXMethodDecl *FromM : D->methods()) { 5731 auto ToOrErr = import(FromM); 5732 if (!ToOrErr) 5733 return ToOrErr.takeError(); 5734 } 5735 5736 // TODO Import instantiated default arguments. 5737 // TODO Import instantiated exception specifications. 5738 // 5739 // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint 5740 // what else could be fused during an AST merge. 5741 return PrevDefinition; 5742 } 5743 } else { // ODR violation. 5744 // FIXME HandleNameConflict 5745 return make_error<ASTImportError>(ASTImportError::NameConflict); 5746 } 5747 } 5748 5749 // Import the location of this declaration. 5750 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 5751 if (!BeginLocOrErr) 5752 return BeginLocOrErr.takeError(); 5753 ExpectedSLoc IdLocOrErr = import(D->getLocation()); 5754 if (!IdLocOrErr) 5755 return IdLocOrErr.takeError(); 5756 5757 // Create the specialization. 5758 ClassTemplateSpecializationDecl *D2 = nullptr; 5759 if (PartialSpec) { 5760 // Import TemplateArgumentListInfo. 5761 TemplateArgumentListInfo ToTAInfo; 5762 const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten(); 5763 if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo)) 5764 return std::move(Err); 5765 5766 QualType CanonInjType; 5767 if (Error Err = importInto( 5768 CanonInjType, PartialSpec->getInjectedSpecializationType())) 5769 return std::move(Err); 5770 CanonInjType = CanonInjType.getCanonicalType(); 5771 5772 if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>( 5773 D2, D, Importer.getToContext(), D->getTagKind(), DC, 5774 *BeginLocOrErr, *IdLocOrErr, ToTPList, ClassTemplate, 5775 llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()), 5776 ToTAInfo, CanonInjType, 5777 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl))) 5778 return D2; 5779 5780 // Update InsertPos, because preceding import calls may have invalidated 5781 // it by adding new specializations. 5782 auto *PartSpec2 = cast<ClassTemplatePartialSpecializationDecl>(D2); 5783 if (!ClassTemplate->findPartialSpecialization(TemplateArgs, ToTPList, 5784 InsertPos)) 5785 // Add this partial specialization to the class template. 5786 ClassTemplate->AddPartialSpecialization(PartSpec2, InsertPos); 5787 5788 updateLookupTableForTemplateParameters(*ToTPList); 5789 } else { // Not a partial specialization. 5790 if (GetImportedOrCreateDecl( 5791 D2, D, Importer.getToContext(), D->getTagKind(), DC, 5792 *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs, 5793 PrevDecl)) 5794 return D2; 5795 5796 // Update InsertPos, because preceding import calls may have invalidated 5797 // it by adding new specializations. 5798 if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos)) 5799 // Add this specialization to the class template. 5800 ClassTemplate->AddSpecialization(D2, InsertPos); 5801 } 5802 5803 D2->setSpecializationKind(D->getSpecializationKind()); 5804 5805 // Set the context of this specialization/instantiation. 5806 D2->setLexicalDeclContext(LexicalDC); 5807 5808 // Add to the DC only if it was an explicit specialization/instantiation. 5809 if (D2->isExplicitInstantiationOrSpecialization()) { 5810 LexicalDC->addDeclInternal(D2); 5811 } 5812 5813 if (auto BraceRangeOrErr = import(D->getBraceRange())) 5814 D2->setBraceRange(*BraceRangeOrErr); 5815 else 5816 return BraceRangeOrErr.takeError(); 5817 5818 // Import the qualifier, if any. 5819 if (auto LocOrErr = import(D->getQualifierLoc())) 5820 D2->setQualifierInfo(*LocOrErr); 5821 else 5822 return LocOrErr.takeError(); 5823 5824 if (auto *TSI = D->getTypeAsWritten()) { 5825 if (auto TInfoOrErr = import(TSI)) 5826 D2->setTypeAsWritten(*TInfoOrErr); 5827 else 5828 return TInfoOrErr.takeError(); 5829 5830 if (auto LocOrErr = import(D->getTemplateKeywordLoc())) 5831 D2->setTemplateKeywordLoc(*LocOrErr); 5832 else 5833 return LocOrErr.takeError(); 5834 5835 if (auto LocOrErr = import(D->getExternLoc())) 5836 D2->setExternLoc(*LocOrErr); 5837 else 5838 return LocOrErr.takeError(); 5839 } 5840 5841 if (D->getPointOfInstantiation().isValid()) { 5842 if (auto POIOrErr = import(D->getPointOfInstantiation())) 5843 D2->setPointOfInstantiation(*POIOrErr); 5844 else 5845 return POIOrErr.takeError(); 5846 } 5847 5848 D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind()); 5849 5850 if (D->isCompleteDefinition()) 5851 if (Error Err = ImportDefinition(D, D2)) 5852 return std::move(Err); 5853 5854 return D2; 5855 } 5856 5857 ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) { 5858 // Import the major distinguishing characteristics of this variable template. 5859 DeclContext *DC, *LexicalDC; 5860 DeclarationName Name; 5861 SourceLocation Loc; 5862 NamedDecl *ToD; 5863 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 5864 return std::move(Err); 5865 if (ToD) 5866 return ToD; 5867 5868 // We may already have a template of the same name; try to find and match it. 5869 assert(!DC->isFunctionOrMethod() && 5870 "Variable templates cannot be declared at function scope"); 5871 5872 SmallVector<NamedDecl *, 4> ConflictingDecls; 5873 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 5874 VarTemplateDecl *FoundByLookup = nullptr; 5875 for (auto *FoundDecl : FoundDecls) { 5876 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 5877 continue; 5878 5879 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(FoundDecl)) { 5880 // Use the templated decl, some linkage flags are set only there. 5881 if (!hasSameVisibilityContextAndLinkage(FoundTemplate->getTemplatedDecl(), 5882 D->getTemplatedDecl())) 5883 continue; 5884 if (IsStructuralMatch(D, FoundTemplate)) { 5885 // The Decl in the "From" context has a definition, but in the 5886 // "To" context we already have a definition. 5887 VarTemplateDecl *FoundDef = getTemplateDefinition(FoundTemplate); 5888 if (D->isThisDeclarationADefinition() && FoundDef) 5889 // FIXME Check for ODR error if the two definitions have 5890 // different initializers? 5891 return Importer.MapImported(D, FoundDef); 5892 5893 FoundByLookup = FoundTemplate; 5894 break; 5895 } 5896 ConflictingDecls.push_back(FoundDecl); 5897 } 5898 } 5899 5900 if (!ConflictingDecls.empty()) { 5901 ExpectedName NameOrErr = Importer.HandleNameConflict( 5902 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(), 5903 ConflictingDecls.size()); 5904 if (NameOrErr) 5905 Name = NameOrErr.get(); 5906 else 5907 return NameOrErr.takeError(); 5908 } 5909 5910 VarDecl *DTemplated = D->getTemplatedDecl(); 5911 5912 // Import the type. 5913 // FIXME: Value not used? 5914 ExpectedType TypeOrErr = import(DTemplated->getType()); 5915 if (!TypeOrErr) 5916 return TypeOrErr.takeError(); 5917 5918 // Create the declaration that is being templated. 5919 VarDecl *ToTemplated; 5920 if (Error Err = importInto(ToTemplated, DTemplated)) 5921 return std::move(Err); 5922 5923 // Create the variable template declaration itself. 5924 auto TemplateParamsOrErr = import(D->getTemplateParameters()); 5925 if (!TemplateParamsOrErr) 5926 return TemplateParamsOrErr.takeError(); 5927 5928 VarTemplateDecl *ToVarTD; 5929 if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc, 5930 Name, *TemplateParamsOrErr, ToTemplated)) 5931 return ToVarTD; 5932 5933 ToTemplated->setDescribedVarTemplate(ToVarTD); 5934 5935 ToVarTD->setAccess(D->getAccess()); 5936 ToVarTD->setLexicalDeclContext(LexicalDC); 5937 LexicalDC->addDeclInternal(ToVarTD); 5938 if (DC != Importer.getToContext().getTranslationUnitDecl()) 5939 updateLookupTableForTemplateParameters(**TemplateParamsOrErr); 5940 5941 if (FoundByLookup) { 5942 auto *Recent = 5943 const_cast<VarTemplateDecl *>(FoundByLookup->getMostRecentDecl()); 5944 if (!ToTemplated->getPreviousDecl()) { 5945 auto *PrevTemplated = 5946 FoundByLookup->getTemplatedDecl()->getMostRecentDecl(); 5947 if (ToTemplated != PrevTemplated) 5948 ToTemplated->setPreviousDecl(PrevTemplated); 5949 } 5950 ToVarTD->setPreviousDecl(Recent); 5951 } 5952 5953 return ToVarTD; 5954 } 5955 5956 ExpectedDecl ASTNodeImporter::VisitVarTemplateSpecializationDecl( 5957 VarTemplateSpecializationDecl *D) { 5958 // If this record has a definition in the translation unit we're coming from, 5959 // but this particular declaration is not that definition, import the 5960 // definition and map to that. 5961 VarDecl *Definition = D->getDefinition(); 5962 if (Definition && Definition != D) { 5963 if (ExpectedDecl ImportedDefOrErr = import(Definition)) 5964 return Importer.MapImported(D, *ImportedDefOrErr); 5965 else 5966 return ImportedDefOrErr.takeError(); 5967 } 5968 5969 VarTemplateDecl *VarTemplate = nullptr; 5970 if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate())) 5971 return std::move(Err); 5972 5973 // Import the context of this declaration. 5974 DeclContext *DC, *LexicalDC; 5975 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 5976 return std::move(Err); 5977 5978 // Import the location of this declaration. 5979 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 5980 if (!BeginLocOrErr) 5981 return BeginLocOrErr.takeError(); 5982 5983 auto IdLocOrErr = import(D->getLocation()); 5984 if (!IdLocOrErr) 5985 return IdLocOrErr.takeError(); 5986 5987 // Import template arguments. 5988 SmallVector<TemplateArgument, 2> TemplateArgs; 5989 if (Error Err = ImportTemplateArguments( 5990 D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs)) 5991 return std::move(Err); 5992 5993 // Try to find an existing specialization with these template arguments. 5994 void *InsertPos = nullptr; 5995 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization( 5996 TemplateArgs, InsertPos); 5997 if (D2) { 5998 // We already have a variable template specialization with these template 5999 // arguments. 6000 6001 // FIXME: Check for specialization vs. instantiation errors. 6002 6003 if (VarDecl *FoundDef = D2->getDefinition()) { 6004 if (!D->isThisDeclarationADefinition() || 6005 IsStructuralMatch(D, FoundDef)) { 6006 // The record types structurally match, or the "from" translation 6007 // unit only had a forward declaration anyway; call it the same 6008 // variable. 6009 return Importer.MapImported(D, FoundDef); 6010 } 6011 } 6012 } else { 6013 // Import the type. 6014 QualType T; 6015 if (Error Err = importInto(T, D->getType())) 6016 return std::move(Err); 6017 6018 auto TInfoOrErr = import(D->getTypeSourceInfo()); 6019 if (!TInfoOrErr) 6020 return TInfoOrErr.takeError(); 6021 6022 TemplateArgumentListInfo ToTAInfo; 6023 if (const ASTTemplateArgumentListInfo *Args = D->getTemplateArgsInfo()) { 6024 if (Error Err = ImportTemplateArgumentListInfo(*Args, ToTAInfo)) 6025 return std::move(Err); 6026 } 6027 6028 using PartVarSpecDecl = VarTemplatePartialSpecializationDecl; 6029 // Create a new specialization. 6030 if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) { 6031 // Import TemplateArgumentListInfo 6032 TemplateArgumentListInfo ArgInfos; 6033 const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten(); 6034 // NOTE: FromTAArgsAsWritten and template parameter list are non-null. 6035 if (Error Err = ImportTemplateArgumentListInfo( 6036 *FromTAArgsAsWritten, ArgInfos)) 6037 return std::move(Err); 6038 6039 auto ToTPListOrErr = import(FromPartial->getTemplateParameters()); 6040 if (!ToTPListOrErr) 6041 return ToTPListOrErr.takeError(); 6042 6043 PartVarSpecDecl *ToPartial; 6044 if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC, 6045 *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr, 6046 VarTemplate, T, *TInfoOrErr, 6047 D->getStorageClass(), TemplateArgs, ArgInfos)) 6048 return ToPartial; 6049 6050 if (Expected<PartVarSpecDecl *> ToInstOrErr = import( 6051 FromPartial->getInstantiatedFromMember())) 6052 ToPartial->setInstantiatedFromMember(*ToInstOrErr); 6053 else 6054 return ToInstOrErr.takeError(); 6055 6056 if (FromPartial->isMemberSpecialization()) 6057 ToPartial->setMemberSpecialization(); 6058 6059 D2 = ToPartial; 6060 6061 // FIXME: Use this update if VarTemplatePartialSpecializationDecl is fixed 6062 // to adopt template parameters. 6063 // updateLookupTableForTemplateParameters(**ToTPListOrErr); 6064 } else { // Full specialization 6065 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, 6066 *BeginLocOrErr, *IdLocOrErr, VarTemplate, 6067 T, *TInfoOrErr, 6068 D->getStorageClass(), TemplateArgs)) 6069 return D2; 6070 } 6071 6072 if (D->getPointOfInstantiation().isValid()) { 6073 if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation())) 6074 D2->setPointOfInstantiation(*POIOrErr); 6075 else 6076 return POIOrErr.takeError(); 6077 } 6078 6079 D2->setSpecializationKind(D->getSpecializationKind()); 6080 D2->setTemplateArgsInfo(ToTAInfo); 6081 6082 // Add this specialization to the class template. 6083 VarTemplate->AddSpecialization(D2, InsertPos); 6084 6085 // Import the qualifier, if any. 6086 if (auto LocOrErr = import(D->getQualifierLoc())) 6087 D2->setQualifierInfo(*LocOrErr); 6088 else 6089 return LocOrErr.takeError(); 6090 6091 if (D->isConstexpr()) 6092 D2->setConstexpr(true); 6093 6094 // Add the specialization to this context. 6095 D2->setLexicalDeclContext(LexicalDC); 6096 LexicalDC->addDeclInternal(D2); 6097 6098 D2->setAccess(D->getAccess()); 6099 } 6100 6101 if (Error Err = ImportInitializer(D, D2)) 6102 return std::move(Err); 6103 6104 return D2; 6105 } 6106 6107 ExpectedDecl 6108 ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 6109 DeclContext *DC, *LexicalDC; 6110 DeclarationName Name; 6111 SourceLocation Loc; 6112 NamedDecl *ToD; 6113 6114 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 6115 return std::move(Err); 6116 6117 if (ToD) 6118 return ToD; 6119 6120 const FunctionTemplateDecl *FoundByLookup = nullptr; 6121 6122 // Try to find a function in our own ("to") context with the same name, same 6123 // type, and in the same context as the function we're importing. 6124 // FIXME Split this into a separate function. 6125 if (!LexicalDC->isFunctionOrMethod()) { 6126 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend; 6127 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 6128 for (auto *FoundDecl : FoundDecls) { 6129 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 6130 continue; 6131 6132 if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(FoundDecl)) { 6133 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D)) 6134 continue; 6135 if (IsStructuralMatch(D, FoundTemplate)) { 6136 FunctionTemplateDecl *TemplateWithDef = 6137 getTemplateDefinition(FoundTemplate); 6138 if (D->isThisDeclarationADefinition() && TemplateWithDef) 6139 return Importer.MapImported(D, TemplateWithDef); 6140 6141 FoundByLookup = FoundTemplate; 6142 break; 6143 // TODO: handle conflicting names 6144 } 6145 } 6146 } 6147 } 6148 6149 auto ParamsOrErr = import(D->getTemplateParameters()); 6150 if (!ParamsOrErr) 6151 return ParamsOrErr.takeError(); 6152 TemplateParameterList *Params = *ParamsOrErr; 6153 6154 FunctionDecl *TemplatedFD; 6155 if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl())) 6156 return std::move(Err); 6157 6158 // At creation of the template the template parameters are "adopted" 6159 // (DeclContext is changed). After this possible change the lookup table 6160 // must be updated. 6161 // At deduction guides the DeclContext of the template parameters may be 6162 // different from what we would expect, it may be the class template, or a 6163 // probably different CXXDeductionGuideDecl. This may come from the fact that 6164 // the template parameter objects may be shared between deduction guides or 6165 // the class template, and at creation of multiple FunctionTemplateDecl 6166 // objects (for deduction guides) the same parameters are re-used. The 6167 // "adoption" happens multiple times with different parent, even recursively 6168 // for TemplateTemplateParmDecl. The same happens at import when the 6169 // FunctionTemplateDecl objects are created, but in different order. 6170 // In this way the DeclContext of these template parameters is not necessarily 6171 // the same as in the "from" context. 6172 SmallVector<DeclContext *, 2> OldParamDC; 6173 OldParamDC.reserve(Params->size()); 6174 llvm::transform(*Params, std::back_inserter(OldParamDC), 6175 [](NamedDecl *ND) { return ND->getDeclContext(); }); 6176 6177 FunctionTemplateDecl *ToFunc; 6178 if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name, 6179 Params, TemplatedFD)) 6180 return ToFunc; 6181 6182 TemplatedFD->setDescribedFunctionTemplate(ToFunc); 6183 6184 ToFunc->setAccess(D->getAccess()); 6185 ToFunc->setLexicalDeclContext(LexicalDC); 6186 LexicalDC->addDeclInternal(ToFunc); 6187 6188 ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable(); 6189 if (LT && !OldParamDC.empty()) { 6190 for (unsigned int I = 0; I < OldParamDC.size(); ++I) 6191 LT->updateForced(Params->getParam(I), OldParamDC[I]); 6192 } 6193 6194 if (FoundByLookup) { 6195 auto *Recent = 6196 const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl()); 6197 if (!TemplatedFD->getPreviousDecl()) { 6198 assert(FoundByLookup->getTemplatedDecl() && 6199 "Found decl must have its templated decl set"); 6200 auto *PrevTemplated = 6201 FoundByLookup->getTemplatedDecl()->getMostRecentDecl(); 6202 if (TemplatedFD != PrevTemplated) 6203 TemplatedFD->setPreviousDecl(PrevTemplated); 6204 } 6205 ToFunc->setPreviousDecl(Recent); 6206 } 6207 6208 return ToFunc; 6209 } 6210 6211 //---------------------------------------------------------------------------- 6212 // Import Statements 6213 //---------------------------------------------------------------------------- 6214 6215 ExpectedStmt ASTNodeImporter::VisitStmt(Stmt *S) { 6216 Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node) 6217 << S->getStmtClassName(); 6218 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 6219 } 6220 6221 6222 ExpectedStmt ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) { 6223 if (Importer.returnWithErrorInTest()) 6224 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 6225 SmallVector<IdentifierInfo *, 4> Names; 6226 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) { 6227 IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I)); 6228 // ToII is nullptr when no symbolic name is given for output operand 6229 // see ParseStmtAsm::ParseAsmOperandsOpt 6230 Names.push_back(ToII); 6231 } 6232 6233 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) { 6234 IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I)); 6235 // ToII is nullptr when no symbolic name is given for input operand 6236 // see ParseStmtAsm::ParseAsmOperandsOpt 6237 Names.push_back(ToII); 6238 } 6239 6240 SmallVector<StringLiteral *, 4> Clobbers; 6241 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) { 6242 if (auto ClobberOrErr = import(S->getClobberStringLiteral(I))) 6243 Clobbers.push_back(*ClobberOrErr); 6244 else 6245 return ClobberOrErr.takeError(); 6246 6247 } 6248 6249 SmallVector<StringLiteral *, 4> Constraints; 6250 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) { 6251 if (auto OutputOrErr = import(S->getOutputConstraintLiteral(I))) 6252 Constraints.push_back(*OutputOrErr); 6253 else 6254 return OutputOrErr.takeError(); 6255 } 6256 6257 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) { 6258 if (auto InputOrErr = import(S->getInputConstraintLiteral(I))) 6259 Constraints.push_back(*InputOrErr); 6260 else 6261 return InputOrErr.takeError(); 6262 } 6263 6264 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs() + 6265 S->getNumLabels()); 6266 if (Error Err = ImportContainerChecked(S->outputs(), Exprs)) 6267 return std::move(Err); 6268 6269 if (Error Err = 6270 ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs())) 6271 return std::move(Err); 6272 6273 if (Error Err = ImportArrayChecked( 6274 S->labels(), Exprs.begin() + S->getNumOutputs() + S->getNumInputs())) 6275 return std::move(Err); 6276 6277 ExpectedSLoc AsmLocOrErr = import(S->getAsmLoc()); 6278 if (!AsmLocOrErr) 6279 return AsmLocOrErr.takeError(); 6280 auto AsmStrOrErr = import(S->getAsmString()); 6281 if (!AsmStrOrErr) 6282 return AsmStrOrErr.takeError(); 6283 ExpectedSLoc RParenLocOrErr = import(S->getRParenLoc()); 6284 if (!RParenLocOrErr) 6285 return RParenLocOrErr.takeError(); 6286 6287 return new (Importer.getToContext()) GCCAsmStmt( 6288 Importer.getToContext(), 6289 *AsmLocOrErr, 6290 S->isSimple(), 6291 S->isVolatile(), 6292 S->getNumOutputs(), 6293 S->getNumInputs(), 6294 Names.data(), 6295 Constraints.data(), 6296 Exprs.data(), 6297 *AsmStrOrErr, 6298 S->getNumClobbers(), 6299 Clobbers.data(), 6300 S->getNumLabels(), 6301 *RParenLocOrErr); 6302 } 6303 6304 ExpectedStmt ASTNodeImporter::VisitDeclStmt(DeclStmt *S) { 6305 6306 Error Err = Error::success(); 6307 auto ToDG = importChecked(Err, S->getDeclGroup()); 6308 auto ToBeginLoc = importChecked(Err, S->getBeginLoc()); 6309 auto ToEndLoc = importChecked(Err, S->getEndLoc()); 6310 if (Err) 6311 return std::move(Err); 6312 return new (Importer.getToContext()) DeclStmt(ToDG, ToBeginLoc, ToEndLoc); 6313 } 6314 6315 ExpectedStmt ASTNodeImporter::VisitNullStmt(NullStmt *S) { 6316 ExpectedSLoc ToSemiLocOrErr = import(S->getSemiLoc()); 6317 if (!ToSemiLocOrErr) 6318 return ToSemiLocOrErr.takeError(); 6319 return new (Importer.getToContext()) NullStmt( 6320 *ToSemiLocOrErr, S->hasLeadingEmptyMacro()); 6321 } 6322 6323 ExpectedStmt ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) { 6324 SmallVector<Stmt *, 8> ToStmts(S->size()); 6325 6326 if (Error Err = ImportContainerChecked(S->body(), ToStmts)) 6327 return std::move(Err); 6328 6329 ExpectedSLoc ToLBracLocOrErr = import(S->getLBracLoc()); 6330 if (!ToLBracLocOrErr) 6331 return ToLBracLocOrErr.takeError(); 6332 6333 ExpectedSLoc ToRBracLocOrErr = import(S->getRBracLoc()); 6334 if (!ToRBracLocOrErr) 6335 return ToRBracLocOrErr.takeError(); 6336 6337 FPOptionsOverride FPO = 6338 S->hasStoredFPFeatures() ? S->getStoredFPFeatures() : FPOptionsOverride(); 6339 return CompoundStmt::Create(Importer.getToContext(), ToStmts, FPO, 6340 *ToLBracLocOrErr, *ToRBracLocOrErr); 6341 } 6342 6343 ExpectedStmt ASTNodeImporter::VisitCaseStmt(CaseStmt *S) { 6344 6345 Error Err = Error::success(); 6346 auto ToLHS = importChecked(Err, S->getLHS()); 6347 auto ToRHS = importChecked(Err, S->getRHS()); 6348 auto ToSubStmt = importChecked(Err, S->getSubStmt()); 6349 auto ToCaseLoc = importChecked(Err, S->getCaseLoc()); 6350 auto ToEllipsisLoc = importChecked(Err, S->getEllipsisLoc()); 6351 auto ToColonLoc = importChecked(Err, S->getColonLoc()); 6352 if (Err) 6353 return std::move(Err); 6354 6355 auto *ToStmt = CaseStmt::Create(Importer.getToContext(), ToLHS, ToRHS, 6356 ToCaseLoc, ToEllipsisLoc, ToColonLoc); 6357 ToStmt->setSubStmt(ToSubStmt); 6358 6359 return ToStmt; 6360 } 6361 6362 ExpectedStmt ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) { 6363 6364 Error Err = Error::success(); 6365 auto ToDefaultLoc = importChecked(Err, S->getDefaultLoc()); 6366 auto ToColonLoc = importChecked(Err, S->getColonLoc()); 6367 auto ToSubStmt = importChecked(Err, S->getSubStmt()); 6368 if (Err) 6369 return std::move(Err); 6370 6371 return new (Importer.getToContext()) DefaultStmt( 6372 ToDefaultLoc, ToColonLoc, ToSubStmt); 6373 } 6374 6375 ExpectedStmt ASTNodeImporter::VisitLabelStmt(LabelStmt *S) { 6376 6377 Error Err = Error::success(); 6378 auto ToIdentLoc = importChecked(Err, S->getIdentLoc()); 6379 auto ToLabelDecl = importChecked(Err, S->getDecl()); 6380 auto ToSubStmt = importChecked(Err, S->getSubStmt()); 6381 if (Err) 6382 return std::move(Err); 6383 6384 return new (Importer.getToContext()) LabelStmt( 6385 ToIdentLoc, ToLabelDecl, ToSubStmt); 6386 } 6387 6388 ExpectedStmt ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) { 6389 ExpectedSLoc ToAttrLocOrErr = import(S->getAttrLoc()); 6390 if (!ToAttrLocOrErr) 6391 return ToAttrLocOrErr.takeError(); 6392 ArrayRef<const Attr*> FromAttrs(S->getAttrs()); 6393 SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size()); 6394 if (Error Err = ImportContainerChecked(FromAttrs, ToAttrs)) 6395 return std::move(Err); 6396 ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt()); 6397 if (!ToSubStmtOrErr) 6398 return ToSubStmtOrErr.takeError(); 6399 6400 return AttributedStmt::Create( 6401 Importer.getToContext(), *ToAttrLocOrErr, ToAttrs, *ToSubStmtOrErr); 6402 } 6403 6404 ExpectedStmt ASTNodeImporter::VisitIfStmt(IfStmt *S) { 6405 6406 Error Err = Error::success(); 6407 auto ToIfLoc = importChecked(Err, S->getIfLoc()); 6408 auto ToInit = importChecked(Err, S->getInit()); 6409 auto ToConditionVariable = importChecked(Err, S->getConditionVariable()); 6410 auto ToCond = importChecked(Err, S->getCond()); 6411 auto ToLParenLoc = importChecked(Err, S->getLParenLoc()); 6412 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6413 auto ToThen = importChecked(Err, S->getThen()); 6414 auto ToElseLoc = importChecked(Err, S->getElseLoc()); 6415 auto ToElse = importChecked(Err, S->getElse()); 6416 if (Err) 6417 return std::move(Err); 6418 6419 return IfStmt::Create(Importer.getToContext(), ToIfLoc, S->getStatementKind(), 6420 ToInit, ToConditionVariable, ToCond, ToLParenLoc, 6421 ToRParenLoc, ToThen, ToElseLoc, ToElse); 6422 } 6423 6424 ExpectedStmt ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) { 6425 6426 Error Err = Error::success(); 6427 auto ToInit = importChecked(Err, S->getInit()); 6428 auto ToConditionVariable = importChecked(Err, S->getConditionVariable()); 6429 auto ToCond = importChecked(Err, S->getCond()); 6430 auto ToLParenLoc = importChecked(Err, S->getLParenLoc()); 6431 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6432 auto ToBody = importChecked(Err, S->getBody()); 6433 auto ToSwitchLoc = importChecked(Err, S->getSwitchLoc()); 6434 if (Err) 6435 return std::move(Err); 6436 6437 auto *ToStmt = 6438 SwitchStmt::Create(Importer.getToContext(), ToInit, ToConditionVariable, 6439 ToCond, ToLParenLoc, ToRParenLoc); 6440 ToStmt->setBody(ToBody); 6441 ToStmt->setSwitchLoc(ToSwitchLoc); 6442 6443 // Now we have to re-chain the cases. 6444 SwitchCase *LastChainedSwitchCase = nullptr; 6445 for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr; 6446 SC = SC->getNextSwitchCase()) { 6447 Expected<SwitchCase *> ToSCOrErr = import(SC); 6448 if (!ToSCOrErr) 6449 return ToSCOrErr.takeError(); 6450 if (LastChainedSwitchCase) 6451 LastChainedSwitchCase->setNextSwitchCase(*ToSCOrErr); 6452 else 6453 ToStmt->setSwitchCaseList(*ToSCOrErr); 6454 LastChainedSwitchCase = *ToSCOrErr; 6455 } 6456 6457 return ToStmt; 6458 } 6459 6460 ExpectedStmt ASTNodeImporter::VisitWhileStmt(WhileStmt *S) { 6461 6462 Error Err = Error::success(); 6463 auto ToConditionVariable = importChecked(Err, S->getConditionVariable()); 6464 auto ToCond = importChecked(Err, S->getCond()); 6465 auto ToBody = importChecked(Err, S->getBody()); 6466 auto ToWhileLoc = importChecked(Err, S->getWhileLoc()); 6467 auto ToLParenLoc = importChecked(Err, S->getLParenLoc()); 6468 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6469 if (Err) 6470 return std::move(Err); 6471 6472 return WhileStmt::Create(Importer.getToContext(), ToConditionVariable, ToCond, 6473 ToBody, ToWhileLoc, ToLParenLoc, ToRParenLoc); 6474 } 6475 6476 ExpectedStmt ASTNodeImporter::VisitDoStmt(DoStmt *S) { 6477 6478 Error Err = Error::success(); 6479 auto ToBody = importChecked(Err, S->getBody()); 6480 auto ToCond = importChecked(Err, S->getCond()); 6481 auto ToDoLoc = importChecked(Err, S->getDoLoc()); 6482 auto ToWhileLoc = importChecked(Err, S->getWhileLoc()); 6483 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6484 if (Err) 6485 return std::move(Err); 6486 6487 return new (Importer.getToContext()) DoStmt( 6488 ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc); 6489 } 6490 6491 ExpectedStmt ASTNodeImporter::VisitForStmt(ForStmt *S) { 6492 6493 Error Err = Error::success(); 6494 auto ToInit = importChecked(Err, S->getInit()); 6495 auto ToCond = importChecked(Err, S->getCond()); 6496 auto ToConditionVariable = importChecked(Err, S->getConditionVariable()); 6497 auto ToInc = importChecked(Err, S->getInc()); 6498 auto ToBody = importChecked(Err, S->getBody()); 6499 auto ToForLoc = importChecked(Err, S->getForLoc()); 6500 auto ToLParenLoc = importChecked(Err, S->getLParenLoc()); 6501 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6502 if (Err) 6503 return std::move(Err); 6504 6505 return new (Importer.getToContext()) ForStmt( 6506 Importer.getToContext(), 6507 ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc, ToLParenLoc, 6508 ToRParenLoc); 6509 } 6510 6511 ExpectedStmt ASTNodeImporter::VisitGotoStmt(GotoStmt *S) { 6512 6513 Error Err = Error::success(); 6514 auto ToLabel = importChecked(Err, S->getLabel()); 6515 auto ToGotoLoc = importChecked(Err, S->getGotoLoc()); 6516 auto ToLabelLoc = importChecked(Err, S->getLabelLoc()); 6517 if (Err) 6518 return std::move(Err); 6519 6520 return new (Importer.getToContext()) GotoStmt( 6521 ToLabel, ToGotoLoc, ToLabelLoc); 6522 } 6523 6524 ExpectedStmt ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) { 6525 6526 Error Err = Error::success(); 6527 auto ToGotoLoc = importChecked(Err, S->getGotoLoc()); 6528 auto ToStarLoc = importChecked(Err, S->getStarLoc()); 6529 auto ToTarget = importChecked(Err, S->getTarget()); 6530 if (Err) 6531 return std::move(Err); 6532 6533 return new (Importer.getToContext()) IndirectGotoStmt( 6534 ToGotoLoc, ToStarLoc, ToTarget); 6535 } 6536 6537 ExpectedStmt ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) { 6538 ExpectedSLoc ToContinueLocOrErr = import(S->getContinueLoc()); 6539 if (!ToContinueLocOrErr) 6540 return ToContinueLocOrErr.takeError(); 6541 return new (Importer.getToContext()) ContinueStmt(*ToContinueLocOrErr); 6542 } 6543 6544 ExpectedStmt ASTNodeImporter::VisitBreakStmt(BreakStmt *S) { 6545 auto ToBreakLocOrErr = import(S->getBreakLoc()); 6546 if (!ToBreakLocOrErr) 6547 return ToBreakLocOrErr.takeError(); 6548 return new (Importer.getToContext()) BreakStmt(*ToBreakLocOrErr); 6549 } 6550 6551 ExpectedStmt ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) { 6552 6553 Error Err = Error::success(); 6554 auto ToReturnLoc = importChecked(Err, S->getReturnLoc()); 6555 auto ToRetValue = importChecked(Err, S->getRetValue()); 6556 auto ToNRVOCandidate = importChecked(Err, S->getNRVOCandidate()); 6557 if (Err) 6558 return std::move(Err); 6559 6560 return ReturnStmt::Create(Importer.getToContext(), ToReturnLoc, ToRetValue, 6561 ToNRVOCandidate); 6562 } 6563 6564 ExpectedStmt ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) { 6565 6566 Error Err = Error::success(); 6567 auto ToCatchLoc = importChecked(Err, S->getCatchLoc()); 6568 auto ToExceptionDecl = importChecked(Err, S->getExceptionDecl()); 6569 auto ToHandlerBlock = importChecked(Err, S->getHandlerBlock()); 6570 if (Err) 6571 return std::move(Err); 6572 6573 return new (Importer.getToContext()) CXXCatchStmt ( 6574 ToCatchLoc, ToExceptionDecl, ToHandlerBlock); 6575 } 6576 6577 ExpectedStmt ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) { 6578 ExpectedSLoc ToTryLocOrErr = import(S->getTryLoc()); 6579 if (!ToTryLocOrErr) 6580 return ToTryLocOrErr.takeError(); 6581 6582 ExpectedStmt ToTryBlockOrErr = import(S->getTryBlock()); 6583 if (!ToTryBlockOrErr) 6584 return ToTryBlockOrErr.takeError(); 6585 6586 SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers()); 6587 for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) { 6588 CXXCatchStmt *FromHandler = S->getHandler(HI); 6589 if (auto ToHandlerOrErr = import(FromHandler)) 6590 ToHandlers[HI] = *ToHandlerOrErr; 6591 else 6592 return ToHandlerOrErr.takeError(); 6593 } 6594 6595 return CXXTryStmt::Create( 6596 Importer.getToContext(), *ToTryLocOrErr,*ToTryBlockOrErr, ToHandlers); 6597 } 6598 6599 ExpectedStmt ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) { 6600 6601 Error Err = Error::success(); 6602 auto ToInit = importChecked(Err, S->getInit()); 6603 auto ToRangeStmt = importChecked(Err, S->getRangeStmt()); 6604 auto ToBeginStmt = importChecked(Err, S->getBeginStmt()); 6605 auto ToEndStmt = importChecked(Err, S->getEndStmt()); 6606 auto ToCond = importChecked(Err, S->getCond()); 6607 auto ToInc = importChecked(Err, S->getInc()); 6608 auto ToLoopVarStmt = importChecked(Err, S->getLoopVarStmt()); 6609 auto ToBody = importChecked(Err, S->getBody()); 6610 auto ToForLoc = importChecked(Err, S->getForLoc()); 6611 auto ToCoawaitLoc = importChecked(Err, S->getCoawaitLoc()); 6612 auto ToColonLoc = importChecked(Err, S->getColonLoc()); 6613 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6614 if (Err) 6615 return std::move(Err); 6616 6617 return new (Importer.getToContext()) CXXForRangeStmt( 6618 ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt, 6619 ToBody, ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc); 6620 } 6621 6622 ExpectedStmt 6623 ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) { 6624 Error Err = Error::success(); 6625 auto ToElement = importChecked(Err, S->getElement()); 6626 auto ToCollection = importChecked(Err, S->getCollection()); 6627 auto ToBody = importChecked(Err, S->getBody()); 6628 auto ToForLoc = importChecked(Err, S->getForLoc()); 6629 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6630 if (Err) 6631 return std::move(Err); 6632 6633 return new (Importer.getToContext()) ObjCForCollectionStmt(ToElement, 6634 ToCollection, 6635 ToBody, 6636 ToForLoc, 6637 ToRParenLoc); 6638 } 6639 6640 ExpectedStmt ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) { 6641 6642 Error Err = Error::success(); 6643 auto ToAtCatchLoc = importChecked(Err, S->getAtCatchLoc()); 6644 auto ToRParenLoc = importChecked(Err, S->getRParenLoc()); 6645 auto ToCatchParamDecl = importChecked(Err, S->getCatchParamDecl()); 6646 auto ToCatchBody = importChecked(Err, S->getCatchBody()); 6647 if (Err) 6648 return std::move(Err); 6649 6650 return new (Importer.getToContext()) ObjCAtCatchStmt ( 6651 ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody); 6652 } 6653 6654 ExpectedStmt ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) { 6655 ExpectedSLoc ToAtFinallyLocOrErr = import(S->getAtFinallyLoc()); 6656 if (!ToAtFinallyLocOrErr) 6657 return ToAtFinallyLocOrErr.takeError(); 6658 ExpectedStmt ToAtFinallyStmtOrErr = import(S->getFinallyBody()); 6659 if (!ToAtFinallyStmtOrErr) 6660 return ToAtFinallyStmtOrErr.takeError(); 6661 return new (Importer.getToContext()) ObjCAtFinallyStmt(*ToAtFinallyLocOrErr, 6662 *ToAtFinallyStmtOrErr); 6663 } 6664 6665 ExpectedStmt ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) { 6666 6667 Error Err = Error::success(); 6668 auto ToAtTryLoc = importChecked(Err, S->getAtTryLoc()); 6669 auto ToTryBody = importChecked(Err, S->getTryBody()); 6670 auto ToFinallyStmt = importChecked(Err, S->getFinallyStmt()); 6671 if (Err) 6672 return std::move(Err); 6673 6674 SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts()); 6675 for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) { 6676 ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI); 6677 if (ExpectedStmt ToCatchStmtOrErr = import(FromCatchStmt)) 6678 ToCatchStmts[CI] = *ToCatchStmtOrErr; 6679 else 6680 return ToCatchStmtOrErr.takeError(); 6681 } 6682 6683 return ObjCAtTryStmt::Create(Importer.getToContext(), 6684 ToAtTryLoc, ToTryBody, 6685 ToCatchStmts.begin(), ToCatchStmts.size(), 6686 ToFinallyStmt); 6687 } 6688 6689 ExpectedStmt 6690 ASTNodeImporter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) { 6691 6692 Error Err = Error::success(); 6693 auto ToAtSynchronizedLoc = importChecked(Err, S->getAtSynchronizedLoc()); 6694 auto ToSynchExpr = importChecked(Err, S->getSynchExpr()); 6695 auto ToSynchBody = importChecked(Err, S->getSynchBody()); 6696 if (Err) 6697 return std::move(Err); 6698 6699 return new (Importer.getToContext()) ObjCAtSynchronizedStmt( 6700 ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody); 6701 } 6702 6703 ExpectedStmt ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) { 6704 ExpectedSLoc ToThrowLocOrErr = import(S->getThrowLoc()); 6705 if (!ToThrowLocOrErr) 6706 return ToThrowLocOrErr.takeError(); 6707 ExpectedExpr ToThrowExprOrErr = import(S->getThrowExpr()); 6708 if (!ToThrowExprOrErr) 6709 return ToThrowExprOrErr.takeError(); 6710 return new (Importer.getToContext()) ObjCAtThrowStmt( 6711 *ToThrowLocOrErr, *ToThrowExprOrErr); 6712 } 6713 6714 ExpectedStmt ASTNodeImporter::VisitObjCAutoreleasePoolStmt( 6715 ObjCAutoreleasePoolStmt *S) { 6716 ExpectedSLoc ToAtLocOrErr = import(S->getAtLoc()); 6717 if (!ToAtLocOrErr) 6718 return ToAtLocOrErr.takeError(); 6719 ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt()); 6720 if (!ToSubStmtOrErr) 6721 return ToSubStmtOrErr.takeError(); 6722 return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(*ToAtLocOrErr, 6723 *ToSubStmtOrErr); 6724 } 6725 6726 //---------------------------------------------------------------------------- 6727 // Import Expressions 6728 //---------------------------------------------------------------------------- 6729 ExpectedStmt ASTNodeImporter::VisitExpr(Expr *E) { 6730 Importer.FromDiag(E->getBeginLoc(), diag::err_unsupported_ast_node) 6731 << E->getStmtClassName(); 6732 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 6733 } 6734 6735 ExpectedStmt ASTNodeImporter::VisitSourceLocExpr(SourceLocExpr *E) { 6736 Error Err = Error::success(); 6737 auto ToType = importChecked(Err, E->getType()); 6738 auto BLoc = importChecked(Err, E->getBeginLoc()); 6739 auto RParenLoc = importChecked(Err, E->getEndLoc()); 6740 if (Err) 6741 return std::move(Err); 6742 auto ParentContextOrErr = Importer.ImportContext(E->getParentContext()); 6743 if (!ParentContextOrErr) 6744 return ParentContextOrErr.takeError(); 6745 6746 return new (Importer.getToContext()) 6747 SourceLocExpr(Importer.getToContext(), E->getIdentKind(), ToType, BLoc, 6748 RParenLoc, *ParentContextOrErr); 6749 } 6750 6751 ExpectedStmt ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) { 6752 6753 Error Err = Error::success(); 6754 auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc()); 6755 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 6756 auto ToWrittenTypeInfo = importChecked(Err, E->getWrittenTypeInfo()); 6757 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 6758 auto ToType = importChecked(Err, E->getType()); 6759 if (Err) 6760 return std::move(Err); 6761 6762 return new (Importer.getToContext()) VAArgExpr( 6763 ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType, 6764 E->isMicrosoftABI()); 6765 } 6766 6767 ExpectedStmt ASTNodeImporter::VisitChooseExpr(ChooseExpr *E) { 6768 6769 Error Err = Error::success(); 6770 auto ToCond = importChecked(Err, E->getCond()); 6771 auto ToLHS = importChecked(Err, E->getLHS()); 6772 auto ToRHS = importChecked(Err, E->getRHS()); 6773 auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc()); 6774 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 6775 auto ToType = importChecked(Err, E->getType()); 6776 if (Err) 6777 return std::move(Err); 6778 6779 ExprValueKind VK = E->getValueKind(); 6780 ExprObjectKind OK = E->getObjectKind(); 6781 6782 // The value of CondIsTrue only matters if the value is not 6783 // condition-dependent. 6784 bool CondIsTrue = !E->isConditionDependent() && E->isConditionTrue(); 6785 6786 return new (Importer.getToContext()) 6787 ChooseExpr(ToBuiltinLoc, ToCond, ToLHS, ToRHS, ToType, VK, OK, 6788 ToRParenLoc, CondIsTrue); 6789 } 6790 6791 ExpectedStmt ASTNodeImporter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) { 6792 Error Err = Error::success(); 6793 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 6794 auto ToBeginLoc = importChecked(Err, E->getBeginLoc()); 6795 auto ToType = importChecked(Err, E->getType()); 6796 const unsigned NumSubExprs = E->getNumSubExprs(); 6797 6798 llvm::SmallVector<Expr *, 8> ToSubExprs; 6799 llvm::ArrayRef<Expr *> FromSubExprs(E->getSubExprs(), NumSubExprs); 6800 ToSubExprs.resize(NumSubExprs); 6801 6802 if ((Err = ImportContainerChecked(FromSubExprs, ToSubExprs))) 6803 return std::move(Err); 6804 6805 return new (Importer.getToContext()) ShuffleVectorExpr( 6806 Importer.getToContext(), ToSubExprs, ToType, ToBeginLoc, ToRParenLoc); 6807 } 6808 6809 ExpectedStmt ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) { 6810 ExpectedType TypeOrErr = import(E->getType()); 6811 if (!TypeOrErr) 6812 return TypeOrErr.takeError(); 6813 6814 ExpectedSLoc BeginLocOrErr = import(E->getBeginLoc()); 6815 if (!BeginLocOrErr) 6816 return BeginLocOrErr.takeError(); 6817 6818 return new (Importer.getToContext()) GNUNullExpr(*TypeOrErr, *BeginLocOrErr); 6819 } 6820 6821 ExpectedStmt 6822 ASTNodeImporter::VisitGenericSelectionExpr(GenericSelectionExpr *E) { 6823 Error Err = Error::success(); 6824 auto ToGenericLoc = importChecked(Err, E->getGenericLoc()); 6825 auto *ToControllingExpr = importChecked(Err, E->getControllingExpr()); 6826 auto ToDefaultLoc = importChecked(Err, E->getDefaultLoc()); 6827 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 6828 if (Err) 6829 return std::move(Err); 6830 6831 ArrayRef<const TypeSourceInfo *> FromAssocTypes(E->getAssocTypeSourceInfos()); 6832 SmallVector<TypeSourceInfo *, 1> ToAssocTypes(FromAssocTypes.size()); 6833 if (Error Err = ImportContainerChecked(FromAssocTypes, ToAssocTypes)) 6834 return std::move(Err); 6835 6836 ArrayRef<const Expr *> FromAssocExprs(E->getAssocExprs()); 6837 SmallVector<Expr *, 1> ToAssocExprs(FromAssocExprs.size()); 6838 if (Error Err = ImportContainerChecked(FromAssocExprs, ToAssocExprs)) 6839 return std::move(Err); 6840 6841 const ASTContext &ToCtx = Importer.getToContext(); 6842 if (E->isResultDependent()) { 6843 return GenericSelectionExpr::Create( 6844 ToCtx, ToGenericLoc, ToControllingExpr, 6845 llvm::makeArrayRef(ToAssocTypes), llvm::makeArrayRef(ToAssocExprs), 6846 ToDefaultLoc, ToRParenLoc, E->containsUnexpandedParameterPack()); 6847 } 6848 6849 return GenericSelectionExpr::Create( 6850 ToCtx, ToGenericLoc, ToControllingExpr, llvm::makeArrayRef(ToAssocTypes), 6851 llvm::makeArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc, 6852 E->containsUnexpandedParameterPack(), E->getResultIndex()); 6853 } 6854 6855 ExpectedStmt ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) { 6856 6857 Error Err = Error::success(); 6858 auto ToBeginLoc = importChecked(Err, E->getBeginLoc()); 6859 auto ToType = importChecked(Err, E->getType()); 6860 auto ToFunctionName = importChecked(Err, E->getFunctionName()); 6861 if (Err) 6862 return std::move(Err); 6863 6864 return PredefinedExpr::Create(Importer.getToContext(), ToBeginLoc, ToType, 6865 E->getIdentKind(), ToFunctionName); 6866 } 6867 6868 ExpectedStmt ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) { 6869 6870 Error Err = Error::success(); 6871 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc()); 6872 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc()); 6873 auto ToDecl = importChecked(Err, E->getDecl()); 6874 auto ToLocation = importChecked(Err, E->getLocation()); 6875 auto ToType = importChecked(Err, E->getType()); 6876 if (Err) 6877 return std::move(Err); 6878 6879 NamedDecl *ToFoundD = nullptr; 6880 if (E->getDecl() != E->getFoundDecl()) { 6881 auto FoundDOrErr = import(E->getFoundDecl()); 6882 if (!FoundDOrErr) 6883 return FoundDOrErr.takeError(); 6884 ToFoundD = *FoundDOrErr; 6885 } 6886 6887 TemplateArgumentListInfo ToTAInfo; 6888 TemplateArgumentListInfo *ToResInfo = nullptr; 6889 if (E->hasExplicitTemplateArgs()) { 6890 if (Error Err = 6891 ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(), 6892 E->template_arguments(), ToTAInfo)) 6893 return std::move(Err); 6894 ToResInfo = &ToTAInfo; 6895 } 6896 6897 auto *ToE = DeclRefExpr::Create( 6898 Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, ToDecl, 6899 E->refersToEnclosingVariableOrCapture(), ToLocation, ToType, 6900 E->getValueKind(), ToFoundD, ToResInfo, E->isNonOdrUse()); 6901 if (E->hadMultipleCandidates()) 6902 ToE->setHadMultipleCandidates(true); 6903 return ToE; 6904 } 6905 6906 ExpectedStmt ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { 6907 ExpectedType TypeOrErr = import(E->getType()); 6908 if (!TypeOrErr) 6909 return TypeOrErr.takeError(); 6910 6911 return new (Importer.getToContext()) ImplicitValueInitExpr(*TypeOrErr); 6912 } 6913 6914 ExpectedStmt ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *E) { 6915 ExpectedExpr ToInitOrErr = import(E->getInit()); 6916 if (!ToInitOrErr) 6917 return ToInitOrErr.takeError(); 6918 6919 ExpectedSLoc ToEqualOrColonLocOrErr = import(E->getEqualOrColonLoc()); 6920 if (!ToEqualOrColonLocOrErr) 6921 return ToEqualOrColonLocOrErr.takeError(); 6922 6923 SmallVector<Expr *, 4> ToIndexExprs(E->getNumSubExprs() - 1); 6924 // List elements from the second, the first is Init itself 6925 for (unsigned I = 1, N = E->getNumSubExprs(); I < N; I++) { 6926 if (ExpectedExpr ToArgOrErr = import(E->getSubExpr(I))) 6927 ToIndexExprs[I - 1] = *ToArgOrErr; 6928 else 6929 return ToArgOrErr.takeError(); 6930 } 6931 6932 SmallVector<Designator, 4> ToDesignators(E->size()); 6933 if (Error Err = ImportContainerChecked(E->designators(), ToDesignators)) 6934 return std::move(Err); 6935 6936 return DesignatedInitExpr::Create( 6937 Importer.getToContext(), ToDesignators, 6938 ToIndexExprs, *ToEqualOrColonLocOrErr, 6939 E->usesGNUSyntax(), *ToInitOrErr); 6940 } 6941 6942 ExpectedStmt 6943 ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) { 6944 ExpectedType ToTypeOrErr = import(E->getType()); 6945 if (!ToTypeOrErr) 6946 return ToTypeOrErr.takeError(); 6947 6948 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 6949 if (!ToLocationOrErr) 6950 return ToLocationOrErr.takeError(); 6951 6952 return new (Importer.getToContext()) CXXNullPtrLiteralExpr( 6953 *ToTypeOrErr, *ToLocationOrErr); 6954 } 6955 6956 ExpectedStmt ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) { 6957 ExpectedType ToTypeOrErr = import(E->getType()); 6958 if (!ToTypeOrErr) 6959 return ToTypeOrErr.takeError(); 6960 6961 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 6962 if (!ToLocationOrErr) 6963 return ToLocationOrErr.takeError(); 6964 6965 return IntegerLiteral::Create( 6966 Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr); 6967 } 6968 6969 6970 ExpectedStmt ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) { 6971 ExpectedType ToTypeOrErr = import(E->getType()); 6972 if (!ToTypeOrErr) 6973 return ToTypeOrErr.takeError(); 6974 6975 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 6976 if (!ToLocationOrErr) 6977 return ToLocationOrErr.takeError(); 6978 6979 return FloatingLiteral::Create( 6980 Importer.getToContext(), E->getValue(), E->isExact(), 6981 *ToTypeOrErr, *ToLocationOrErr); 6982 } 6983 6984 ExpectedStmt ASTNodeImporter::VisitImaginaryLiteral(ImaginaryLiteral *E) { 6985 auto ToTypeOrErr = import(E->getType()); 6986 if (!ToTypeOrErr) 6987 return ToTypeOrErr.takeError(); 6988 6989 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); 6990 if (!ToSubExprOrErr) 6991 return ToSubExprOrErr.takeError(); 6992 6993 return new (Importer.getToContext()) ImaginaryLiteral( 6994 *ToSubExprOrErr, *ToTypeOrErr); 6995 } 6996 6997 ExpectedStmt ASTNodeImporter::VisitFixedPointLiteral(FixedPointLiteral *E) { 6998 auto ToTypeOrErr = import(E->getType()); 6999 if (!ToTypeOrErr) 7000 return ToTypeOrErr.takeError(); 7001 7002 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 7003 if (!ToLocationOrErr) 7004 return ToLocationOrErr.takeError(); 7005 7006 return new (Importer.getToContext()) FixedPointLiteral( 7007 Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr, 7008 Importer.getToContext().getFixedPointScale(*ToTypeOrErr)); 7009 } 7010 7011 ExpectedStmt ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) { 7012 ExpectedType ToTypeOrErr = import(E->getType()); 7013 if (!ToTypeOrErr) 7014 return ToTypeOrErr.takeError(); 7015 7016 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 7017 if (!ToLocationOrErr) 7018 return ToLocationOrErr.takeError(); 7019 7020 return new (Importer.getToContext()) CharacterLiteral( 7021 E->getValue(), E->getKind(), *ToTypeOrErr, *ToLocationOrErr); 7022 } 7023 7024 ExpectedStmt ASTNodeImporter::VisitStringLiteral(StringLiteral *E) { 7025 ExpectedType ToTypeOrErr = import(E->getType()); 7026 if (!ToTypeOrErr) 7027 return ToTypeOrErr.takeError(); 7028 7029 SmallVector<SourceLocation, 4> ToLocations(E->getNumConcatenated()); 7030 if (Error Err = ImportArrayChecked( 7031 E->tokloc_begin(), E->tokloc_end(), ToLocations.begin())) 7032 return std::move(Err); 7033 7034 return StringLiteral::Create( 7035 Importer.getToContext(), E->getBytes(), E->getKind(), E->isPascal(), 7036 *ToTypeOrErr, ToLocations.data(), ToLocations.size()); 7037 } 7038 7039 ExpectedStmt ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 7040 7041 Error Err = Error::success(); 7042 auto ToLParenLoc = importChecked(Err, E->getLParenLoc()); 7043 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo()); 7044 auto ToType = importChecked(Err, E->getType()); 7045 auto ToInitializer = importChecked(Err, E->getInitializer()); 7046 if (Err) 7047 return std::move(Err); 7048 7049 return new (Importer.getToContext()) CompoundLiteralExpr( 7050 ToLParenLoc, ToTypeSourceInfo, ToType, E->getValueKind(), 7051 ToInitializer, E->isFileScope()); 7052 } 7053 7054 ExpectedStmt ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) { 7055 7056 Error Err = Error::success(); 7057 auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc()); 7058 auto ToType = importChecked(Err, E->getType()); 7059 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7060 if (Err) 7061 return std::move(Err); 7062 7063 SmallVector<Expr *, 6> ToExprs(E->getNumSubExprs()); 7064 if (Error Err = ImportArrayChecked( 7065 E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(), 7066 ToExprs.begin())) 7067 return std::move(Err); 7068 7069 return new (Importer.getToContext()) AtomicExpr( 7070 7071 ToBuiltinLoc, ToExprs, ToType, E->getOp(), ToRParenLoc); 7072 } 7073 7074 ExpectedStmt ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) { 7075 Error Err = Error::success(); 7076 auto ToAmpAmpLoc = importChecked(Err, E->getAmpAmpLoc()); 7077 auto ToLabelLoc = importChecked(Err, E->getLabelLoc()); 7078 auto ToLabel = importChecked(Err, E->getLabel()); 7079 auto ToType = importChecked(Err, E->getType()); 7080 if (Err) 7081 return std::move(Err); 7082 7083 return new (Importer.getToContext()) AddrLabelExpr( 7084 ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType); 7085 } 7086 ExpectedStmt ASTNodeImporter::VisitConstantExpr(ConstantExpr *E) { 7087 Error Err = Error::success(); 7088 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 7089 auto ToResult = importChecked(Err, E->getAPValueResult()); 7090 if (Err) 7091 return std::move(Err); 7092 7093 return ConstantExpr::Create(Importer.getToContext(), ToSubExpr, ToResult); 7094 } 7095 ExpectedStmt ASTNodeImporter::VisitParenExpr(ParenExpr *E) { 7096 Error Err = Error::success(); 7097 auto ToLParen = importChecked(Err, E->getLParen()); 7098 auto ToRParen = importChecked(Err, E->getRParen()); 7099 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 7100 if (Err) 7101 return std::move(Err); 7102 7103 return new (Importer.getToContext()) 7104 ParenExpr(ToLParen, ToRParen, ToSubExpr); 7105 } 7106 7107 ExpectedStmt ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) { 7108 SmallVector<Expr *, 4> ToExprs(E->getNumExprs()); 7109 if (Error Err = ImportContainerChecked(E->exprs(), ToExprs)) 7110 return std::move(Err); 7111 7112 ExpectedSLoc ToLParenLocOrErr = import(E->getLParenLoc()); 7113 if (!ToLParenLocOrErr) 7114 return ToLParenLocOrErr.takeError(); 7115 7116 ExpectedSLoc ToRParenLocOrErr = import(E->getRParenLoc()); 7117 if (!ToRParenLocOrErr) 7118 return ToRParenLocOrErr.takeError(); 7119 7120 return ParenListExpr::Create(Importer.getToContext(), *ToLParenLocOrErr, 7121 ToExprs, *ToRParenLocOrErr); 7122 } 7123 7124 ExpectedStmt ASTNodeImporter::VisitStmtExpr(StmtExpr *E) { 7125 Error Err = Error::success(); 7126 auto ToSubStmt = importChecked(Err, E->getSubStmt()); 7127 auto ToType = importChecked(Err, E->getType()); 7128 auto ToLParenLoc = importChecked(Err, E->getLParenLoc()); 7129 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7130 if (Err) 7131 return std::move(Err); 7132 7133 return new (Importer.getToContext()) 7134 StmtExpr(ToSubStmt, ToType, ToLParenLoc, ToRParenLoc, 7135 E->getTemplateDepth()); 7136 } 7137 7138 ExpectedStmt ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) { 7139 Error Err = Error::success(); 7140 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 7141 auto ToType = importChecked(Err, E->getType()); 7142 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7143 if (Err) 7144 return std::move(Err); 7145 7146 return UnaryOperator::Create( 7147 Importer.getToContext(), ToSubExpr, E->getOpcode(), ToType, 7148 E->getValueKind(), E->getObjectKind(), ToOperatorLoc, E->canOverflow(), 7149 E->getFPOptionsOverride()); 7150 } 7151 7152 ExpectedStmt 7153 7154 ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) { 7155 Error Err = Error::success(); 7156 auto ToType = importChecked(Err, E->getType()); 7157 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7158 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7159 if (Err) 7160 return std::move(Err); 7161 7162 if (E->isArgumentType()) { 7163 Expected<TypeSourceInfo *> ToArgumentTypeInfoOrErr = 7164 import(E->getArgumentTypeInfo()); 7165 if (!ToArgumentTypeInfoOrErr) 7166 return ToArgumentTypeInfoOrErr.takeError(); 7167 7168 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr( 7169 E->getKind(), *ToArgumentTypeInfoOrErr, ToType, ToOperatorLoc, 7170 ToRParenLoc); 7171 } 7172 7173 ExpectedExpr ToArgumentExprOrErr = import(E->getArgumentExpr()); 7174 if (!ToArgumentExprOrErr) 7175 return ToArgumentExprOrErr.takeError(); 7176 7177 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr( 7178 E->getKind(), *ToArgumentExprOrErr, ToType, ToOperatorLoc, ToRParenLoc); 7179 } 7180 7181 ExpectedStmt ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) { 7182 Error Err = Error::success(); 7183 auto ToLHS = importChecked(Err, E->getLHS()); 7184 auto ToRHS = importChecked(Err, E->getRHS()); 7185 auto ToType = importChecked(Err, E->getType()); 7186 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7187 if (Err) 7188 return std::move(Err); 7189 7190 return BinaryOperator::Create( 7191 Importer.getToContext(), ToLHS, ToRHS, E->getOpcode(), ToType, 7192 E->getValueKind(), E->getObjectKind(), ToOperatorLoc, 7193 E->getFPFeatures(Importer.getFromContext().getLangOpts())); 7194 } 7195 7196 ExpectedStmt ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) { 7197 Error Err = Error::success(); 7198 auto ToCond = importChecked(Err, E->getCond()); 7199 auto ToQuestionLoc = importChecked(Err, E->getQuestionLoc()); 7200 auto ToLHS = importChecked(Err, E->getLHS()); 7201 auto ToColonLoc = importChecked(Err, E->getColonLoc()); 7202 auto ToRHS = importChecked(Err, E->getRHS()); 7203 auto ToType = importChecked(Err, E->getType()); 7204 if (Err) 7205 return std::move(Err); 7206 7207 return new (Importer.getToContext()) ConditionalOperator( 7208 ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, ToType, 7209 E->getValueKind(), E->getObjectKind()); 7210 } 7211 7212 ExpectedStmt 7213 ASTNodeImporter::VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 7214 Error Err = Error::success(); 7215 auto ToCommon = importChecked(Err, E->getCommon()); 7216 auto ToOpaqueValue = importChecked(Err, E->getOpaqueValue()); 7217 auto ToCond = importChecked(Err, E->getCond()); 7218 auto ToTrueExpr = importChecked(Err, E->getTrueExpr()); 7219 auto ToFalseExpr = importChecked(Err, E->getFalseExpr()); 7220 auto ToQuestionLoc = importChecked(Err, E->getQuestionLoc()); 7221 auto ToColonLoc = importChecked(Err, E->getColonLoc()); 7222 auto ToType = importChecked(Err, E->getType()); 7223 if (Err) 7224 return std::move(Err); 7225 7226 return new (Importer.getToContext()) BinaryConditionalOperator( 7227 ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr, 7228 ToQuestionLoc, ToColonLoc, ToType, E->getValueKind(), 7229 E->getObjectKind()); 7230 } 7231 7232 ExpectedStmt ASTNodeImporter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) { 7233 Error Err = Error::success(); 7234 auto ToBeginLoc = importChecked(Err, E->getBeginLoc()); 7235 auto ToQueriedTypeSourceInfo = 7236 importChecked(Err, E->getQueriedTypeSourceInfo()); 7237 auto ToDimensionExpression = importChecked(Err, E->getDimensionExpression()); 7238 auto ToEndLoc = importChecked(Err, E->getEndLoc()); 7239 auto ToType = importChecked(Err, E->getType()); 7240 if (Err) 7241 return std::move(Err); 7242 7243 return new (Importer.getToContext()) ArrayTypeTraitExpr( 7244 ToBeginLoc, E->getTrait(), ToQueriedTypeSourceInfo, E->getValue(), 7245 ToDimensionExpression, ToEndLoc, ToType); 7246 } 7247 7248 ExpectedStmt ASTNodeImporter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) { 7249 Error Err = Error::success(); 7250 auto ToBeginLoc = importChecked(Err, E->getBeginLoc()); 7251 auto ToQueriedExpression = importChecked(Err, E->getQueriedExpression()); 7252 auto ToEndLoc = importChecked(Err, E->getEndLoc()); 7253 auto ToType = importChecked(Err, E->getType()); 7254 if (Err) 7255 return std::move(Err); 7256 7257 return new (Importer.getToContext()) ExpressionTraitExpr( 7258 ToBeginLoc, E->getTrait(), ToQueriedExpression, E->getValue(), 7259 ToEndLoc, ToType); 7260 } 7261 7262 ExpectedStmt ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) { 7263 Error Err = Error::success(); 7264 auto ToLocation = importChecked(Err, E->getLocation()); 7265 auto ToType = importChecked(Err, E->getType()); 7266 auto ToSourceExpr = importChecked(Err, E->getSourceExpr()); 7267 if (Err) 7268 return std::move(Err); 7269 7270 return new (Importer.getToContext()) OpaqueValueExpr( 7271 ToLocation, ToType, E->getValueKind(), E->getObjectKind(), ToSourceExpr); 7272 } 7273 7274 ExpectedStmt ASTNodeImporter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 7275 Error Err = Error::success(); 7276 auto ToLHS = importChecked(Err, E->getLHS()); 7277 auto ToRHS = importChecked(Err, E->getRHS()); 7278 auto ToType = importChecked(Err, E->getType()); 7279 auto ToRBracketLoc = importChecked(Err, E->getRBracketLoc()); 7280 if (Err) 7281 return std::move(Err); 7282 7283 return new (Importer.getToContext()) ArraySubscriptExpr( 7284 ToLHS, ToRHS, ToType, E->getValueKind(), E->getObjectKind(), 7285 ToRBracketLoc); 7286 } 7287 7288 ExpectedStmt 7289 ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) { 7290 Error Err = Error::success(); 7291 auto ToLHS = importChecked(Err, E->getLHS()); 7292 auto ToRHS = importChecked(Err, E->getRHS()); 7293 auto ToType = importChecked(Err, E->getType()); 7294 auto ToComputationLHSType = importChecked(Err, E->getComputationLHSType()); 7295 auto ToComputationResultType = 7296 importChecked(Err, E->getComputationResultType()); 7297 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7298 if (Err) 7299 return std::move(Err); 7300 7301 return CompoundAssignOperator::Create( 7302 Importer.getToContext(), ToLHS, ToRHS, E->getOpcode(), ToType, 7303 E->getValueKind(), E->getObjectKind(), ToOperatorLoc, 7304 E->getFPFeatures(Importer.getFromContext().getLangOpts()), 7305 ToComputationLHSType, ToComputationResultType); 7306 } 7307 7308 Expected<CXXCastPath> 7309 ASTNodeImporter::ImportCastPath(CastExpr *CE) { 7310 CXXCastPath Path; 7311 for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) { 7312 if (auto SpecOrErr = import(*I)) 7313 Path.push_back(*SpecOrErr); 7314 else 7315 return SpecOrErr.takeError(); 7316 } 7317 return Path; 7318 } 7319 7320 ExpectedStmt ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) { 7321 ExpectedType ToTypeOrErr = import(E->getType()); 7322 if (!ToTypeOrErr) 7323 return ToTypeOrErr.takeError(); 7324 7325 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); 7326 if (!ToSubExprOrErr) 7327 return ToSubExprOrErr.takeError(); 7328 7329 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E); 7330 if (!ToBasePathOrErr) 7331 return ToBasePathOrErr.takeError(); 7332 7333 return ImplicitCastExpr::Create( 7334 Importer.getToContext(), *ToTypeOrErr, E->getCastKind(), *ToSubExprOrErr, 7335 &(*ToBasePathOrErr), E->getValueKind(), E->getFPFeatures()); 7336 } 7337 7338 ExpectedStmt ASTNodeImporter::VisitExplicitCastExpr(ExplicitCastExpr *E) { 7339 Error Err = Error::success(); 7340 auto ToType = importChecked(Err, E->getType()); 7341 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 7342 auto ToTypeInfoAsWritten = importChecked(Err, E->getTypeInfoAsWritten()); 7343 if (Err) 7344 return std::move(Err); 7345 7346 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E); 7347 if (!ToBasePathOrErr) 7348 return ToBasePathOrErr.takeError(); 7349 CXXCastPath *ToBasePath = &(*ToBasePathOrErr); 7350 7351 switch (E->getStmtClass()) { 7352 case Stmt::CStyleCastExprClass: { 7353 auto *CCE = cast<CStyleCastExpr>(E); 7354 ExpectedSLoc ToLParenLocOrErr = import(CCE->getLParenLoc()); 7355 if (!ToLParenLocOrErr) 7356 return ToLParenLocOrErr.takeError(); 7357 ExpectedSLoc ToRParenLocOrErr = import(CCE->getRParenLoc()); 7358 if (!ToRParenLocOrErr) 7359 return ToRParenLocOrErr.takeError(); 7360 return CStyleCastExpr::Create( 7361 Importer.getToContext(), ToType, E->getValueKind(), E->getCastKind(), 7362 ToSubExpr, ToBasePath, CCE->getFPFeatures(), ToTypeInfoAsWritten, 7363 *ToLParenLocOrErr, *ToRParenLocOrErr); 7364 } 7365 7366 case Stmt::CXXFunctionalCastExprClass: { 7367 auto *FCE = cast<CXXFunctionalCastExpr>(E); 7368 ExpectedSLoc ToLParenLocOrErr = import(FCE->getLParenLoc()); 7369 if (!ToLParenLocOrErr) 7370 return ToLParenLocOrErr.takeError(); 7371 ExpectedSLoc ToRParenLocOrErr = import(FCE->getRParenLoc()); 7372 if (!ToRParenLocOrErr) 7373 return ToRParenLocOrErr.takeError(); 7374 return CXXFunctionalCastExpr::Create( 7375 Importer.getToContext(), ToType, E->getValueKind(), ToTypeInfoAsWritten, 7376 E->getCastKind(), ToSubExpr, ToBasePath, FCE->getFPFeatures(), 7377 *ToLParenLocOrErr, *ToRParenLocOrErr); 7378 } 7379 7380 case Stmt::ObjCBridgedCastExprClass: { 7381 auto *OCE = cast<ObjCBridgedCastExpr>(E); 7382 ExpectedSLoc ToLParenLocOrErr = import(OCE->getLParenLoc()); 7383 if (!ToLParenLocOrErr) 7384 return ToLParenLocOrErr.takeError(); 7385 ExpectedSLoc ToBridgeKeywordLocOrErr = import(OCE->getBridgeKeywordLoc()); 7386 if (!ToBridgeKeywordLocOrErr) 7387 return ToBridgeKeywordLocOrErr.takeError(); 7388 return new (Importer.getToContext()) ObjCBridgedCastExpr( 7389 *ToLParenLocOrErr, OCE->getBridgeKind(), E->getCastKind(), 7390 *ToBridgeKeywordLocOrErr, ToTypeInfoAsWritten, ToSubExpr); 7391 } 7392 default: 7393 llvm_unreachable("Cast expression of unsupported type!"); 7394 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 7395 } 7396 } 7397 7398 ExpectedStmt ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *E) { 7399 SmallVector<OffsetOfNode, 4> ToNodes; 7400 for (int I = 0, N = E->getNumComponents(); I < N; ++I) { 7401 const OffsetOfNode &FromNode = E->getComponent(I); 7402 7403 SourceLocation ToBeginLoc, ToEndLoc; 7404 7405 if (FromNode.getKind() != OffsetOfNode::Base) { 7406 Error Err = Error::success(); 7407 ToBeginLoc = importChecked(Err, FromNode.getBeginLoc()); 7408 ToEndLoc = importChecked(Err, FromNode.getEndLoc()); 7409 if (Err) 7410 return std::move(Err); 7411 } 7412 7413 switch (FromNode.getKind()) { 7414 case OffsetOfNode::Array: 7415 ToNodes.push_back( 7416 OffsetOfNode(ToBeginLoc, FromNode.getArrayExprIndex(), ToEndLoc)); 7417 break; 7418 case OffsetOfNode::Base: { 7419 auto ToBSOrErr = import(FromNode.getBase()); 7420 if (!ToBSOrErr) 7421 return ToBSOrErr.takeError(); 7422 ToNodes.push_back(OffsetOfNode(*ToBSOrErr)); 7423 break; 7424 } 7425 case OffsetOfNode::Field: { 7426 auto ToFieldOrErr = import(FromNode.getField()); 7427 if (!ToFieldOrErr) 7428 return ToFieldOrErr.takeError(); 7429 ToNodes.push_back(OffsetOfNode(ToBeginLoc, *ToFieldOrErr, ToEndLoc)); 7430 break; 7431 } 7432 case OffsetOfNode::Identifier: { 7433 IdentifierInfo *ToII = Importer.Import(FromNode.getFieldName()); 7434 ToNodes.push_back(OffsetOfNode(ToBeginLoc, ToII, ToEndLoc)); 7435 break; 7436 } 7437 } 7438 } 7439 7440 SmallVector<Expr *, 4> ToExprs(E->getNumExpressions()); 7441 for (int I = 0, N = E->getNumExpressions(); I < N; ++I) { 7442 ExpectedExpr ToIndexExprOrErr = import(E->getIndexExpr(I)); 7443 if (!ToIndexExprOrErr) 7444 return ToIndexExprOrErr.takeError(); 7445 ToExprs[I] = *ToIndexExprOrErr; 7446 } 7447 7448 Error Err = Error::success(); 7449 auto ToType = importChecked(Err, E->getType()); 7450 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo()); 7451 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7452 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7453 if (Err) 7454 return std::move(Err); 7455 7456 return OffsetOfExpr::Create( 7457 Importer.getToContext(), ToType, ToOperatorLoc, ToTypeSourceInfo, ToNodes, 7458 ToExprs, ToRParenLoc); 7459 } 7460 7461 ExpectedStmt ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) { 7462 Error Err = Error::success(); 7463 auto ToType = importChecked(Err, E->getType()); 7464 auto ToOperand = importChecked(Err, E->getOperand()); 7465 auto ToBeginLoc = importChecked(Err, E->getBeginLoc()); 7466 auto ToEndLoc = importChecked(Err, E->getEndLoc()); 7467 if (Err) 7468 return std::move(Err); 7469 7470 CanThrowResult ToCanThrow; 7471 if (E->isValueDependent()) 7472 ToCanThrow = CT_Dependent; 7473 else 7474 ToCanThrow = E->getValue() ? CT_Can : CT_Cannot; 7475 7476 return new (Importer.getToContext()) CXXNoexceptExpr( 7477 ToType, ToOperand, ToCanThrow, ToBeginLoc, ToEndLoc); 7478 } 7479 7480 ExpectedStmt ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) { 7481 Error Err = Error::success(); 7482 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 7483 auto ToType = importChecked(Err, E->getType()); 7484 auto ToThrowLoc = importChecked(Err, E->getThrowLoc()); 7485 if (Err) 7486 return std::move(Err); 7487 7488 return new (Importer.getToContext()) CXXThrowExpr( 7489 ToSubExpr, ToType, ToThrowLoc, E->isThrownVariableInScope()); 7490 } 7491 7492 ExpectedStmt ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 7493 ExpectedSLoc ToUsedLocOrErr = import(E->getUsedLocation()); 7494 if (!ToUsedLocOrErr) 7495 return ToUsedLocOrErr.takeError(); 7496 7497 auto ToParamOrErr = import(E->getParam()); 7498 if (!ToParamOrErr) 7499 return ToParamOrErr.takeError(); 7500 7501 auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext()); 7502 if (!UsedContextOrErr) 7503 return UsedContextOrErr.takeError(); 7504 7505 // Import the default arg if it was not imported yet. 7506 // This is needed because it can happen that during the import of the 7507 // default expression (from VisitParmVarDecl) the same ParmVarDecl is 7508 // encountered here. The default argument for a ParmVarDecl is set in the 7509 // ParmVarDecl only after it is imported (set in VisitParmVarDecl if not here, 7510 // see VisitParmVarDecl). 7511 ParmVarDecl *ToParam = *ToParamOrErr; 7512 if (!ToParam->getDefaultArg()) { 7513 Optional<ParmVarDecl *> FromParam = Importer.getImportedFromDecl(ToParam); 7514 assert(FromParam && "ParmVarDecl was not imported?"); 7515 7516 if (Error Err = ImportDefaultArgOfParmVarDecl(*FromParam, ToParam)) 7517 return std::move(Err); 7518 } 7519 7520 return CXXDefaultArgExpr::Create(Importer.getToContext(), *ToUsedLocOrErr, 7521 *ToParamOrErr, *UsedContextOrErr); 7522 } 7523 7524 ExpectedStmt 7525 ASTNodeImporter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 7526 Error Err = Error::success(); 7527 auto ToType = importChecked(Err, E->getType()); 7528 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo()); 7529 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7530 if (Err) 7531 return std::move(Err); 7532 7533 return new (Importer.getToContext()) CXXScalarValueInitExpr( 7534 ToType, ToTypeSourceInfo, ToRParenLoc); 7535 } 7536 7537 ExpectedStmt 7538 ASTNodeImporter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 7539 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); 7540 if (!ToSubExprOrErr) 7541 return ToSubExprOrErr.takeError(); 7542 7543 auto ToDtorOrErr = import(E->getTemporary()->getDestructor()); 7544 if (!ToDtorOrErr) 7545 return ToDtorOrErr.takeError(); 7546 7547 ASTContext &ToCtx = Importer.getToContext(); 7548 CXXTemporary *Temp = CXXTemporary::Create(ToCtx, *ToDtorOrErr); 7549 return CXXBindTemporaryExpr::Create(ToCtx, Temp, *ToSubExprOrErr); 7550 } 7551 7552 ExpectedStmt 7553 7554 ASTNodeImporter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) { 7555 Error Err = Error::success(); 7556 auto ToConstructor = importChecked(Err, E->getConstructor()); 7557 auto ToType = importChecked(Err, E->getType()); 7558 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo()); 7559 auto ToParenOrBraceRange = importChecked(Err, E->getParenOrBraceRange()); 7560 if (Err) 7561 return std::move(Err); 7562 7563 SmallVector<Expr *, 8> ToArgs(E->getNumArgs()); 7564 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) 7565 return std::move(Err); 7566 7567 return CXXTemporaryObjectExpr::Create( 7568 Importer.getToContext(), ToConstructor, ToType, ToTypeSourceInfo, ToArgs, 7569 ToParenOrBraceRange, E->hadMultipleCandidates(), 7570 E->isListInitialization(), E->isStdInitListInitialization(), 7571 E->requiresZeroInitialization()); 7572 } 7573 7574 ExpectedDecl ASTNodeImporter::VisitLifetimeExtendedTemporaryDecl( 7575 LifetimeExtendedTemporaryDecl *D) { 7576 DeclContext *DC, *LexicalDC; 7577 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 7578 return std::move(Err); 7579 7580 Error Err = Error::success(); 7581 auto Temporary = importChecked(Err, D->getTemporaryExpr()); 7582 auto ExtendingDecl = importChecked(Err, D->getExtendingDecl()); 7583 if (Err) 7584 return std::move(Err); 7585 // FIXME: Should ManglingNumber get numbers associated with 'to' context? 7586 7587 LifetimeExtendedTemporaryDecl *To; 7588 if (GetImportedOrCreateDecl(To, D, Temporary, ExtendingDecl, 7589 D->getManglingNumber())) 7590 return To; 7591 7592 To->setLexicalDeclContext(LexicalDC); 7593 LexicalDC->addDeclInternal(To); 7594 return To; 7595 } 7596 7597 ExpectedStmt 7598 ASTNodeImporter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) { 7599 Error Err = Error::success(); 7600 auto ToType = importChecked(Err, E->getType()); 7601 Expr *ToTemporaryExpr = importChecked( 7602 Err, E->getLifetimeExtendedTemporaryDecl() ? nullptr : E->getSubExpr()); 7603 auto ToMaterializedDecl = 7604 importChecked(Err, E->getLifetimeExtendedTemporaryDecl()); 7605 if (Err) 7606 return std::move(Err); 7607 7608 if (!ToTemporaryExpr) 7609 ToTemporaryExpr = cast<Expr>(ToMaterializedDecl->getTemporaryExpr()); 7610 7611 auto *ToMTE = new (Importer.getToContext()) MaterializeTemporaryExpr( 7612 ToType, ToTemporaryExpr, E->isBoundToLvalueReference(), 7613 ToMaterializedDecl); 7614 7615 return ToMTE; 7616 } 7617 7618 ExpectedStmt ASTNodeImporter::VisitPackExpansionExpr(PackExpansionExpr *E) { 7619 Error Err = Error::success(); 7620 auto ToType = importChecked(Err, E->getType()); 7621 auto ToPattern = importChecked(Err, E->getPattern()); 7622 auto ToEllipsisLoc = importChecked(Err, E->getEllipsisLoc()); 7623 if (Err) 7624 return std::move(Err); 7625 7626 return new (Importer.getToContext()) PackExpansionExpr( 7627 ToType, ToPattern, ToEllipsisLoc, E->getNumExpansions()); 7628 } 7629 7630 ExpectedStmt ASTNodeImporter::VisitSizeOfPackExpr(SizeOfPackExpr *E) { 7631 Error Err = Error::success(); 7632 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7633 auto ToPack = importChecked(Err, E->getPack()); 7634 auto ToPackLoc = importChecked(Err, E->getPackLoc()); 7635 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7636 if (Err) 7637 return std::move(Err); 7638 7639 Optional<unsigned> Length; 7640 if (!E->isValueDependent()) 7641 Length = E->getPackLength(); 7642 7643 SmallVector<TemplateArgument, 8> ToPartialArguments; 7644 if (E->isPartiallySubstituted()) { 7645 if (Error Err = ImportTemplateArguments( 7646 E->getPartialArguments().data(), 7647 E->getPartialArguments().size(), 7648 ToPartialArguments)) 7649 return std::move(Err); 7650 } 7651 7652 return SizeOfPackExpr::Create( 7653 Importer.getToContext(), ToOperatorLoc, ToPack, ToPackLoc, ToRParenLoc, 7654 Length, ToPartialArguments); 7655 } 7656 7657 7658 ExpectedStmt ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *E) { 7659 Error Err = Error::success(); 7660 auto ToOperatorNew = importChecked(Err, E->getOperatorNew()); 7661 auto ToOperatorDelete = importChecked(Err, E->getOperatorDelete()); 7662 auto ToTypeIdParens = importChecked(Err, E->getTypeIdParens()); 7663 auto ToArraySize = importChecked(Err, E->getArraySize()); 7664 auto ToInitializer = importChecked(Err, E->getInitializer()); 7665 auto ToType = importChecked(Err, E->getType()); 7666 auto ToAllocatedTypeSourceInfo = 7667 importChecked(Err, E->getAllocatedTypeSourceInfo()); 7668 auto ToSourceRange = importChecked(Err, E->getSourceRange()); 7669 auto ToDirectInitRange = importChecked(Err, E->getDirectInitRange()); 7670 if (Err) 7671 return std::move(Err); 7672 7673 SmallVector<Expr *, 4> ToPlacementArgs(E->getNumPlacementArgs()); 7674 if (Error Err = 7675 ImportContainerChecked(E->placement_arguments(), ToPlacementArgs)) 7676 return std::move(Err); 7677 7678 return CXXNewExpr::Create( 7679 Importer.getToContext(), E->isGlobalNew(), ToOperatorNew, 7680 ToOperatorDelete, E->passAlignment(), E->doesUsualArrayDeleteWantSize(), 7681 ToPlacementArgs, ToTypeIdParens, ToArraySize, E->getInitializationStyle(), 7682 ToInitializer, ToType, ToAllocatedTypeSourceInfo, ToSourceRange, 7683 ToDirectInitRange); 7684 } 7685 7686 ExpectedStmt ASTNodeImporter::VisitCXXDeleteExpr(CXXDeleteExpr *E) { 7687 Error Err = Error::success(); 7688 auto ToType = importChecked(Err, E->getType()); 7689 auto ToOperatorDelete = importChecked(Err, E->getOperatorDelete()); 7690 auto ToArgument = importChecked(Err, E->getArgument()); 7691 auto ToBeginLoc = importChecked(Err, E->getBeginLoc()); 7692 if (Err) 7693 return std::move(Err); 7694 7695 return new (Importer.getToContext()) CXXDeleteExpr( 7696 ToType, E->isGlobalDelete(), E->isArrayForm(), E->isArrayFormAsWritten(), 7697 E->doesUsualArrayDeleteWantSize(), ToOperatorDelete, ToArgument, 7698 ToBeginLoc); 7699 } 7700 7701 ExpectedStmt ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) { 7702 Error Err = Error::success(); 7703 auto ToType = importChecked(Err, E->getType()); 7704 auto ToLocation = importChecked(Err, E->getLocation()); 7705 auto ToConstructor = importChecked(Err, E->getConstructor()); 7706 auto ToParenOrBraceRange = importChecked(Err, E->getParenOrBraceRange()); 7707 if (Err) 7708 return std::move(Err); 7709 7710 SmallVector<Expr *, 6> ToArgs(E->getNumArgs()); 7711 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) 7712 return std::move(Err); 7713 7714 return CXXConstructExpr::Create( 7715 Importer.getToContext(), ToType, ToLocation, ToConstructor, 7716 E->isElidable(), ToArgs, E->hadMultipleCandidates(), 7717 E->isListInitialization(), E->isStdInitListInitialization(), 7718 E->requiresZeroInitialization(), E->getConstructionKind(), 7719 ToParenOrBraceRange); 7720 } 7721 7722 ExpectedStmt ASTNodeImporter::VisitExprWithCleanups(ExprWithCleanups *E) { 7723 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); 7724 if (!ToSubExprOrErr) 7725 return ToSubExprOrErr.takeError(); 7726 7727 SmallVector<ExprWithCleanups::CleanupObject, 8> ToObjects(E->getNumObjects()); 7728 if (Error Err = ImportContainerChecked(E->getObjects(), ToObjects)) 7729 return std::move(Err); 7730 7731 return ExprWithCleanups::Create( 7732 Importer.getToContext(), *ToSubExprOrErr, E->cleanupsHaveSideEffects(), 7733 ToObjects); 7734 } 7735 7736 ExpectedStmt ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 7737 Error Err = Error::success(); 7738 auto ToCallee = importChecked(Err, E->getCallee()); 7739 auto ToType = importChecked(Err, E->getType()); 7740 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7741 if (Err) 7742 return std::move(Err); 7743 7744 SmallVector<Expr *, 4> ToArgs(E->getNumArgs()); 7745 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) 7746 return std::move(Err); 7747 7748 return CXXMemberCallExpr::Create(Importer.getToContext(), ToCallee, ToArgs, 7749 ToType, E->getValueKind(), ToRParenLoc, 7750 E->getFPFeatures()); 7751 } 7752 7753 ExpectedStmt ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) { 7754 ExpectedType ToTypeOrErr = import(E->getType()); 7755 if (!ToTypeOrErr) 7756 return ToTypeOrErr.takeError(); 7757 7758 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 7759 if (!ToLocationOrErr) 7760 return ToLocationOrErr.takeError(); 7761 7762 return new (Importer.getToContext()) CXXThisExpr( 7763 *ToLocationOrErr, *ToTypeOrErr, E->isImplicit()); 7764 } 7765 7766 ExpectedStmt ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { 7767 ExpectedType ToTypeOrErr = import(E->getType()); 7768 if (!ToTypeOrErr) 7769 return ToTypeOrErr.takeError(); 7770 7771 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 7772 if (!ToLocationOrErr) 7773 return ToLocationOrErr.takeError(); 7774 7775 return new (Importer.getToContext()) CXXBoolLiteralExpr( 7776 E->getValue(), *ToTypeOrErr, *ToLocationOrErr); 7777 } 7778 7779 ExpectedStmt ASTNodeImporter::VisitMemberExpr(MemberExpr *E) { 7780 Error Err = Error::success(); 7781 auto ToBase = importChecked(Err, E->getBase()); 7782 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7783 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc()); 7784 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc()); 7785 auto ToMemberDecl = importChecked(Err, E->getMemberDecl()); 7786 auto ToType = importChecked(Err, E->getType()); 7787 auto ToDecl = importChecked(Err, E->getFoundDecl().getDecl()); 7788 auto ToName = importChecked(Err, E->getMemberNameInfo().getName()); 7789 auto ToLoc = importChecked(Err, E->getMemberNameInfo().getLoc()); 7790 if (Err) 7791 return std::move(Err); 7792 7793 DeclAccessPair ToFoundDecl = 7794 DeclAccessPair::make(ToDecl, E->getFoundDecl().getAccess()); 7795 7796 DeclarationNameInfo ToMemberNameInfo(ToName, ToLoc); 7797 7798 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr; 7799 if (E->hasExplicitTemplateArgs()) { 7800 if (Error Err = 7801 ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(), 7802 E->template_arguments(), ToTAInfo)) 7803 return std::move(Err); 7804 ResInfo = &ToTAInfo; 7805 } 7806 7807 return MemberExpr::Create(Importer.getToContext(), ToBase, E->isArrow(), 7808 ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc, 7809 ToMemberDecl, ToFoundDecl, ToMemberNameInfo, 7810 ResInfo, ToType, E->getValueKind(), 7811 E->getObjectKind(), E->isNonOdrUse()); 7812 } 7813 7814 ExpectedStmt 7815 ASTNodeImporter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) { 7816 Error Err = Error::success(); 7817 auto ToBase = importChecked(Err, E->getBase()); 7818 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7819 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc()); 7820 auto ToScopeTypeInfo = importChecked(Err, E->getScopeTypeInfo()); 7821 auto ToColonColonLoc = importChecked(Err, E->getColonColonLoc()); 7822 auto ToTildeLoc = importChecked(Err, E->getTildeLoc()); 7823 if (Err) 7824 return std::move(Err); 7825 7826 PseudoDestructorTypeStorage Storage; 7827 if (IdentifierInfo *FromII = E->getDestroyedTypeIdentifier()) { 7828 IdentifierInfo *ToII = Importer.Import(FromII); 7829 ExpectedSLoc ToDestroyedTypeLocOrErr = import(E->getDestroyedTypeLoc()); 7830 if (!ToDestroyedTypeLocOrErr) 7831 return ToDestroyedTypeLocOrErr.takeError(); 7832 Storage = PseudoDestructorTypeStorage(ToII, *ToDestroyedTypeLocOrErr); 7833 } else { 7834 if (auto ToTIOrErr = import(E->getDestroyedTypeInfo())) 7835 Storage = PseudoDestructorTypeStorage(*ToTIOrErr); 7836 else 7837 return ToTIOrErr.takeError(); 7838 } 7839 7840 return new (Importer.getToContext()) CXXPseudoDestructorExpr( 7841 Importer.getToContext(), ToBase, E->isArrow(), ToOperatorLoc, 7842 ToQualifierLoc, ToScopeTypeInfo, ToColonColonLoc, ToTildeLoc, Storage); 7843 } 7844 7845 ExpectedStmt ASTNodeImporter::VisitCXXDependentScopeMemberExpr( 7846 CXXDependentScopeMemberExpr *E) { 7847 Error Err = Error::success(); 7848 auto ToType = importChecked(Err, E->getType()); 7849 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7850 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc()); 7851 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc()); 7852 auto ToFirstQualifierFoundInScope = 7853 importChecked(Err, E->getFirstQualifierFoundInScope()); 7854 if (Err) 7855 return std::move(Err); 7856 7857 Expr *ToBase = nullptr; 7858 if (!E->isImplicitAccess()) { 7859 if (ExpectedExpr ToBaseOrErr = import(E->getBase())) 7860 ToBase = *ToBaseOrErr; 7861 else 7862 return ToBaseOrErr.takeError(); 7863 } 7864 7865 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr; 7866 7867 if (E->hasExplicitTemplateArgs()) { 7868 if (Error Err = 7869 ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(), 7870 E->template_arguments(), ToTAInfo)) 7871 return std::move(Err); 7872 ResInfo = &ToTAInfo; 7873 } 7874 auto ToMember = importChecked(Err, E->getMember()); 7875 auto ToMemberLoc = importChecked(Err, E->getMemberLoc()); 7876 if (Err) 7877 return std::move(Err); 7878 DeclarationNameInfo ToMemberNameInfo(ToMember, ToMemberLoc); 7879 7880 // Import additional name location/type info. 7881 if (Error Err = 7882 ImportDeclarationNameLoc(E->getMemberNameInfo(), ToMemberNameInfo)) 7883 return std::move(Err); 7884 7885 return CXXDependentScopeMemberExpr::Create( 7886 Importer.getToContext(), ToBase, ToType, E->isArrow(), ToOperatorLoc, 7887 ToQualifierLoc, ToTemplateKeywordLoc, ToFirstQualifierFoundInScope, 7888 ToMemberNameInfo, ResInfo); 7889 } 7890 7891 ExpectedStmt 7892 ASTNodeImporter::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) { 7893 Error Err = Error::success(); 7894 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc()); 7895 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc()); 7896 auto ToDeclName = importChecked(Err, E->getDeclName()); 7897 auto ToNameLoc = importChecked(Err, E->getNameInfo().getLoc()); 7898 auto ToLAngleLoc = importChecked(Err, E->getLAngleLoc()); 7899 auto ToRAngleLoc = importChecked(Err, E->getRAngleLoc()); 7900 if (Err) 7901 return std::move(Err); 7902 7903 DeclarationNameInfo ToNameInfo(ToDeclName, ToNameLoc); 7904 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo)) 7905 return std::move(Err); 7906 7907 TemplateArgumentListInfo ToTAInfo(ToLAngleLoc, ToRAngleLoc); 7908 TemplateArgumentListInfo *ResInfo = nullptr; 7909 if (E->hasExplicitTemplateArgs()) { 7910 if (Error Err = 7911 ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo)) 7912 return std::move(Err); 7913 ResInfo = &ToTAInfo; 7914 } 7915 7916 return DependentScopeDeclRefExpr::Create( 7917 Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, 7918 ToNameInfo, ResInfo); 7919 } 7920 7921 ExpectedStmt ASTNodeImporter::VisitCXXUnresolvedConstructExpr( 7922 CXXUnresolvedConstructExpr *E) { 7923 Error Err = Error::success(); 7924 auto ToLParenLoc = importChecked(Err, E->getLParenLoc()); 7925 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 7926 auto ToType = importChecked(Err, E->getType()); 7927 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo()); 7928 if (Err) 7929 return std::move(Err); 7930 7931 SmallVector<Expr *, 8> ToArgs(E->getNumArgs()); 7932 if (Error Err = 7933 ImportArrayChecked(E->arg_begin(), E->arg_end(), ToArgs.begin())) 7934 return std::move(Err); 7935 7936 return CXXUnresolvedConstructExpr::Create( 7937 Importer.getToContext(), ToType, ToTypeSourceInfo, ToLParenLoc, 7938 llvm::makeArrayRef(ToArgs), ToRParenLoc); 7939 } 7940 7941 ExpectedStmt 7942 ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) { 7943 Expected<CXXRecordDecl *> ToNamingClassOrErr = import(E->getNamingClass()); 7944 if (!ToNamingClassOrErr) 7945 return ToNamingClassOrErr.takeError(); 7946 7947 auto ToQualifierLocOrErr = import(E->getQualifierLoc()); 7948 if (!ToQualifierLocOrErr) 7949 return ToQualifierLocOrErr.takeError(); 7950 7951 Error Err = Error::success(); 7952 auto ToName = importChecked(Err, E->getName()); 7953 auto ToNameLoc = importChecked(Err, E->getNameLoc()); 7954 if (Err) 7955 return std::move(Err); 7956 DeclarationNameInfo ToNameInfo(ToName, ToNameLoc); 7957 7958 // Import additional name location/type info. 7959 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo)) 7960 return std::move(Err); 7961 7962 UnresolvedSet<8> ToDecls; 7963 for (auto *D : E->decls()) 7964 if (auto ToDOrErr = import(D)) 7965 ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr)); 7966 else 7967 return ToDOrErr.takeError(); 7968 7969 if (E->hasExplicitTemplateArgs()) { 7970 TemplateArgumentListInfo ToTAInfo; 7971 if (Error Err = ImportTemplateArgumentListInfo( 7972 E->getLAngleLoc(), E->getRAngleLoc(), E->template_arguments(), 7973 ToTAInfo)) 7974 return std::move(Err); 7975 7976 ExpectedSLoc ToTemplateKeywordLocOrErr = import(E->getTemplateKeywordLoc()); 7977 if (!ToTemplateKeywordLocOrErr) 7978 return ToTemplateKeywordLocOrErr.takeError(); 7979 7980 return UnresolvedLookupExpr::Create( 7981 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr, 7982 *ToTemplateKeywordLocOrErr, ToNameInfo, E->requiresADL(), &ToTAInfo, 7983 ToDecls.begin(), ToDecls.end()); 7984 } 7985 7986 return UnresolvedLookupExpr::Create( 7987 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr, 7988 ToNameInfo, E->requiresADL(), E->isOverloaded(), ToDecls.begin(), 7989 ToDecls.end()); 7990 } 7991 7992 ExpectedStmt 7993 ASTNodeImporter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) { 7994 Error Err = Error::success(); 7995 auto ToType = importChecked(Err, E->getType()); 7996 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 7997 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc()); 7998 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc()); 7999 auto ToName = importChecked(Err, E->getName()); 8000 auto ToNameLoc = importChecked(Err, E->getNameLoc()); 8001 if (Err) 8002 return std::move(Err); 8003 8004 DeclarationNameInfo ToNameInfo(ToName, ToNameLoc); 8005 // Import additional name location/type info. 8006 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo)) 8007 return std::move(Err); 8008 8009 UnresolvedSet<8> ToDecls; 8010 for (Decl *D : E->decls()) 8011 if (auto ToDOrErr = import(D)) 8012 ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr)); 8013 else 8014 return ToDOrErr.takeError(); 8015 8016 TemplateArgumentListInfo ToTAInfo; 8017 TemplateArgumentListInfo *ResInfo = nullptr; 8018 if (E->hasExplicitTemplateArgs()) { 8019 TemplateArgumentListInfo FromTAInfo; 8020 E->copyTemplateArgumentsInto(FromTAInfo); 8021 if (Error Err = ImportTemplateArgumentListInfo(FromTAInfo, ToTAInfo)) 8022 return std::move(Err); 8023 ResInfo = &ToTAInfo; 8024 } 8025 8026 Expr *ToBase = nullptr; 8027 if (!E->isImplicitAccess()) { 8028 if (ExpectedExpr ToBaseOrErr = import(E->getBase())) 8029 ToBase = *ToBaseOrErr; 8030 else 8031 return ToBaseOrErr.takeError(); 8032 } 8033 8034 return UnresolvedMemberExpr::Create( 8035 Importer.getToContext(), E->hasUnresolvedUsing(), ToBase, ToType, 8036 E->isArrow(), ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc, 8037 ToNameInfo, ResInfo, ToDecls.begin(), ToDecls.end()); 8038 } 8039 8040 ExpectedStmt ASTNodeImporter::VisitCallExpr(CallExpr *E) { 8041 Error Err = Error::success(); 8042 auto ToCallee = importChecked(Err, E->getCallee()); 8043 auto ToType = importChecked(Err, E->getType()); 8044 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 8045 if (Err) 8046 return std::move(Err); 8047 8048 unsigned NumArgs = E->getNumArgs(); 8049 llvm::SmallVector<Expr *, 2> ToArgs(NumArgs); 8050 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) 8051 return std::move(Err); 8052 8053 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) { 8054 return CXXOperatorCallExpr::Create( 8055 Importer.getToContext(), OCE->getOperator(), ToCallee, ToArgs, ToType, 8056 OCE->getValueKind(), ToRParenLoc, OCE->getFPFeatures(), 8057 OCE->getADLCallKind()); 8058 } 8059 8060 return CallExpr::Create(Importer.getToContext(), ToCallee, ToArgs, ToType, 8061 E->getValueKind(), ToRParenLoc, E->getFPFeatures(), 8062 /*MinNumArgs=*/0, E->getADLCallKind()); 8063 } 8064 8065 ExpectedStmt ASTNodeImporter::VisitLambdaExpr(LambdaExpr *E) { 8066 CXXRecordDecl *FromClass = E->getLambdaClass(); 8067 auto ToClassOrErr = import(FromClass); 8068 if (!ToClassOrErr) 8069 return ToClassOrErr.takeError(); 8070 CXXRecordDecl *ToClass = *ToClassOrErr; 8071 8072 auto ToCallOpOrErr = import(E->getCallOperator()); 8073 if (!ToCallOpOrErr) 8074 return ToCallOpOrErr.takeError(); 8075 8076 SmallVector<Expr *, 8> ToCaptureInits(E->capture_size()); 8077 if (Error Err = ImportContainerChecked(E->capture_inits(), ToCaptureInits)) 8078 return std::move(Err); 8079 8080 Error Err = Error::success(); 8081 auto ToIntroducerRange = importChecked(Err, E->getIntroducerRange()); 8082 auto ToCaptureDefaultLoc = importChecked(Err, E->getCaptureDefaultLoc()); 8083 auto ToEndLoc = importChecked(Err, E->getEndLoc()); 8084 if (Err) 8085 return std::move(Err); 8086 8087 return LambdaExpr::Create(Importer.getToContext(), ToClass, ToIntroducerRange, 8088 E->getCaptureDefault(), ToCaptureDefaultLoc, 8089 E->hasExplicitParameters(), 8090 E->hasExplicitResultType(), ToCaptureInits, 8091 ToEndLoc, E->containsUnexpandedParameterPack()); 8092 } 8093 8094 8095 ExpectedStmt ASTNodeImporter::VisitInitListExpr(InitListExpr *E) { 8096 Error Err = Error::success(); 8097 auto ToLBraceLoc = importChecked(Err, E->getLBraceLoc()); 8098 auto ToRBraceLoc = importChecked(Err, E->getRBraceLoc()); 8099 auto ToType = importChecked(Err, E->getType()); 8100 if (Err) 8101 return std::move(Err); 8102 8103 SmallVector<Expr *, 4> ToExprs(E->getNumInits()); 8104 if (Error Err = ImportContainerChecked(E->inits(), ToExprs)) 8105 return std::move(Err); 8106 8107 ASTContext &ToCtx = Importer.getToContext(); 8108 InitListExpr *To = new (ToCtx) InitListExpr( 8109 ToCtx, ToLBraceLoc, ToExprs, ToRBraceLoc); 8110 To->setType(ToType); 8111 8112 if (E->hasArrayFiller()) { 8113 if (ExpectedExpr ToFillerOrErr = import(E->getArrayFiller())) 8114 To->setArrayFiller(*ToFillerOrErr); 8115 else 8116 return ToFillerOrErr.takeError(); 8117 } 8118 8119 if (FieldDecl *FromFD = E->getInitializedFieldInUnion()) { 8120 if (auto ToFDOrErr = import(FromFD)) 8121 To->setInitializedFieldInUnion(*ToFDOrErr); 8122 else 8123 return ToFDOrErr.takeError(); 8124 } 8125 8126 if (InitListExpr *SyntForm = E->getSyntacticForm()) { 8127 if (auto ToSyntFormOrErr = import(SyntForm)) 8128 To->setSyntacticForm(*ToSyntFormOrErr); 8129 else 8130 return ToSyntFormOrErr.takeError(); 8131 } 8132 8133 // Copy InitListExprBitfields, which are not handled in the ctor of 8134 // InitListExpr. 8135 To->sawArrayRangeDesignator(E->hadArrayRangeDesignator()); 8136 8137 return To; 8138 } 8139 8140 ExpectedStmt ASTNodeImporter::VisitCXXStdInitializerListExpr( 8141 CXXStdInitializerListExpr *E) { 8142 ExpectedType ToTypeOrErr = import(E->getType()); 8143 if (!ToTypeOrErr) 8144 return ToTypeOrErr.takeError(); 8145 8146 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); 8147 if (!ToSubExprOrErr) 8148 return ToSubExprOrErr.takeError(); 8149 8150 return new (Importer.getToContext()) CXXStdInitializerListExpr( 8151 *ToTypeOrErr, *ToSubExprOrErr); 8152 } 8153 8154 ExpectedStmt ASTNodeImporter::VisitCXXInheritedCtorInitExpr( 8155 CXXInheritedCtorInitExpr *E) { 8156 Error Err = Error::success(); 8157 auto ToLocation = importChecked(Err, E->getLocation()); 8158 auto ToType = importChecked(Err, E->getType()); 8159 auto ToConstructor = importChecked(Err, E->getConstructor()); 8160 if (Err) 8161 return std::move(Err); 8162 8163 return new (Importer.getToContext()) CXXInheritedCtorInitExpr( 8164 ToLocation, ToType, ToConstructor, E->constructsVBase(), 8165 E->inheritedFromVBase()); 8166 } 8167 8168 ExpectedStmt ASTNodeImporter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) { 8169 Error Err = Error::success(); 8170 auto ToType = importChecked(Err, E->getType()); 8171 auto ToCommonExpr = importChecked(Err, E->getCommonExpr()); 8172 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 8173 if (Err) 8174 return std::move(Err); 8175 8176 return new (Importer.getToContext()) ArrayInitLoopExpr( 8177 ToType, ToCommonExpr, ToSubExpr); 8178 } 8179 8180 ExpectedStmt ASTNodeImporter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) { 8181 ExpectedType ToTypeOrErr = import(E->getType()); 8182 if (!ToTypeOrErr) 8183 return ToTypeOrErr.takeError(); 8184 return new (Importer.getToContext()) ArrayInitIndexExpr(*ToTypeOrErr); 8185 } 8186 8187 ExpectedStmt ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) { 8188 ExpectedSLoc ToBeginLocOrErr = import(E->getBeginLoc()); 8189 if (!ToBeginLocOrErr) 8190 return ToBeginLocOrErr.takeError(); 8191 8192 auto ToFieldOrErr = import(E->getField()); 8193 if (!ToFieldOrErr) 8194 return ToFieldOrErr.takeError(); 8195 8196 auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext()); 8197 if (!UsedContextOrErr) 8198 return UsedContextOrErr.takeError(); 8199 8200 FieldDecl *ToField = *ToFieldOrErr; 8201 assert(ToField->hasInClassInitializer() && 8202 "Field should have in-class initializer if there is a default init " 8203 "expression that uses it."); 8204 if (!ToField->getInClassInitializer()) { 8205 // The in-class initializer may be not yet set in "To" AST even if the 8206 // field is already there. This must be set here to make construction of 8207 // CXXDefaultInitExpr work. 8208 auto ToInClassInitializerOrErr = 8209 import(E->getField()->getInClassInitializer()); 8210 if (!ToInClassInitializerOrErr) 8211 return ToInClassInitializerOrErr.takeError(); 8212 ToField->setInClassInitializer(*ToInClassInitializerOrErr); 8213 } 8214 8215 return CXXDefaultInitExpr::Create(Importer.getToContext(), *ToBeginLocOrErr, 8216 ToField, *UsedContextOrErr); 8217 } 8218 8219 ExpectedStmt ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) { 8220 Error Err = Error::success(); 8221 auto ToType = importChecked(Err, E->getType()); 8222 auto ToSubExpr = importChecked(Err, E->getSubExpr()); 8223 auto ToTypeInfoAsWritten = importChecked(Err, E->getTypeInfoAsWritten()); 8224 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc()); 8225 auto ToRParenLoc = importChecked(Err, E->getRParenLoc()); 8226 auto ToAngleBrackets = importChecked(Err, E->getAngleBrackets()); 8227 if (Err) 8228 return std::move(Err); 8229 8230 ExprValueKind VK = E->getValueKind(); 8231 CastKind CK = E->getCastKind(); 8232 auto ToBasePathOrErr = ImportCastPath(E); 8233 if (!ToBasePathOrErr) 8234 return ToBasePathOrErr.takeError(); 8235 8236 if (auto CCE = dyn_cast<CXXStaticCastExpr>(E)) { 8237 return CXXStaticCastExpr::Create( 8238 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr), 8239 ToTypeInfoAsWritten, CCE->getFPFeatures(), ToOperatorLoc, ToRParenLoc, 8240 ToAngleBrackets); 8241 } else if (isa<CXXDynamicCastExpr>(E)) { 8242 return CXXDynamicCastExpr::Create( 8243 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr), 8244 ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); 8245 } else if (isa<CXXReinterpretCastExpr>(E)) { 8246 return CXXReinterpretCastExpr::Create( 8247 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr), 8248 ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); 8249 } else if (isa<CXXConstCastExpr>(E)) { 8250 return CXXConstCastExpr::Create( 8251 Importer.getToContext(), ToType, VK, ToSubExpr, ToTypeInfoAsWritten, 8252 ToOperatorLoc, ToRParenLoc, ToAngleBrackets); 8253 } else { 8254 llvm_unreachable("Unknown cast type"); 8255 return make_error<ASTImportError>(); 8256 } 8257 } 8258 8259 ExpectedStmt ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr( 8260 SubstNonTypeTemplateParmExpr *E) { 8261 Error Err = Error::success(); 8262 auto ToType = importChecked(Err, E->getType()); 8263 auto ToExprLoc = importChecked(Err, E->getExprLoc()); 8264 auto ToParameter = importChecked(Err, E->getParameter()); 8265 auto ToReplacement = importChecked(Err, E->getReplacement()); 8266 if (Err) 8267 return std::move(Err); 8268 8269 return new (Importer.getToContext()) SubstNonTypeTemplateParmExpr( 8270 ToType, E->getValueKind(), ToExprLoc, ToParameter, 8271 E->isReferenceParameter(), ToReplacement); 8272 } 8273 8274 ExpectedStmt ASTNodeImporter::VisitTypeTraitExpr(TypeTraitExpr *E) { 8275 Error Err = Error::success(); 8276 auto ToType = importChecked(Err, E->getType()); 8277 auto ToBeginLoc = importChecked(Err, E->getBeginLoc()); 8278 auto ToEndLoc = importChecked(Err, E->getEndLoc()); 8279 if (Err) 8280 return std::move(Err); 8281 8282 SmallVector<TypeSourceInfo *, 4> ToArgs(E->getNumArgs()); 8283 if (Error Err = ImportContainerChecked(E->getArgs(), ToArgs)) 8284 return std::move(Err); 8285 8286 // According to Sema::BuildTypeTrait(), if E is value-dependent, 8287 // Value is always false. 8288 bool ToValue = (E->isValueDependent() ? false : E->getValue()); 8289 8290 return TypeTraitExpr::Create( 8291 Importer.getToContext(), ToType, ToBeginLoc, E->getTrait(), ToArgs, 8292 ToEndLoc, ToValue); 8293 } 8294 8295 ExpectedStmt ASTNodeImporter::VisitCXXTypeidExpr(CXXTypeidExpr *E) { 8296 ExpectedType ToTypeOrErr = import(E->getType()); 8297 if (!ToTypeOrErr) 8298 return ToTypeOrErr.takeError(); 8299 8300 auto ToSourceRangeOrErr = import(E->getSourceRange()); 8301 if (!ToSourceRangeOrErr) 8302 return ToSourceRangeOrErr.takeError(); 8303 8304 if (E->isTypeOperand()) { 8305 if (auto ToTSIOrErr = import(E->getTypeOperandSourceInfo())) 8306 return new (Importer.getToContext()) CXXTypeidExpr( 8307 *ToTypeOrErr, *ToTSIOrErr, *ToSourceRangeOrErr); 8308 else 8309 return ToTSIOrErr.takeError(); 8310 } 8311 8312 ExpectedExpr ToExprOperandOrErr = import(E->getExprOperand()); 8313 if (!ToExprOperandOrErr) 8314 return ToExprOperandOrErr.takeError(); 8315 8316 return new (Importer.getToContext()) CXXTypeidExpr( 8317 *ToTypeOrErr, *ToExprOperandOrErr, *ToSourceRangeOrErr); 8318 } 8319 8320 ExpectedStmt ASTNodeImporter::VisitCXXFoldExpr(CXXFoldExpr *E) { 8321 Error Err = Error::success(); 8322 8323 QualType ToType = importChecked(Err, E->getType()); 8324 UnresolvedLookupExpr *ToCallee = importChecked(Err, E->getCallee()); 8325 SourceLocation ToLParenLoc = importChecked(Err, E->getLParenLoc()); 8326 Expr *ToLHS = importChecked(Err, E->getLHS()); 8327 SourceLocation ToEllipsisLoc = importChecked(Err, E->getEllipsisLoc()); 8328 Expr *ToRHS = importChecked(Err, E->getRHS()); 8329 SourceLocation ToRParenLoc = importChecked(Err, E->getRParenLoc()); 8330 8331 if (Err) 8332 return std::move(Err); 8333 8334 return new (Importer.getToContext()) 8335 CXXFoldExpr(ToType, ToCallee, ToLParenLoc, ToLHS, E->getOperator(), 8336 ToEllipsisLoc, ToRHS, ToRParenLoc, E->getNumExpansions()); 8337 } 8338 8339 Error ASTNodeImporter::ImportOverriddenMethods(CXXMethodDecl *ToMethod, 8340 CXXMethodDecl *FromMethod) { 8341 Error ImportErrors = Error::success(); 8342 for (auto *FromOverriddenMethod : FromMethod->overridden_methods()) { 8343 if (auto ImportedOrErr = import(FromOverriddenMethod)) 8344 ToMethod->getCanonicalDecl()->addOverriddenMethod(cast<CXXMethodDecl>( 8345 (*ImportedOrErr)->getCanonicalDecl())); 8346 else 8347 ImportErrors = 8348 joinErrors(std::move(ImportErrors), ImportedOrErr.takeError()); 8349 } 8350 return ImportErrors; 8351 } 8352 8353 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager, 8354 ASTContext &FromContext, FileManager &FromFileManager, 8355 bool MinimalImport, 8356 std::shared_ptr<ASTImporterSharedState> SharedState) 8357 : SharedState(SharedState), ToContext(ToContext), FromContext(FromContext), 8358 ToFileManager(ToFileManager), FromFileManager(FromFileManager), 8359 Minimal(MinimalImport), ODRHandling(ODRHandlingType::Conservative) { 8360 8361 // Create a default state without the lookup table: LLDB case. 8362 if (!SharedState) { 8363 this->SharedState = std::make_shared<ASTImporterSharedState>(); 8364 } 8365 8366 ImportedDecls[FromContext.getTranslationUnitDecl()] = 8367 ToContext.getTranslationUnitDecl(); 8368 } 8369 8370 ASTImporter::~ASTImporter() = default; 8371 8372 Optional<unsigned> ASTImporter::getFieldIndex(Decl *F) { 8373 assert(F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl>(*F)) && 8374 "Try to get field index for non-field."); 8375 8376 auto *Owner = dyn_cast<RecordDecl>(F->getDeclContext()); 8377 if (!Owner) 8378 return None; 8379 8380 unsigned Index = 0; 8381 for (const auto *D : Owner->decls()) { 8382 if (D == F) 8383 return Index; 8384 8385 if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) 8386 ++Index; 8387 } 8388 8389 llvm_unreachable("Field was not found in its parent context."); 8390 8391 return None; 8392 } 8393 8394 ASTImporter::FoundDeclsTy 8395 ASTImporter::findDeclsInToCtx(DeclContext *DC, DeclarationName Name) { 8396 // We search in the redecl context because of transparent contexts. 8397 // E.g. a simple C language enum is a transparent context: 8398 // enum E { A, B }; 8399 // Now if we had a global variable in the TU 8400 // int A; 8401 // then the enum constant 'A' and the variable 'A' violates ODR. 8402 // We can diagnose this only if we search in the redecl context. 8403 DeclContext *ReDC = DC->getRedeclContext(); 8404 if (SharedState->getLookupTable()) { 8405 ASTImporterLookupTable::LookupResult LookupResult = 8406 SharedState->getLookupTable()->lookup(ReDC, Name); 8407 return FoundDeclsTy(LookupResult.begin(), LookupResult.end()); 8408 } else { 8409 DeclContext::lookup_result NoloadLookupResult = ReDC->noload_lookup(Name); 8410 FoundDeclsTy Result(NoloadLookupResult.begin(), NoloadLookupResult.end()); 8411 // We must search by the slow case of localUncachedLookup because that is 8412 // working even if there is no LookupPtr for the DC. We could use 8413 // DC::buildLookup() to create the LookupPtr, but that would load external 8414 // decls again, we must avoid that case. 8415 // Also, even if we had the LookupPtr, we must find Decls which are not 8416 // in the LookupPtr, so we need the slow case. 8417 // These cases are handled in ASTImporterLookupTable, but we cannot use 8418 // that with LLDB since that traverses through the AST which initiates the 8419 // load of external decls again via DC::decls(). And again, we must avoid 8420 // loading external decls during the import. 8421 if (Result.empty()) 8422 ReDC->localUncachedLookup(Name, Result); 8423 return Result; 8424 } 8425 } 8426 8427 void ASTImporter::AddToLookupTable(Decl *ToD) { 8428 SharedState->addDeclToLookup(ToD); 8429 } 8430 8431 Expected<Decl *> ASTImporter::ImportImpl(Decl *FromD) { 8432 // Import the decl using ASTNodeImporter. 8433 ASTNodeImporter Importer(*this); 8434 return Importer.Visit(FromD); 8435 } 8436 8437 void ASTImporter::RegisterImportedDecl(Decl *FromD, Decl *ToD) { 8438 MapImported(FromD, ToD); 8439 } 8440 8441 llvm::Expected<ExprWithCleanups::CleanupObject> 8442 ASTImporter::Import(ExprWithCleanups::CleanupObject From) { 8443 if (auto *CLE = From.dyn_cast<CompoundLiteralExpr *>()) { 8444 if (Expected<Expr *> R = Import(CLE)) 8445 return ExprWithCleanups::CleanupObject(cast<CompoundLiteralExpr>(*R)); 8446 } 8447 8448 // FIXME: Handle BlockDecl when we implement importing BlockExpr in 8449 // ASTNodeImporter. 8450 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct); 8451 } 8452 8453 ExpectedTypePtr ASTImporter::Import(const Type *FromT) { 8454 if (!FromT) 8455 return FromT; 8456 8457 // Check whether we've already imported this type. 8458 llvm::DenseMap<const Type *, const Type *>::iterator Pos = 8459 ImportedTypes.find(FromT); 8460 if (Pos != ImportedTypes.end()) 8461 return Pos->second; 8462 8463 // Import the type. 8464 ASTNodeImporter Importer(*this); 8465 ExpectedType ToTOrErr = Importer.Visit(FromT); 8466 if (!ToTOrErr) 8467 return ToTOrErr.takeError(); 8468 8469 // Record the imported type. 8470 ImportedTypes[FromT] = ToTOrErr->getTypePtr(); 8471 8472 return ToTOrErr->getTypePtr(); 8473 } 8474 8475 Expected<QualType> ASTImporter::Import(QualType FromT) { 8476 if (FromT.isNull()) 8477 return QualType{}; 8478 8479 ExpectedTypePtr ToTyOrErr = Import(FromT.getTypePtr()); 8480 if (!ToTyOrErr) 8481 return ToTyOrErr.takeError(); 8482 8483 return ToContext.getQualifiedType(*ToTyOrErr, FromT.getLocalQualifiers()); 8484 } 8485 8486 Expected<TypeSourceInfo *> ASTImporter::Import(TypeSourceInfo *FromTSI) { 8487 if (!FromTSI) 8488 return FromTSI; 8489 8490 // FIXME: For now we just create a "trivial" type source info based 8491 // on the type and a single location. Implement a real version of this. 8492 ExpectedType TOrErr = Import(FromTSI->getType()); 8493 if (!TOrErr) 8494 return TOrErr.takeError(); 8495 ExpectedSLoc BeginLocOrErr = Import(FromTSI->getTypeLoc().getBeginLoc()); 8496 if (!BeginLocOrErr) 8497 return BeginLocOrErr.takeError(); 8498 8499 return ToContext.getTrivialTypeSourceInfo(*TOrErr, *BeginLocOrErr); 8500 } 8501 8502 // To use this object, it should be created before the new attribute is created, 8503 // and destructed after it is created. The construction already performs the 8504 // import of the data. 8505 template <typename T> struct AttrArgImporter { 8506 AttrArgImporter(const AttrArgImporter<T> &) = delete; 8507 AttrArgImporter(AttrArgImporter<T> &&) = default; 8508 AttrArgImporter<T> &operator=(const AttrArgImporter<T> &) = delete; 8509 AttrArgImporter<T> &operator=(AttrArgImporter<T> &&) = default; 8510 8511 AttrArgImporter(ASTNodeImporter &I, Error &Err, const T &From) 8512 : To(I.importChecked(Err, From)) {} 8513 8514 const T &value() { return To; } 8515 8516 private: 8517 T To; 8518 }; 8519 8520 // To use this object, it should be created before the new attribute is created, 8521 // and destructed after it is created. The construction already performs the 8522 // import of the data. The array data is accessible in a pointer form, this form 8523 // is used by the attribute classes. This object should be created once for the 8524 // array data to be imported (the array size is not imported, just copied). 8525 template <typename T> struct AttrArgArrayImporter { 8526 AttrArgArrayImporter(const AttrArgArrayImporter<T> &) = delete; 8527 AttrArgArrayImporter(AttrArgArrayImporter<T> &&) = default; 8528 AttrArgArrayImporter<T> &operator=(const AttrArgArrayImporter<T> &) = delete; 8529 AttrArgArrayImporter<T> &operator=(AttrArgArrayImporter<T> &&) = default; 8530 8531 AttrArgArrayImporter(ASTNodeImporter &I, Error &Err, 8532 const llvm::iterator_range<T *> &From, 8533 unsigned ArraySize) { 8534 if (Err) 8535 return; 8536 To.reserve(ArraySize); 8537 Err = I.ImportContainerChecked(From, To); 8538 } 8539 8540 T *value() { return To.data(); } 8541 8542 private: 8543 llvm::SmallVector<T, 2> To; 8544 }; 8545 8546 class AttrImporter { 8547 Error Err{Error::success()}; 8548 Attr *ToAttr = nullptr; 8549 ASTImporter &Importer; 8550 ASTNodeImporter NImporter; 8551 8552 public: 8553 AttrImporter(ASTImporter &I) : Importer(I), NImporter(I) {} 8554 8555 // Create an "importer" for an attribute parameter. 8556 // Result of the 'value()' of that object is to be passed to the function 8557 // 'importAttr', in the order that is expected by the attribute class. 8558 template <class T> AttrArgImporter<T> importArg(const T &From) { 8559 return AttrArgImporter<T>(NImporter, Err, From); 8560 } 8561 8562 // Create an "importer" for an attribute parameter that has array type. 8563 // Result of the 'value()' of that object is to be passed to the function 8564 // 'importAttr', then the size of the array as next argument. 8565 template <typename T> 8566 AttrArgArrayImporter<T> importArrayArg(const llvm::iterator_range<T *> &From, 8567 unsigned ArraySize) { 8568 return AttrArgArrayImporter<T>(NImporter, Err, From, ArraySize); 8569 } 8570 8571 // Create an attribute object with the specified arguments. 8572 // The 'FromAttr' is the original (not imported) attribute, the 'ImportedArg' 8573 // should be values that are passed to the 'Create' function of the attribute. 8574 // (The 'Create' with 'ASTContext' first and 'AttributeCommonInfo' last is 8575 // used here.) As much data is copied or imported from the old attribute 8576 // as possible. The passed arguments should be already imported. 8577 // If an import error happens, the internal error is set to it, and any 8578 // further import attempt is ignored. 8579 template <typename T, typename... Arg> 8580 void importAttr(const T *FromAttr, Arg &&...ImportedArg) { 8581 static_assert(std::is_base_of<Attr, T>::value, 8582 "T should be subclass of Attr."); 8583 assert(!ToAttr && "Use one AttrImporter to import one Attribute object."); 8584 8585 const IdentifierInfo *ToAttrName = Importer.Import(FromAttr->getAttrName()); 8586 const IdentifierInfo *ToScopeName = 8587 Importer.Import(FromAttr->getScopeName()); 8588 SourceRange ToAttrRange = 8589 NImporter.importChecked(Err, FromAttr->getRange()); 8590 SourceLocation ToScopeLoc = 8591 NImporter.importChecked(Err, FromAttr->getScopeLoc()); 8592 8593 if (Err) 8594 return; 8595 8596 AttributeCommonInfo ToI(ToAttrName, ToScopeName, ToAttrRange, ToScopeLoc, 8597 FromAttr->getParsedKind(), FromAttr->getSyntax(), 8598 FromAttr->getAttributeSpellingListIndex()); 8599 // The "SemanticSpelling" is not needed to be passed to the constructor. 8600 // That value is recalculated from the SpellingListIndex if needed. 8601 ToAttr = T::Create(Importer.getToContext(), 8602 std::forward<Arg>(ImportedArg)..., ToI); 8603 8604 ToAttr->setImplicit(FromAttr->isImplicit()); 8605 ToAttr->setPackExpansion(FromAttr->isPackExpansion()); 8606 if (auto *ToInheritableAttr = dyn_cast<InheritableAttr>(ToAttr)) 8607 ToInheritableAttr->setInherited(FromAttr->isInherited()); 8608 } 8609 8610 // Create a clone of the 'FromAttr' and import its source range only. 8611 // This causes objects with invalid references to be created if the 'FromAttr' 8612 // contains other data that should be imported. 8613 void cloneAttr(const Attr *FromAttr) { 8614 assert(!ToAttr && "Use one AttrImporter to import one Attribute object."); 8615 8616 SourceRange ToRange = NImporter.importChecked(Err, FromAttr->getRange()); 8617 if (Err) 8618 return; 8619 8620 ToAttr = FromAttr->clone(Importer.getToContext()); 8621 ToAttr->setRange(ToRange); 8622 } 8623 8624 // Get the result of the previous import attempt (can be used only once). 8625 llvm::Expected<Attr *> getResult() && { 8626 if (Err) 8627 return std::move(Err); 8628 assert(ToAttr && "Attribute should be created."); 8629 return ToAttr; 8630 } 8631 }; 8632 8633 Expected<Attr *> ASTImporter::Import(const Attr *FromAttr) { 8634 AttrImporter AI(*this); 8635 8636 // FIXME: Is there some kind of AttrVisitor to use here? 8637 switch (FromAttr->getKind()) { 8638 case attr::Aligned: { 8639 auto *From = cast<AlignedAttr>(FromAttr); 8640 if (From->isAlignmentExpr()) 8641 AI.importAttr(From, true, AI.importArg(From->getAlignmentExpr()).value()); 8642 else 8643 AI.importAttr(From, false, 8644 AI.importArg(From->getAlignmentType()).value()); 8645 break; 8646 } 8647 8648 case attr::Format: { 8649 const auto *From = cast<FormatAttr>(FromAttr); 8650 AI.importAttr(From, Import(From->getType()), From->getFormatIdx(), 8651 From->getFirstArg()); 8652 break; 8653 } 8654 8655 case attr::EnableIf: { 8656 const auto *From = cast<EnableIfAttr>(FromAttr); 8657 AI.importAttr(From, AI.importArg(From->getCond()).value(), 8658 From->getMessage()); 8659 break; 8660 } 8661 8662 case attr::AssertCapability: { 8663 const auto *From = cast<AssertCapabilityAttr>(FromAttr); 8664 AI.importAttr(From, 8665 AI.importArrayArg(From->args(), From->args_size()).value(), 8666 From->args_size()); 8667 break; 8668 } 8669 case attr::AcquireCapability: { 8670 const auto *From = cast<AcquireCapabilityAttr>(FromAttr); 8671 AI.importAttr(From, 8672 AI.importArrayArg(From->args(), From->args_size()).value(), 8673 From->args_size()); 8674 break; 8675 } 8676 case attr::TryAcquireCapability: { 8677 const auto *From = cast<TryAcquireCapabilityAttr>(FromAttr); 8678 AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(), 8679 AI.importArrayArg(From->args(), From->args_size()).value(), 8680 From->args_size()); 8681 break; 8682 } 8683 case attr::ReleaseCapability: { 8684 const auto *From = cast<ReleaseCapabilityAttr>(FromAttr); 8685 AI.importAttr(From, 8686 AI.importArrayArg(From->args(), From->args_size()).value(), 8687 From->args_size()); 8688 break; 8689 } 8690 case attr::RequiresCapability: { 8691 const auto *From = cast<RequiresCapabilityAttr>(FromAttr); 8692 AI.importAttr(From, 8693 AI.importArrayArg(From->args(), From->args_size()).value(), 8694 From->args_size()); 8695 break; 8696 } 8697 case attr::GuardedBy: { 8698 const auto *From = cast<GuardedByAttr>(FromAttr); 8699 AI.importAttr(From, AI.importArg(From->getArg()).value()); 8700 break; 8701 } 8702 case attr::PtGuardedBy: { 8703 const auto *From = cast<PtGuardedByAttr>(FromAttr); 8704 AI.importAttr(From, AI.importArg(From->getArg()).value()); 8705 break; 8706 } 8707 case attr::AcquiredAfter: { 8708 const auto *From = cast<AcquiredAfterAttr>(FromAttr); 8709 AI.importAttr(From, 8710 AI.importArrayArg(From->args(), From->args_size()).value(), 8711 From->args_size()); 8712 break; 8713 } 8714 case attr::AcquiredBefore: { 8715 const auto *From = cast<AcquiredBeforeAttr>(FromAttr); 8716 AI.importAttr(From, 8717 AI.importArrayArg(From->args(), From->args_size()).value(), 8718 From->args_size()); 8719 break; 8720 } 8721 case attr::AssertExclusiveLock: { 8722 const auto *From = cast<AssertExclusiveLockAttr>(FromAttr); 8723 AI.importAttr(From, 8724 AI.importArrayArg(From->args(), From->args_size()).value(), 8725 From->args_size()); 8726 break; 8727 } 8728 case attr::AssertSharedLock: { 8729 const auto *From = cast<AssertSharedLockAttr>(FromAttr); 8730 AI.importAttr(From, 8731 AI.importArrayArg(From->args(), From->args_size()).value(), 8732 From->args_size()); 8733 break; 8734 } 8735 case attr::ExclusiveTrylockFunction: { 8736 const auto *From = cast<ExclusiveTrylockFunctionAttr>(FromAttr); 8737 AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(), 8738 AI.importArrayArg(From->args(), From->args_size()).value(), 8739 From->args_size()); 8740 break; 8741 } 8742 case attr::SharedTrylockFunction: { 8743 const auto *From = cast<SharedTrylockFunctionAttr>(FromAttr); 8744 AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(), 8745 AI.importArrayArg(From->args(), From->args_size()).value(), 8746 From->args_size()); 8747 break; 8748 } 8749 case attr::LockReturned: { 8750 const auto *From = cast<LockReturnedAttr>(FromAttr); 8751 AI.importAttr(From, AI.importArg(From->getArg()).value()); 8752 break; 8753 } 8754 case attr::LocksExcluded: { 8755 const auto *From = cast<LocksExcludedAttr>(FromAttr); 8756 AI.importAttr(From, 8757 AI.importArrayArg(From->args(), From->args_size()).value(), 8758 From->args_size()); 8759 break; 8760 } 8761 8762 default: { 8763 // The default branch works for attributes that have no arguments to import. 8764 // FIXME: Handle every attribute type that has arguments of type to import 8765 // (most often Expr* or Decl* or type) in the switch above. 8766 AI.cloneAttr(FromAttr); 8767 break; 8768 } 8769 } 8770 8771 return std::move(AI).getResult(); 8772 } 8773 8774 Decl *ASTImporter::GetAlreadyImportedOrNull(const Decl *FromD) const { 8775 auto Pos = ImportedDecls.find(FromD); 8776 if (Pos != ImportedDecls.end()) 8777 return Pos->second; 8778 else 8779 return nullptr; 8780 } 8781 8782 TranslationUnitDecl *ASTImporter::GetFromTU(Decl *ToD) { 8783 auto FromDPos = ImportedFromDecls.find(ToD); 8784 if (FromDPos == ImportedFromDecls.end()) 8785 return nullptr; 8786 return FromDPos->second->getTranslationUnitDecl(); 8787 } 8788 8789 Expected<Decl *> ASTImporter::Import(Decl *FromD) { 8790 if (!FromD) 8791 return nullptr; 8792 8793 // Push FromD to the stack, and remove that when we return. 8794 ImportPath.push(FromD); 8795 auto ImportPathBuilder = 8796 llvm::make_scope_exit([this]() { ImportPath.pop(); }); 8797 8798 // Check whether there was a previous failed import. 8799 // If yes return the existing error. 8800 if (auto Error = getImportDeclErrorIfAny(FromD)) 8801 return make_error<ASTImportError>(*Error); 8802 8803 // Check whether we've already imported this declaration. 8804 Decl *ToD = GetAlreadyImportedOrNull(FromD); 8805 if (ToD) { 8806 // Already imported (possibly from another TU) and with an error. 8807 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) { 8808 setImportDeclError(FromD, *Error); 8809 return make_error<ASTImportError>(*Error); 8810 } 8811 8812 // If FromD has some updated flags after last import, apply it. 8813 updateFlags(FromD, ToD); 8814 // If we encounter a cycle during an import then we save the relevant part 8815 // of the import path associated to the Decl. 8816 if (ImportPath.hasCycleAtBack()) 8817 SavedImportPaths[FromD].push_back(ImportPath.copyCycleAtBack()); 8818 return ToD; 8819 } 8820 8821 // Import the declaration. 8822 ExpectedDecl ToDOrErr = ImportImpl(FromD); 8823 if (!ToDOrErr) { 8824 // Failed to import. 8825 8826 auto Pos = ImportedDecls.find(FromD); 8827 if (Pos != ImportedDecls.end()) { 8828 // Import failed after the object was created. 8829 // Remove all references to it. 8830 auto *ToD = Pos->second; 8831 ImportedDecls.erase(Pos); 8832 8833 // ImportedDecls and ImportedFromDecls are not symmetric. It may happen 8834 // (e.g. with namespaces) that several decls from the 'from' context are 8835 // mapped to the same decl in the 'to' context. If we removed entries 8836 // from the LookupTable here then we may end up removing them multiple 8837 // times. 8838 8839 // The Lookuptable contains decls only which are in the 'to' context. 8840 // Remove from the Lookuptable only if it is *imported* into the 'to' 8841 // context (and do not remove it if it was added during the initial 8842 // traverse of the 'to' context). 8843 auto PosF = ImportedFromDecls.find(ToD); 8844 if (PosF != ImportedFromDecls.end()) { 8845 // In the case of TypedefNameDecl we create the Decl first and only 8846 // then we import and set its DeclContext. So, the DC might not be set 8847 // when we reach here. 8848 if (ToD->getDeclContext()) 8849 SharedState->removeDeclFromLookup(ToD); 8850 ImportedFromDecls.erase(PosF); 8851 } 8852 8853 // FIXME: AST may contain remaining references to the failed object. 8854 // However, the ImportDeclErrors in the shared state contains all the 8855 // failed objects together with their error. 8856 } 8857 8858 // Error encountered for the first time. 8859 // After takeError the error is not usable any more in ToDOrErr. 8860 // Get a copy of the error object (any more simple solution for this?). 8861 ASTImportError ErrOut; 8862 handleAllErrors(ToDOrErr.takeError(), 8863 [&ErrOut](const ASTImportError &E) { ErrOut = E; }); 8864 setImportDeclError(FromD, ErrOut); 8865 // Set the error for the mapped to Decl, which is in the "to" context. 8866 if (Pos != ImportedDecls.end()) 8867 SharedState->setImportDeclError(Pos->second, ErrOut); 8868 8869 // Set the error for all nodes which have been created before we 8870 // recognized the error. 8871 for (const auto &Path : SavedImportPaths[FromD]) { 8872 // The import path contains import-dependency nodes first. 8873 // Save the node that was imported as dependency of the current node. 8874 Decl *PrevFromDi = FromD; 8875 for (Decl *FromDi : Path) { 8876 // Begin and end of the path equals 'FromD', skip it. 8877 if (FromDi == FromD) 8878 continue; 8879 // We should not set import error on a node and all following nodes in 8880 // the path if child import errors are ignored. 8881 if (ChildErrorHandlingStrategy(FromDi).ignoreChildErrorOnParent( 8882 PrevFromDi)) 8883 break; 8884 PrevFromDi = FromDi; 8885 setImportDeclError(FromDi, ErrOut); 8886 //FIXME Should we remove these Decls from ImportedDecls? 8887 // Set the error for the mapped to Decl, which is in the "to" context. 8888 auto Ii = ImportedDecls.find(FromDi); 8889 if (Ii != ImportedDecls.end()) 8890 SharedState->setImportDeclError(Ii->second, ErrOut); 8891 // FIXME Should we remove these Decls from the LookupTable, 8892 // and from ImportedFromDecls? 8893 } 8894 } 8895 SavedImportPaths.erase(FromD); 8896 8897 // Do not return ToDOrErr, error was taken out of it. 8898 return make_error<ASTImportError>(ErrOut); 8899 } 8900 8901 ToD = *ToDOrErr; 8902 8903 // FIXME: Handle the "already imported with error" case. We can get here 8904 // nullptr only if GetImportedOrCreateDecl returned nullptr (after a 8905 // previously failed create was requested). 8906 // Later GetImportedOrCreateDecl can be updated to return the error. 8907 if (!ToD) { 8908 auto Err = getImportDeclErrorIfAny(FromD); 8909 assert(Err); 8910 return make_error<ASTImportError>(*Err); 8911 } 8912 8913 // We could import from the current TU without error. But previously we 8914 // already had imported a Decl as `ToD` from another TU (with another 8915 // ASTImporter object) and with an error. 8916 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) { 8917 setImportDeclError(FromD, *Error); 8918 return make_error<ASTImportError>(*Error); 8919 } 8920 8921 // Make sure that ImportImpl registered the imported decl. 8922 assert(ImportedDecls.count(FromD) != 0 && "Missing call to MapImported?"); 8923 8924 if (FromD->hasAttrs()) 8925 for (const Attr *FromAttr : FromD->getAttrs()) { 8926 auto ToAttrOrErr = Import(FromAttr); 8927 if (ToAttrOrErr) 8928 ToD->addAttr(*ToAttrOrErr); 8929 else 8930 return ToAttrOrErr.takeError(); 8931 } 8932 8933 // Notify subclasses. 8934 Imported(FromD, ToD); 8935 8936 updateFlags(FromD, ToD); 8937 SavedImportPaths.erase(FromD); 8938 return ToDOrErr; 8939 } 8940 8941 llvm::Expected<InheritedConstructor> 8942 ASTImporter::Import(const InheritedConstructor &From) { 8943 return ASTNodeImporter(*this).ImportInheritedConstructor(From); 8944 } 8945 8946 Expected<DeclContext *> ASTImporter::ImportContext(DeclContext *FromDC) { 8947 if (!FromDC) 8948 return FromDC; 8949 8950 ExpectedDecl ToDCOrErr = Import(cast<Decl>(FromDC)); 8951 if (!ToDCOrErr) 8952 return ToDCOrErr.takeError(); 8953 auto *ToDC = cast<DeclContext>(*ToDCOrErr); 8954 8955 // When we're using a record/enum/Objective-C class/protocol as a context, we 8956 // need it to have a definition. 8957 if (auto *ToRecord = dyn_cast<RecordDecl>(ToDC)) { 8958 auto *FromRecord = cast<RecordDecl>(FromDC); 8959 if (ToRecord->isCompleteDefinition()) 8960 return ToDC; 8961 8962 // If FromRecord is not defined we need to force it to be. 8963 // Simply calling CompleteDecl(...) for a RecordDecl will break some cases 8964 // it will start the definition but we never finish it. 8965 // If there are base classes they won't be imported and we will 8966 // be missing anything that we inherit from those bases. 8967 if (FromRecord->getASTContext().getExternalSource() && 8968 !FromRecord->isCompleteDefinition()) 8969 FromRecord->getASTContext().getExternalSource()->CompleteType(FromRecord); 8970 8971 if (FromRecord->isCompleteDefinition()) 8972 if (Error Err = ASTNodeImporter(*this).ImportDefinition( 8973 FromRecord, ToRecord, ASTNodeImporter::IDK_Basic)) 8974 return std::move(Err); 8975 } else if (auto *ToEnum = dyn_cast<EnumDecl>(ToDC)) { 8976 auto *FromEnum = cast<EnumDecl>(FromDC); 8977 if (ToEnum->isCompleteDefinition()) { 8978 // Do nothing. 8979 } else if (FromEnum->isCompleteDefinition()) { 8980 if (Error Err = ASTNodeImporter(*this).ImportDefinition( 8981 FromEnum, ToEnum, ASTNodeImporter::IDK_Basic)) 8982 return std::move(Err); 8983 } else { 8984 CompleteDecl(ToEnum); 8985 } 8986 } else if (auto *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) { 8987 auto *FromClass = cast<ObjCInterfaceDecl>(FromDC); 8988 if (ToClass->getDefinition()) { 8989 // Do nothing. 8990 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) { 8991 if (Error Err = ASTNodeImporter(*this).ImportDefinition( 8992 FromDef, ToClass, ASTNodeImporter::IDK_Basic)) 8993 return std::move(Err); 8994 } else { 8995 CompleteDecl(ToClass); 8996 } 8997 } else if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) { 8998 auto *FromProto = cast<ObjCProtocolDecl>(FromDC); 8999 if (ToProto->getDefinition()) { 9000 // Do nothing. 9001 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) { 9002 if (Error Err = ASTNodeImporter(*this).ImportDefinition( 9003 FromDef, ToProto, ASTNodeImporter::IDK_Basic)) 9004 return std::move(Err); 9005 } else { 9006 CompleteDecl(ToProto); 9007 } 9008 } 9009 9010 return ToDC; 9011 } 9012 9013 Expected<Expr *> ASTImporter::Import(Expr *FromE) { 9014 if (ExpectedStmt ToSOrErr = Import(cast_or_null<Stmt>(FromE))) 9015 return cast_or_null<Expr>(*ToSOrErr); 9016 else 9017 return ToSOrErr.takeError(); 9018 } 9019 9020 Expected<Stmt *> ASTImporter::Import(Stmt *FromS) { 9021 if (!FromS) 9022 return nullptr; 9023 9024 // Check whether we've already imported this statement. 9025 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS); 9026 if (Pos != ImportedStmts.end()) 9027 return Pos->second; 9028 9029 // Import the statement. 9030 ASTNodeImporter Importer(*this); 9031 ExpectedStmt ToSOrErr = Importer.Visit(FromS); 9032 if (!ToSOrErr) 9033 return ToSOrErr; 9034 9035 if (auto *ToE = dyn_cast<Expr>(*ToSOrErr)) { 9036 auto *FromE = cast<Expr>(FromS); 9037 // Copy ExprBitfields, which may not be handled in Expr subclasses 9038 // constructors. 9039 ToE->setValueKind(FromE->getValueKind()); 9040 ToE->setObjectKind(FromE->getObjectKind()); 9041 ToE->setDependence(FromE->getDependence()); 9042 } 9043 9044 // Record the imported statement object. 9045 ImportedStmts[FromS] = *ToSOrErr; 9046 return ToSOrErr; 9047 } 9048 9049 Expected<NestedNameSpecifier *> 9050 ASTImporter::Import(NestedNameSpecifier *FromNNS) { 9051 if (!FromNNS) 9052 return nullptr; 9053 9054 NestedNameSpecifier *Prefix = nullptr; 9055 if (Error Err = importInto(Prefix, FromNNS->getPrefix())) 9056 return std::move(Err); 9057 9058 switch (FromNNS->getKind()) { 9059 case NestedNameSpecifier::Identifier: 9060 assert(FromNNS->getAsIdentifier() && "NNS should contain identifier."); 9061 return NestedNameSpecifier::Create(ToContext, Prefix, 9062 Import(FromNNS->getAsIdentifier())); 9063 9064 case NestedNameSpecifier::Namespace: 9065 if (ExpectedDecl NSOrErr = Import(FromNNS->getAsNamespace())) { 9066 return NestedNameSpecifier::Create(ToContext, Prefix, 9067 cast<NamespaceDecl>(*NSOrErr)); 9068 } else 9069 return NSOrErr.takeError(); 9070 9071 case NestedNameSpecifier::NamespaceAlias: 9072 if (ExpectedDecl NSADOrErr = Import(FromNNS->getAsNamespaceAlias())) 9073 return NestedNameSpecifier::Create(ToContext, Prefix, 9074 cast<NamespaceAliasDecl>(*NSADOrErr)); 9075 else 9076 return NSADOrErr.takeError(); 9077 9078 case NestedNameSpecifier::Global: 9079 return NestedNameSpecifier::GlobalSpecifier(ToContext); 9080 9081 case NestedNameSpecifier::Super: 9082 if (ExpectedDecl RDOrErr = Import(FromNNS->getAsRecordDecl())) 9083 return NestedNameSpecifier::SuperSpecifier(ToContext, 9084 cast<CXXRecordDecl>(*RDOrErr)); 9085 else 9086 return RDOrErr.takeError(); 9087 9088 case NestedNameSpecifier::TypeSpec: 9089 case NestedNameSpecifier::TypeSpecWithTemplate: 9090 if (ExpectedTypePtr TyOrErr = Import(FromNNS->getAsType())) { 9091 bool TSTemplate = 9092 FromNNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate; 9093 return NestedNameSpecifier::Create(ToContext, Prefix, TSTemplate, 9094 *TyOrErr); 9095 } else { 9096 return TyOrErr.takeError(); 9097 } 9098 } 9099 9100 llvm_unreachable("Invalid nested name specifier kind"); 9101 } 9102 9103 Expected<NestedNameSpecifierLoc> 9104 ASTImporter::Import(NestedNameSpecifierLoc FromNNS) { 9105 // Copied from NestedNameSpecifier mostly. 9106 SmallVector<NestedNameSpecifierLoc , 8> NestedNames; 9107 NestedNameSpecifierLoc NNS = FromNNS; 9108 9109 // Push each of the nested-name-specifiers's onto a stack for 9110 // serialization in reverse order. 9111 while (NNS) { 9112 NestedNames.push_back(NNS); 9113 NNS = NNS.getPrefix(); 9114 } 9115 9116 NestedNameSpecifierLocBuilder Builder; 9117 9118 while (!NestedNames.empty()) { 9119 NNS = NestedNames.pop_back_val(); 9120 NestedNameSpecifier *Spec = nullptr; 9121 if (Error Err = importInto(Spec, NNS.getNestedNameSpecifier())) 9122 return std::move(Err); 9123 9124 NestedNameSpecifier::SpecifierKind Kind = Spec->getKind(); 9125 9126 SourceLocation ToLocalBeginLoc, ToLocalEndLoc; 9127 if (Kind != NestedNameSpecifier::Super) { 9128 if (Error Err = importInto(ToLocalBeginLoc, NNS.getLocalBeginLoc())) 9129 return std::move(Err); 9130 9131 if (Kind != NestedNameSpecifier::Global) 9132 if (Error Err = importInto(ToLocalEndLoc, NNS.getLocalEndLoc())) 9133 return std::move(Err); 9134 } 9135 9136 switch (Kind) { 9137 case NestedNameSpecifier::Identifier: 9138 Builder.Extend(getToContext(), Spec->getAsIdentifier(), ToLocalBeginLoc, 9139 ToLocalEndLoc); 9140 break; 9141 9142 case NestedNameSpecifier::Namespace: 9143 Builder.Extend(getToContext(), Spec->getAsNamespace(), ToLocalBeginLoc, 9144 ToLocalEndLoc); 9145 break; 9146 9147 case NestedNameSpecifier::NamespaceAlias: 9148 Builder.Extend(getToContext(), Spec->getAsNamespaceAlias(), 9149 ToLocalBeginLoc, ToLocalEndLoc); 9150 break; 9151 9152 case NestedNameSpecifier::TypeSpec: 9153 case NestedNameSpecifier::TypeSpecWithTemplate: { 9154 SourceLocation ToTLoc; 9155 if (Error Err = importInto(ToTLoc, NNS.getTypeLoc().getBeginLoc())) 9156 return std::move(Err); 9157 TypeSourceInfo *TSI = getToContext().getTrivialTypeSourceInfo( 9158 QualType(Spec->getAsType(), 0), ToTLoc); 9159 if (Kind == NestedNameSpecifier::TypeSpecWithTemplate) 9160 // ToLocalBeginLoc is here the location of the 'template' keyword. 9161 Builder.Extend(getToContext(), ToLocalBeginLoc, TSI->getTypeLoc(), 9162 ToLocalEndLoc); 9163 else 9164 // No location for 'template' keyword here. 9165 Builder.Extend(getToContext(), SourceLocation{}, TSI->getTypeLoc(), 9166 ToLocalEndLoc); 9167 break; 9168 } 9169 9170 case NestedNameSpecifier::Global: 9171 Builder.MakeGlobal(getToContext(), ToLocalBeginLoc); 9172 break; 9173 9174 case NestedNameSpecifier::Super: { 9175 auto ToSourceRangeOrErr = Import(NNS.getSourceRange()); 9176 if (!ToSourceRangeOrErr) 9177 return ToSourceRangeOrErr.takeError(); 9178 9179 Builder.MakeSuper(getToContext(), Spec->getAsRecordDecl(), 9180 ToSourceRangeOrErr->getBegin(), 9181 ToSourceRangeOrErr->getEnd()); 9182 } 9183 } 9184 } 9185 9186 return Builder.getWithLocInContext(getToContext()); 9187 } 9188 9189 Expected<TemplateName> ASTImporter::Import(TemplateName From) { 9190 switch (From.getKind()) { 9191 case TemplateName::Template: 9192 if (ExpectedDecl ToTemplateOrErr = Import(From.getAsTemplateDecl())) 9193 return TemplateName(cast<TemplateDecl>(*ToTemplateOrErr)); 9194 else 9195 return ToTemplateOrErr.takeError(); 9196 9197 case TemplateName::OverloadedTemplate: { 9198 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate(); 9199 UnresolvedSet<2> ToTemplates; 9200 for (auto *I : *FromStorage) { 9201 if (auto ToOrErr = Import(I)) 9202 ToTemplates.addDecl(cast<NamedDecl>(*ToOrErr)); 9203 else 9204 return ToOrErr.takeError(); 9205 } 9206 return ToContext.getOverloadedTemplateName(ToTemplates.begin(), 9207 ToTemplates.end()); 9208 } 9209 9210 case TemplateName::AssumedTemplate: { 9211 AssumedTemplateStorage *FromStorage = From.getAsAssumedTemplateName(); 9212 auto DeclNameOrErr = Import(FromStorage->getDeclName()); 9213 if (!DeclNameOrErr) 9214 return DeclNameOrErr.takeError(); 9215 return ToContext.getAssumedTemplateName(*DeclNameOrErr); 9216 } 9217 9218 case TemplateName::QualifiedTemplate: { 9219 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName(); 9220 auto QualifierOrErr = Import(QTN->getQualifier()); 9221 if (!QualifierOrErr) 9222 return QualifierOrErr.takeError(); 9223 auto TNOrErr = Import(QTN->getUnderlyingTemplate()); 9224 if (!TNOrErr) 9225 return TNOrErr.takeError(); 9226 return ToContext.getQualifiedTemplateName( 9227 *QualifierOrErr, QTN->hasTemplateKeyword(), *TNOrErr); 9228 } 9229 9230 case TemplateName::DependentTemplate: { 9231 DependentTemplateName *DTN = From.getAsDependentTemplateName(); 9232 auto QualifierOrErr = Import(DTN->getQualifier()); 9233 if (!QualifierOrErr) 9234 return QualifierOrErr.takeError(); 9235 9236 if (DTN->isIdentifier()) { 9237 return ToContext.getDependentTemplateName(*QualifierOrErr, 9238 Import(DTN->getIdentifier())); 9239 } 9240 9241 return ToContext.getDependentTemplateName(*QualifierOrErr, 9242 DTN->getOperator()); 9243 } 9244 9245 case TemplateName::SubstTemplateTemplateParm: { 9246 SubstTemplateTemplateParmStorage *Subst = 9247 From.getAsSubstTemplateTemplateParm(); 9248 ExpectedDecl ParamOrErr = Import(Subst->getParameter()); 9249 if (!ParamOrErr) 9250 return ParamOrErr.takeError(); 9251 9252 auto ReplacementOrErr = Import(Subst->getReplacement()); 9253 if (!ReplacementOrErr) 9254 return ReplacementOrErr.takeError(); 9255 9256 return ToContext.getSubstTemplateTemplateParm( 9257 cast<TemplateTemplateParmDecl>(*ParamOrErr), *ReplacementOrErr); 9258 } 9259 9260 case TemplateName::SubstTemplateTemplateParmPack: { 9261 SubstTemplateTemplateParmPackStorage *SubstPack 9262 = From.getAsSubstTemplateTemplateParmPack(); 9263 ExpectedDecl ParamOrErr = Import(SubstPack->getParameterPack()); 9264 if (!ParamOrErr) 9265 return ParamOrErr.takeError(); 9266 9267 ASTNodeImporter Importer(*this); 9268 auto ArgPackOrErr = 9269 Importer.ImportTemplateArgument(SubstPack->getArgumentPack()); 9270 if (!ArgPackOrErr) 9271 return ArgPackOrErr.takeError(); 9272 9273 return ToContext.getSubstTemplateTemplateParmPack( 9274 cast<TemplateTemplateParmDecl>(*ParamOrErr), *ArgPackOrErr); 9275 } 9276 case TemplateName::UsingTemplate: { 9277 auto UsingOrError = Import(From.getAsUsingShadowDecl()); 9278 if (!UsingOrError) 9279 return UsingOrError.takeError(); 9280 return TemplateName(cast<UsingShadowDecl>(*UsingOrError)); 9281 } 9282 } 9283 9284 llvm_unreachable("Invalid template name kind"); 9285 } 9286 9287 Expected<SourceLocation> ASTImporter::Import(SourceLocation FromLoc) { 9288 if (FromLoc.isInvalid()) 9289 return SourceLocation{}; 9290 9291 SourceManager &FromSM = FromContext.getSourceManager(); 9292 bool IsBuiltin = FromSM.isWrittenInBuiltinFile(FromLoc); 9293 9294 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc); 9295 Expected<FileID> ToFileIDOrErr = Import(Decomposed.first, IsBuiltin); 9296 if (!ToFileIDOrErr) 9297 return ToFileIDOrErr.takeError(); 9298 SourceManager &ToSM = ToContext.getSourceManager(); 9299 return ToSM.getComposedLoc(*ToFileIDOrErr, Decomposed.second); 9300 } 9301 9302 Expected<SourceRange> ASTImporter::Import(SourceRange FromRange) { 9303 SourceLocation ToBegin, ToEnd; 9304 if (Error Err = importInto(ToBegin, FromRange.getBegin())) 9305 return std::move(Err); 9306 if (Error Err = importInto(ToEnd, FromRange.getEnd())) 9307 return std::move(Err); 9308 9309 return SourceRange(ToBegin, ToEnd); 9310 } 9311 9312 Expected<FileID> ASTImporter::Import(FileID FromID, bool IsBuiltin) { 9313 llvm::DenseMap<FileID, FileID>::iterator Pos = ImportedFileIDs.find(FromID); 9314 if (Pos != ImportedFileIDs.end()) 9315 return Pos->second; 9316 9317 SourceManager &FromSM = FromContext.getSourceManager(); 9318 SourceManager &ToSM = ToContext.getSourceManager(); 9319 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID); 9320 9321 // Map the FromID to the "to" source manager. 9322 FileID ToID; 9323 if (FromSLoc.isExpansion()) { 9324 const SrcMgr::ExpansionInfo &FromEx = FromSLoc.getExpansion(); 9325 ExpectedSLoc ToSpLoc = Import(FromEx.getSpellingLoc()); 9326 if (!ToSpLoc) 9327 return ToSpLoc.takeError(); 9328 ExpectedSLoc ToExLocS = Import(FromEx.getExpansionLocStart()); 9329 if (!ToExLocS) 9330 return ToExLocS.takeError(); 9331 unsigned ExLength = FromSM.getFileIDSize(FromID); 9332 SourceLocation MLoc; 9333 if (FromEx.isMacroArgExpansion()) { 9334 MLoc = ToSM.createMacroArgExpansionLoc(*ToSpLoc, *ToExLocS, ExLength); 9335 } else { 9336 if (ExpectedSLoc ToExLocE = Import(FromEx.getExpansionLocEnd())) 9337 MLoc = ToSM.createExpansionLoc(*ToSpLoc, *ToExLocS, *ToExLocE, ExLength, 9338 FromEx.isExpansionTokenRange()); 9339 else 9340 return ToExLocE.takeError(); 9341 } 9342 ToID = ToSM.getFileID(MLoc); 9343 } else { 9344 const SrcMgr::ContentCache *Cache = &FromSLoc.getFile().getContentCache(); 9345 9346 if (!IsBuiltin && !Cache->BufferOverridden) { 9347 // Include location of this file. 9348 ExpectedSLoc ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc()); 9349 if (!ToIncludeLoc) 9350 return ToIncludeLoc.takeError(); 9351 9352 // Every FileID that is not the main FileID needs to have a valid include 9353 // location so that the include chain points to the main FileID. When 9354 // importing the main FileID (which has no include location), we need to 9355 // create a fake include location in the main file to keep this property 9356 // intact. 9357 SourceLocation ToIncludeLocOrFakeLoc = *ToIncludeLoc; 9358 if (FromID == FromSM.getMainFileID()) 9359 ToIncludeLocOrFakeLoc = ToSM.getLocForStartOfFile(ToSM.getMainFileID()); 9360 9361 if (Cache->OrigEntry && Cache->OrigEntry->getDir()) { 9362 // FIXME: We probably want to use getVirtualFile(), so we don't hit the 9363 // disk again 9364 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather 9365 // than mmap the files several times. 9366 auto Entry = 9367 ToFileManager.getOptionalFileRef(Cache->OrigEntry->getName()); 9368 // FIXME: The filename may be a virtual name that does probably not 9369 // point to a valid file and we get no Entry here. In this case try with 9370 // the memory buffer below. 9371 if (Entry) 9372 ToID = ToSM.createFileID(*Entry, ToIncludeLocOrFakeLoc, 9373 FromSLoc.getFile().getFileCharacteristic()); 9374 } 9375 } 9376 9377 if (ToID.isInvalid() || IsBuiltin) { 9378 // FIXME: We want to re-use the existing MemoryBuffer! 9379 llvm::Optional<llvm::MemoryBufferRef> FromBuf = 9380 Cache->getBufferOrNone(FromContext.getDiagnostics(), 9381 FromSM.getFileManager(), SourceLocation{}); 9382 if (!FromBuf) 9383 return llvm::make_error<ASTImportError>(ASTImportError::Unknown); 9384 9385 std::unique_ptr<llvm::MemoryBuffer> ToBuf = 9386 llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(), 9387 FromBuf->getBufferIdentifier()); 9388 ToID = ToSM.createFileID(std::move(ToBuf), 9389 FromSLoc.getFile().getFileCharacteristic()); 9390 } 9391 } 9392 9393 assert(ToID.isValid() && "Unexpected invalid fileID was created."); 9394 9395 ImportedFileIDs[FromID] = ToID; 9396 return ToID; 9397 } 9398 9399 Expected<CXXCtorInitializer *> ASTImporter::Import(CXXCtorInitializer *From) { 9400 ExpectedExpr ToExprOrErr = Import(From->getInit()); 9401 if (!ToExprOrErr) 9402 return ToExprOrErr.takeError(); 9403 9404 auto LParenLocOrErr = Import(From->getLParenLoc()); 9405 if (!LParenLocOrErr) 9406 return LParenLocOrErr.takeError(); 9407 9408 auto RParenLocOrErr = Import(From->getRParenLoc()); 9409 if (!RParenLocOrErr) 9410 return RParenLocOrErr.takeError(); 9411 9412 if (From->isBaseInitializer()) { 9413 auto ToTInfoOrErr = Import(From->getTypeSourceInfo()); 9414 if (!ToTInfoOrErr) 9415 return ToTInfoOrErr.takeError(); 9416 9417 SourceLocation EllipsisLoc; 9418 if (From->isPackExpansion()) 9419 if (Error Err = importInto(EllipsisLoc, From->getEllipsisLoc())) 9420 return std::move(Err); 9421 9422 return new (ToContext) CXXCtorInitializer( 9423 ToContext, *ToTInfoOrErr, From->isBaseVirtual(), *LParenLocOrErr, 9424 *ToExprOrErr, *RParenLocOrErr, EllipsisLoc); 9425 } else if (From->isMemberInitializer()) { 9426 ExpectedDecl ToFieldOrErr = Import(From->getMember()); 9427 if (!ToFieldOrErr) 9428 return ToFieldOrErr.takeError(); 9429 9430 auto MemberLocOrErr = Import(From->getMemberLocation()); 9431 if (!MemberLocOrErr) 9432 return MemberLocOrErr.takeError(); 9433 9434 return new (ToContext) CXXCtorInitializer( 9435 ToContext, cast_or_null<FieldDecl>(*ToFieldOrErr), *MemberLocOrErr, 9436 *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr); 9437 } else if (From->isIndirectMemberInitializer()) { 9438 ExpectedDecl ToIFieldOrErr = Import(From->getIndirectMember()); 9439 if (!ToIFieldOrErr) 9440 return ToIFieldOrErr.takeError(); 9441 9442 auto MemberLocOrErr = Import(From->getMemberLocation()); 9443 if (!MemberLocOrErr) 9444 return MemberLocOrErr.takeError(); 9445 9446 return new (ToContext) CXXCtorInitializer( 9447 ToContext, cast_or_null<IndirectFieldDecl>(*ToIFieldOrErr), 9448 *MemberLocOrErr, *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr); 9449 } else if (From->isDelegatingInitializer()) { 9450 auto ToTInfoOrErr = Import(From->getTypeSourceInfo()); 9451 if (!ToTInfoOrErr) 9452 return ToTInfoOrErr.takeError(); 9453 9454 return new (ToContext) 9455 CXXCtorInitializer(ToContext, *ToTInfoOrErr, *LParenLocOrErr, 9456 *ToExprOrErr, *RParenLocOrErr); 9457 } else { 9458 // FIXME: assert? 9459 return make_error<ASTImportError>(); 9460 } 9461 } 9462 9463 Expected<CXXBaseSpecifier *> 9464 ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) { 9465 auto Pos = ImportedCXXBaseSpecifiers.find(BaseSpec); 9466 if (Pos != ImportedCXXBaseSpecifiers.end()) 9467 return Pos->second; 9468 9469 Expected<SourceRange> ToSourceRange = Import(BaseSpec->getSourceRange()); 9470 if (!ToSourceRange) 9471 return ToSourceRange.takeError(); 9472 Expected<TypeSourceInfo *> ToTSI = Import(BaseSpec->getTypeSourceInfo()); 9473 if (!ToTSI) 9474 return ToTSI.takeError(); 9475 ExpectedSLoc ToEllipsisLoc = Import(BaseSpec->getEllipsisLoc()); 9476 if (!ToEllipsisLoc) 9477 return ToEllipsisLoc.takeError(); 9478 CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier( 9479 *ToSourceRange, BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(), 9480 BaseSpec->getAccessSpecifierAsWritten(), *ToTSI, *ToEllipsisLoc); 9481 ImportedCXXBaseSpecifiers[BaseSpec] = Imported; 9482 return Imported; 9483 } 9484 9485 llvm::Expected<APValue> ASTImporter::Import(const APValue &FromValue) { 9486 ASTNodeImporter Importer(*this); 9487 return Importer.ImportAPValue(FromValue); 9488 } 9489 9490 Error ASTImporter::ImportDefinition(Decl *From) { 9491 ExpectedDecl ToOrErr = Import(From); 9492 if (!ToOrErr) 9493 return ToOrErr.takeError(); 9494 Decl *To = *ToOrErr; 9495 9496 auto *FromDC = cast<DeclContext>(From); 9497 ASTNodeImporter Importer(*this); 9498 9499 if (auto *ToRecord = dyn_cast<RecordDecl>(To)) { 9500 if (!ToRecord->getDefinition()) { 9501 return Importer.ImportDefinition( 9502 cast<RecordDecl>(FromDC), ToRecord, 9503 ASTNodeImporter::IDK_Everything); 9504 } 9505 } 9506 9507 if (auto *ToEnum = dyn_cast<EnumDecl>(To)) { 9508 if (!ToEnum->getDefinition()) { 9509 return Importer.ImportDefinition( 9510 cast<EnumDecl>(FromDC), ToEnum, ASTNodeImporter::IDK_Everything); 9511 } 9512 } 9513 9514 if (auto *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) { 9515 if (!ToIFace->getDefinition()) { 9516 return Importer.ImportDefinition( 9517 cast<ObjCInterfaceDecl>(FromDC), ToIFace, 9518 ASTNodeImporter::IDK_Everything); 9519 } 9520 } 9521 9522 if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(To)) { 9523 if (!ToProto->getDefinition()) { 9524 return Importer.ImportDefinition( 9525 cast<ObjCProtocolDecl>(FromDC), ToProto, 9526 ASTNodeImporter::IDK_Everything); 9527 } 9528 } 9529 9530 return Importer.ImportDeclContext(FromDC, true); 9531 } 9532 9533 Expected<DeclarationName> ASTImporter::Import(DeclarationName FromName) { 9534 if (!FromName) 9535 return DeclarationName{}; 9536 9537 switch (FromName.getNameKind()) { 9538 case DeclarationName::Identifier: 9539 return DeclarationName(Import(FromName.getAsIdentifierInfo())); 9540 9541 case DeclarationName::ObjCZeroArgSelector: 9542 case DeclarationName::ObjCOneArgSelector: 9543 case DeclarationName::ObjCMultiArgSelector: 9544 if (auto ToSelOrErr = Import(FromName.getObjCSelector())) 9545 return DeclarationName(*ToSelOrErr); 9546 else 9547 return ToSelOrErr.takeError(); 9548 9549 case DeclarationName::CXXConstructorName: { 9550 if (auto ToTyOrErr = Import(FromName.getCXXNameType())) 9551 return ToContext.DeclarationNames.getCXXConstructorName( 9552 ToContext.getCanonicalType(*ToTyOrErr)); 9553 else 9554 return ToTyOrErr.takeError(); 9555 } 9556 9557 case DeclarationName::CXXDestructorName: { 9558 if (auto ToTyOrErr = Import(FromName.getCXXNameType())) 9559 return ToContext.DeclarationNames.getCXXDestructorName( 9560 ToContext.getCanonicalType(*ToTyOrErr)); 9561 else 9562 return ToTyOrErr.takeError(); 9563 } 9564 9565 case DeclarationName::CXXDeductionGuideName: { 9566 if (auto ToTemplateOrErr = Import(FromName.getCXXDeductionGuideTemplate())) 9567 return ToContext.DeclarationNames.getCXXDeductionGuideName( 9568 cast<TemplateDecl>(*ToTemplateOrErr)); 9569 else 9570 return ToTemplateOrErr.takeError(); 9571 } 9572 9573 case DeclarationName::CXXConversionFunctionName: { 9574 if (auto ToTyOrErr = Import(FromName.getCXXNameType())) 9575 return ToContext.DeclarationNames.getCXXConversionFunctionName( 9576 ToContext.getCanonicalType(*ToTyOrErr)); 9577 else 9578 return ToTyOrErr.takeError(); 9579 } 9580 9581 case DeclarationName::CXXOperatorName: 9582 return ToContext.DeclarationNames.getCXXOperatorName( 9583 FromName.getCXXOverloadedOperator()); 9584 9585 case DeclarationName::CXXLiteralOperatorName: 9586 return ToContext.DeclarationNames.getCXXLiteralOperatorName( 9587 Import(FromName.getCXXLiteralIdentifier())); 9588 9589 case DeclarationName::CXXUsingDirective: 9590 // FIXME: STATICS! 9591 return DeclarationName::getUsingDirectiveName(); 9592 } 9593 9594 llvm_unreachable("Invalid DeclarationName Kind!"); 9595 } 9596 9597 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) { 9598 if (!FromId) 9599 return nullptr; 9600 9601 IdentifierInfo *ToId = &ToContext.Idents.get(FromId->getName()); 9602 9603 if (!ToId->getBuiltinID() && FromId->getBuiltinID()) 9604 ToId->setBuiltinID(FromId->getBuiltinID()); 9605 9606 return ToId; 9607 } 9608 9609 Expected<Selector> ASTImporter::Import(Selector FromSel) { 9610 if (FromSel.isNull()) 9611 return Selector{}; 9612 9613 SmallVector<IdentifierInfo *, 4> Idents; 9614 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0))); 9615 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I) 9616 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I))); 9617 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data()); 9618 } 9619 9620 llvm::Expected<APValue> 9621 ASTNodeImporter::ImportAPValue(const APValue &FromValue) { 9622 APValue Result; 9623 llvm::Error Err = llvm::Error::success(); 9624 auto ImportLoop = [&](const APValue *From, APValue *To, unsigned Size) { 9625 for (unsigned Idx = 0; Idx < Size; Idx++) { 9626 APValue Tmp = importChecked(Err, From[Idx]); 9627 To[Idx] = Tmp; 9628 } 9629 }; 9630 switch (FromValue.getKind()) { 9631 case APValue::None: 9632 case APValue::Indeterminate: 9633 case APValue::Int: 9634 case APValue::Float: 9635 case APValue::FixedPoint: 9636 case APValue::ComplexInt: 9637 case APValue::ComplexFloat: 9638 Result = FromValue; 9639 break; 9640 case APValue::Vector: { 9641 Result.MakeVector(); 9642 MutableArrayRef<APValue> Elts = 9643 Result.setVectorUninit(FromValue.getVectorLength()); 9644 ImportLoop(((const APValue::Vec *)(const char *)&FromValue.Data)->Elts, 9645 Elts.data(), FromValue.getVectorLength()); 9646 break; 9647 } 9648 case APValue::Array: 9649 Result.MakeArray(FromValue.getArrayInitializedElts(), 9650 FromValue.getArraySize()); 9651 ImportLoop(((const APValue::Arr *)(const char *)&FromValue.Data)->Elts, 9652 ((const APValue::Arr *)(const char *)&Result.Data)->Elts, 9653 FromValue.getArrayInitializedElts()); 9654 break; 9655 case APValue::Struct: 9656 Result.MakeStruct(FromValue.getStructNumBases(), 9657 FromValue.getStructNumFields()); 9658 ImportLoop( 9659 ((const APValue::StructData *)(const char *)&FromValue.Data)->Elts, 9660 ((const APValue::StructData *)(const char *)&Result.Data)->Elts, 9661 FromValue.getStructNumBases() + FromValue.getStructNumFields()); 9662 break; 9663 case APValue::Union: { 9664 Result.MakeUnion(); 9665 const Decl *ImpFDecl = importChecked(Err, FromValue.getUnionField()); 9666 APValue ImpValue = importChecked(Err, FromValue.getUnionValue()); 9667 if (Err) 9668 return std::move(Err); 9669 Result.setUnion(cast<FieldDecl>(ImpFDecl), ImpValue); 9670 break; 9671 } 9672 case APValue::AddrLabelDiff: { 9673 Result.MakeAddrLabelDiff(); 9674 const Expr *ImpLHS = importChecked(Err, FromValue.getAddrLabelDiffLHS()); 9675 const Expr *ImpRHS = importChecked(Err, FromValue.getAddrLabelDiffRHS()); 9676 if (Err) 9677 return std::move(Err); 9678 Result.setAddrLabelDiff(cast<AddrLabelExpr>(ImpLHS), 9679 cast<AddrLabelExpr>(ImpRHS)); 9680 break; 9681 } 9682 case APValue::MemberPointer: { 9683 const Decl *ImpMemPtrDecl = 9684 importChecked(Err, FromValue.getMemberPointerDecl()); 9685 if (Err) 9686 return std::move(Err); 9687 MutableArrayRef<const CXXRecordDecl *> ToPath = 9688 Result.setMemberPointerUninit( 9689 cast<const ValueDecl>(ImpMemPtrDecl), 9690 FromValue.isMemberPointerToDerivedMember(), 9691 FromValue.getMemberPointerPath().size()); 9692 llvm::ArrayRef<const CXXRecordDecl *> FromPath = 9693 Result.getMemberPointerPath(); 9694 for (unsigned Idx = 0; Idx < FromValue.getMemberPointerPath().size(); 9695 Idx++) { 9696 const Decl *ImpDecl = importChecked(Err, FromPath[Idx]); 9697 if (Err) 9698 return std::move(Err); 9699 ToPath[Idx] = cast<const CXXRecordDecl>(ImpDecl->getCanonicalDecl()); 9700 } 9701 break; 9702 } 9703 case APValue::LValue: 9704 APValue::LValueBase Base; 9705 QualType FromElemTy; 9706 if (FromValue.getLValueBase()) { 9707 assert(!FromValue.getLValueBase().is<DynamicAllocLValue>() && 9708 "in C++20 dynamic allocation are transient so they shouldn't " 9709 "appear in the AST"); 9710 if (!FromValue.getLValueBase().is<TypeInfoLValue>()) { 9711 if (const auto *E = 9712 FromValue.getLValueBase().dyn_cast<const Expr *>()) { 9713 FromElemTy = E->getType(); 9714 const Expr *ImpExpr = importChecked(Err, E); 9715 if (Err) 9716 return std::move(Err); 9717 Base = APValue::LValueBase(ImpExpr, 9718 FromValue.getLValueBase().getCallIndex(), 9719 FromValue.getLValueBase().getVersion()); 9720 } else { 9721 FromElemTy = 9722 FromValue.getLValueBase().get<const ValueDecl *>()->getType(); 9723 const Decl *ImpDecl = importChecked( 9724 Err, FromValue.getLValueBase().get<const ValueDecl *>()); 9725 if (Err) 9726 return std::move(Err); 9727 Base = APValue::LValueBase(cast<ValueDecl>(ImpDecl), 9728 FromValue.getLValueBase().getCallIndex(), 9729 FromValue.getLValueBase().getVersion()); 9730 } 9731 } else { 9732 FromElemTy = FromValue.getLValueBase().getTypeInfoType(); 9733 const Type *ImpTypeInfo = importChecked( 9734 Err, FromValue.getLValueBase().get<TypeInfoLValue>().getType()); 9735 QualType ImpType = 9736 importChecked(Err, FromValue.getLValueBase().getTypeInfoType()); 9737 if (Err) 9738 return std::move(Err); 9739 Base = APValue::LValueBase::getTypeInfo(TypeInfoLValue(ImpTypeInfo), 9740 ImpType); 9741 } 9742 } 9743 CharUnits Offset = FromValue.getLValueOffset(); 9744 unsigned PathLength = FromValue.getLValuePath().size(); 9745 Result.MakeLValue(); 9746 if (FromValue.hasLValuePath()) { 9747 MutableArrayRef<APValue::LValuePathEntry> ToPath = Result.setLValueUninit( 9748 Base, Offset, PathLength, FromValue.isLValueOnePastTheEnd(), 9749 FromValue.isNullPointer()); 9750 llvm::ArrayRef<APValue::LValuePathEntry> FromPath = 9751 FromValue.getLValuePath(); 9752 for (unsigned LoopIdx = 0; LoopIdx < PathLength; LoopIdx++) { 9753 if (FromElemTy->isRecordType()) { 9754 const Decl *FromDecl = 9755 FromPath[LoopIdx].getAsBaseOrMember().getPointer(); 9756 const Decl *ImpDecl = importChecked(Err, FromDecl); 9757 if (Err) 9758 return std::move(Err); 9759 if (auto *RD = dyn_cast<CXXRecordDecl>(FromDecl)) 9760 FromElemTy = Importer.FromContext.getRecordType(RD); 9761 else 9762 FromElemTy = cast<ValueDecl>(FromDecl)->getType(); 9763 ToPath[LoopIdx] = APValue::LValuePathEntry(APValue::BaseOrMemberType( 9764 ImpDecl, FromPath[LoopIdx].getAsBaseOrMember().getInt())); 9765 } else { 9766 FromElemTy = 9767 Importer.FromContext.getAsArrayType(FromElemTy)->getElementType(); 9768 ToPath[LoopIdx] = APValue::LValuePathEntry::ArrayIndex( 9769 FromPath[LoopIdx].getAsArrayIndex()); 9770 } 9771 } 9772 } else 9773 Result.setLValue(Base, Offset, APValue::NoLValuePath{}, 9774 FromValue.isNullPointer()); 9775 } 9776 if (Err) 9777 return std::move(Err); 9778 return Result; 9779 } 9780 9781 Expected<DeclarationName> ASTImporter::HandleNameConflict(DeclarationName Name, 9782 DeclContext *DC, 9783 unsigned IDNS, 9784 NamedDecl **Decls, 9785 unsigned NumDecls) { 9786 if (ODRHandling == ODRHandlingType::Conservative) 9787 // Report error at any name conflict. 9788 return make_error<ASTImportError>(ASTImportError::NameConflict); 9789 else 9790 // Allow to create the new Decl with the same name. 9791 return Name; 9792 } 9793 9794 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) { 9795 if (LastDiagFromFrom) 9796 ToContext.getDiagnostics().notePriorDiagnosticFrom( 9797 FromContext.getDiagnostics()); 9798 LastDiagFromFrom = false; 9799 return ToContext.getDiagnostics().Report(Loc, DiagID); 9800 } 9801 9802 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) { 9803 if (!LastDiagFromFrom) 9804 FromContext.getDiagnostics().notePriorDiagnosticFrom( 9805 ToContext.getDiagnostics()); 9806 LastDiagFromFrom = true; 9807 return FromContext.getDiagnostics().Report(Loc, DiagID); 9808 } 9809 9810 void ASTImporter::CompleteDecl (Decl *D) { 9811 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) { 9812 if (!ID->getDefinition()) 9813 ID->startDefinition(); 9814 } 9815 else if (auto *PD = dyn_cast<ObjCProtocolDecl>(D)) { 9816 if (!PD->getDefinition()) 9817 PD->startDefinition(); 9818 } 9819 else if (auto *TD = dyn_cast<TagDecl>(D)) { 9820 if (!TD->getDefinition() && !TD->isBeingDefined()) { 9821 TD->startDefinition(); 9822 TD->setCompleteDefinition(true); 9823 } 9824 } 9825 else { 9826 assert(0 && "CompleteDecl called on a Decl that can't be completed"); 9827 } 9828 } 9829 9830 Decl *ASTImporter::MapImported(Decl *From, Decl *To) { 9831 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(From); 9832 assert((Pos == ImportedDecls.end() || Pos->second == To) && 9833 "Try to import an already imported Decl"); 9834 if (Pos != ImportedDecls.end()) 9835 return Pos->second; 9836 ImportedDecls[From] = To; 9837 // This mapping should be maintained only in this function. Therefore do not 9838 // check for additional consistency. 9839 ImportedFromDecls[To] = From; 9840 // In the case of TypedefNameDecl we create the Decl first and only then we 9841 // import and set its DeclContext. So, the DC is still not set when we reach 9842 // here from GetImportedOrCreateDecl. 9843 if (To->getDeclContext()) 9844 AddToLookupTable(To); 9845 return To; 9846 } 9847 9848 llvm::Optional<ASTImportError> 9849 ASTImporter::getImportDeclErrorIfAny(Decl *FromD) const { 9850 auto Pos = ImportDeclErrors.find(FromD); 9851 if (Pos != ImportDeclErrors.end()) 9852 return Pos->second; 9853 else 9854 return Optional<ASTImportError>(); 9855 } 9856 9857 void ASTImporter::setImportDeclError(Decl *From, ASTImportError Error) { 9858 auto InsertRes = ImportDeclErrors.insert({From, Error}); 9859 (void)InsertRes; 9860 // Either we set the error for the first time, or we already had set one and 9861 // now we want to set the same error. 9862 assert(InsertRes.second || InsertRes.first->second.Error == Error.Error); 9863 } 9864 9865 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To, 9866 bool Complain) { 9867 llvm::DenseMap<const Type *, const Type *>::iterator Pos = 9868 ImportedTypes.find(From.getTypePtr()); 9869 if (Pos != ImportedTypes.end()) { 9870 if (ExpectedType ToFromOrErr = Import(From)) { 9871 if (ToContext.hasSameType(*ToFromOrErr, To)) 9872 return true; 9873 } else { 9874 llvm::consumeError(ToFromOrErr.takeError()); 9875 } 9876 } 9877 9878 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls, 9879 getStructuralEquivalenceKind(*this), false, 9880 Complain); 9881 return Ctx.IsEquivalent(From, To); 9882 } 9883