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