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