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