1 //===--------------------- SemaLookup.cpp - Name Lookup ------------------===// 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 implements name lookup for C, C++, Objective-C, and 10 // Objective-C++. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/CXXInheritance.h" 16 #include "clang/AST/Decl.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclLookups.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/Basic/Builtins.h" 24 #include "clang/Basic/FileManager.h" 25 #include "clang/Basic/LangOptions.h" 26 #include "clang/Lex/HeaderSearch.h" 27 #include "clang/Lex/ModuleLoader.h" 28 #include "clang/Lex/Preprocessor.h" 29 #include "clang/Sema/DeclSpec.h" 30 #include "clang/Sema/Lookup.h" 31 #include "clang/Sema/Overload.h" 32 #include "clang/Sema/RISCVIntrinsicManager.h" 33 #include "clang/Sema/Scope.h" 34 #include "clang/Sema/ScopeInfo.h" 35 #include "clang/Sema/Sema.h" 36 #include "clang/Sema/SemaInternal.h" 37 #include "clang/Sema/TemplateDeduction.h" 38 #include "clang/Sema/TypoCorrection.h" 39 #include "llvm/ADT/STLExtras.h" 40 #include "llvm/ADT/SmallPtrSet.h" 41 #include "llvm/ADT/TinyPtrVector.h" 42 #include "llvm/ADT/edit_distance.h" 43 #include "llvm/Support/Casting.h" 44 #include "llvm/Support/ErrorHandling.h" 45 #include <algorithm> 46 #include <iterator> 47 #include <list> 48 #include <optional> 49 #include <set> 50 #include <utility> 51 #include <vector> 52 53 #include "OpenCLBuiltins.inc" 54 55 using namespace clang; 56 using namespace sema; 57 58 namespace { 59 class UnqualUsingEntry { 60 const DeclContext *Nominated; 61 const DeclContext *CommonAncestor; 62 63 public: 64 UnqualUsingEntry(const DeclContext *Nominated, 65 const DeclContext *CommonAncestor) 66 : Nominated(Nominated), CommonAncestor(CommonAncestor) { 67 } 68 69 const DeclContext *getCommonAncestor() const { 70 return CommonAncestor; 71 } 72 73 const DeclContext *getNominatedNamespace() const { 74 return Nominated; 75 } 76 77 // Sort by the pointer value of the common ancestor. 78 struct Comparator { 79 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) { 80 return L.getCommonAncestor() < R.getCommonAncestor(); 81 } 82 83 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) { 84 return E.getCommonAncestor() < DC; 85 } 86 87 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) { 88 return DC < E.getCommonAncestor(); 89 } 90 }; 91 }; 92 93 /// A collection of using directives, as used by C++ unqualified 94 /// lookup. 95 class UnqualUsingDirectiveSet { 96 Sema &SemaRef; 97 98 typedef SmallVector<UnqualUsingEntry, 8> ListTy; 99 100 ListTy list; 101 llvm::SmallPtrSet<DeclContext*, 8> visited; 102 103 public: 104 UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {} 105 106 void visitScopeChain(Scope *S, Scope *InnermostFileScope) { 107 // C++ [namespace.udir]p1: 108 // During unqualified name lookup, the names appear as if they 109 // were declared in the nearest enclosing namespace which contains 110 // both the using-directive and the nominated namespace. 111 DeclContext *InnermostFileDC = InnermostFileScope->getEntity(); 112 assert(InnermostFileDC && InnermostFileDC->isFileContext()); 113 114 for (; S; S = S->getParent()) { 115 // C++ [namespace.udir]p1: 116 // A using-directive shall not appear in class scope, but may 117 // appear in namespace scope or in block scope. 118 DeclContext *Ctx = S->getEntity(); 119 if (Ctx && Ctx->isFileContext()) { 120 visit(Ctx, Ctx); 121 } else if (!Ctx || Ctx->isFunctionOrMethod()) { 122 for (auto *I : S->using_directives()) 123 if (SemaRef.isVisible(I)) 124 visit(I, InnermostFileDC); 125 } 126 } 127 } 128 129 // Visits a context and collect all of its using directives 130 // recursively. Treats all using directives as if they were 131 // declared in the context. 132 // 133 // A given context is only every visited once, so it is important 134 // that contexts be visited from the inside out in order to get 135 // the effective DCs right. 136 void visit(DeclContext *DC, DeclContext *EffectiveDC) { 137 if (!visited.insert(DC).second) 138 return; 139 140 addUsingDirectives(DC, EffectiveDC); 141 } 142 143 // Visits a using directive and collects all of its using 144 // directives recursively. Treats all using directives as if they 145 // were declared in the effective DC. 146 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { 147 DeclContext *NS = UD->getNominatedNamespace(); 148 if (!visited.insert(NS).second) 149 return; 150 151 addUsingDirective(UD, EffectiveDC); 152 addUsingDirectives(NS, EffectiveDC); 153 } 154 155 // Adds all the using directives in a context (and those nominated 156 // by its using directives, transitively) as if they appeared in 157 // the given effective context. 158 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) { 159 SmallVector<DeclContext*, 4> queue; 160 while (true) { 161 for (auto *UD : DC->using_directives()) { 162 DeclContext *NS = UD->getNominatedNamespace(); 163 if (SemaRef.isVisible(UD) && visited.insert(NS).second) { 164 addUsingDirective(UD, EffectiveDC); 165 queue.push_back(NS); 166 } 167 } 168 169 if (queue.empty()) 170 return; 171 172 DC = queue.pop_back_val(); 173 } 174 } 175 176 // Add a using directive as if it had been declared in the given 177 // context. This helps implement C++ [namespace.udir]p3: 178 // The using-directive is transitive: if a scope contains a 179 // using-directive that nominates a second namespace that itself 180 // contains using-directives, the effect is as if the 181 // using-directives from the second namespace also appeared in 182 // the first. 183 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { 184 // Find the common ancestor between the effective context and 185 // the nominated namespace. 186 DeclContext *Common = UD->getNominatedNamespace(); 187 while (!Common->Encloses(EffectiveDC)) 188 Common = Common->getParent(); 189 Common = Common->getPrimaryContext(); 190 191 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common)); 192 } 193 194 void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); } 195 196 typedef ListTy::const_iterator const_iterator; 197 198 const_iterator begin() const { return list.begin(); } 199 const_iterator end() const { return list.end(); } 200 201 llvm::iterator_range<const_iterator> 202 getNamespacesFor(const DeclContext *DC) const { 203 return llvm::make_range(std::equal_range(begin(), end(), 204 DC->getPrimaryContext(), 205 UnqualUsingEntry::Comparator())); 206 } 207 }; 208 } // end anonymous namespace 209 210 // Retrieve the set of identifier namespaces that correspond to a 211 // specific kind of name lookup. 212 static inline unsigned getIDNS(Sema::LookupNameKind NameKind, 213 bool CPlusPlus, 214 bool Redeclaration) { 215 unsigned IDNS = 0; 216 switch (NameKind) { 217 case Sema::LookupObjCImplicitSelfParam: 218 case Sema::LookupOrdinaryName: 219 case Sema::LookupRedeclarationWithLinkage: 220 case Sema::LookupLocalFriendName: 221 case Sema::LookupDestructorName: 222 IDNS = Decl::IDNS_Ordinary; 223 if (CPlusPlus) { 224 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace; 225 if (Redeclaration) 226 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend; 227 } 228 if (Redeclaration) 229 IDNS |= Decl::IDNS_LocalExtern; 230 break; 231 232 case Sema::LookupOperatorName: 233 // Operator lookup is its own crazy thing; it is not the same 234 // as (e.g.) looking up an operator name for redeclaration. 235 assert(!Redeclaration && "cannot do redeclaration operator lookup"); 236 IDNS = Decl::IDNS_NonMemberOperator; 237 break; 238 239 case Sema::LookupTagName: 240 if (CPlusPlus) { 241 IDNS = Decl::IDNS_Type; 242 243 // When looking for a redeclaration of a tag name, we add: 244 // 1) TagFriend to find undeclared friend decls 245 // 2) Namespace because they can't "overload" with tag decls. 246 // 3) Tag because it includes class templates, which can't 247 // "overload" with tag decls. 248 if (Redeclaration) 249 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace; 250 } else { 251 IDNS = Decl::IDNS_Tag; 252 } 253 break; 254 255 case Sema::LookupLabel: 256 IDNS = Decl::IDNS_Label; 257 break; 258 259 case Sema::LookupMemberName: 260 IDNS = Decl::IDNS_Member; 261 if (CPlusPlus) 262 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary; 263 break; 264 265 case Sema::LookupNestedNameSpecifierName: 266 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace; 267 break; 268 269 case Sema::LookupNamespaceName: 270 IDNS = Decl::IDNS_Namespace; 271 break; 272 273 case Sema::LookupUsingDeclName: 274 assert(Redeclaration && "should only be used for redecl lookup"); 275 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member | 276 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend | 277 Decl::IDNS_LocalExtern; 278 break; 279 280 case Sema::LookupObjCProtocolName: 281 IDNS = Decl::IDNS_ObjCProtocol; 282 break; 283 284 case Sema::LookupOMPReductionName: 285 IDNS = Decl::IDNS_OMPReduction; 286 break; 287 288 case Sema::LookupOMPMapperName: 289 IDNS = Decl::IDNS_OMPMapper; 290 break; 291 292 case Sema::LookupAnyName: 293 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member 294 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol 295 | Decl::IDNS_Type; 296 break; 297 } 298 return IDNS; 299 } 300 301 void LookupResult::configure() { 302 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus, 303 isForRedeclaration()); 304 305 // If we're looking for one of the allocation or deallocation 306 // operators, make sure that the implicitly-declared new and delete 307 // operators can be found. 308 switch (NameInfo.getName().getCXXOverloadedOperator()) { 309 case OO_New: 310 case OO_Delete: 311 case OO_Array_New: 312 case OO_Array_Delete: 313 getSema().DeclareGlobalNewDelete(); 314 break; 315 316 default: 317 break; 318 } 319 320 // Compiler builtins are always visible, regardless of where they end 321 // up being declared. 322 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) { 323 if (unsigned BuiltinID = Id->getBuiltinID()) { 324 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 325 AllowHidden = true; 326 } 327 } 328 } 329 330 bool LookupResult::checkDebugAssumptions() const { 331 // This function is never called by NDEBUG builds. 332 assert(ResultKind != NotFound || Decls.size() == 0); 333 assert(ResultKind != Found || Decls.size() == 1); 334 assert(ResultKind != FoundOverloaded || Decls.size() > 1 || 335 (Decls.size() == 1 && 336 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl()))); 337 assert(ResultKind != FoundUnresolvedValue || checkUnresolved()); 338 assert(ResultKind != Ambiguous || Decls.size() > 1 || 339 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects || 340 Ambiguity == AmbiguousBaseSubobjectTypes))); 341 assert((Paths != nullptr) == (ResultKind == Ambiguous && 342 (Ambiguity == AmbiguousBaseSubobjectTypes || 343 Ambiguity == AmbiguousBaseSubobjects))); 344 return true; 345 } 346 347 // Necessary because CXXBasePaths is not complete in Sema.h 348 void LookupResult::deletePaths(CXXBasePaths *Paths) { 349 delete Paths; 350 } 351 352 /// Get a representative context for a declaration such that two declarations 353 /// will have the same context if they were found within the same scope. 354 static const DeclContext *getContextForScopeMatching(const Decl *D) { 355 // For function-local declarations, use that function as the context. This 356 // doesn't account for scopes within the function; the caller must deal with 357 // those. 358 if (const DeclContext *DC = D->getLexicalDeclContext(); 359 DC->isFunctionOrMethod()) 360 return DC; 361 362 // Otherwise, look at the semantic context of the declaration. The 363 // declaration must have been found there. 364 return D->getDeclContext()->getRedeclContext(); 365 } 366 367 /// Determine whether \p D is a better lookup result than \p Existing, 368 /// given that they declare the same entity. 369 static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind, 370 const NamedDecl *D, 371 const NamedDecl *Existing) { 372 // When looking up redeclarations of a using declaration, prefer a using 373 // shadow declaration over any other declaration of the same entity. 374 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) && 375 !isa<UsingShadowDecl>(Existing)) 376 return true; 377 378 const auto *DUnderlying = D->getUnderlyingDecl(); 379 const auto *EUnderlying = Existing->getUnderlyingDecl(); 380 381 // If they have different underlying declarations, prefer a typedef over the 382 // original type (this happens when two type declarations denote the same 383 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef 384 // might carry additional semantic information, such as an alignment override. 385 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag 386 // declaration over a typedef. Also prefer a tag over a typedef for 387 // destructor name lookup because in some contexts we only accept a 388 // class-name in a destructor declaration. 389 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) { 390 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying)); 391 bool HaveTag = isa<TagDecl>(EUnderlying); 392 bool WantTag = 393 Kind == Sema::LookupTagName || Kind == Sema::LookupDestructorName; 394 return HaveTag != WantTag; 395 } 396 397 // Pick the function with more default arguments. 398 // FIXME: In the presence of ambiguous default arguments, we should keep both, 399 // so we can diagnose the ambiguity if the default argument is needed. 400 // See C++ [over.match.best]p3. 401 if (const auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) { 402 const auto *EFD = cast<FunctionDecl>(EUnderlying); 403 unsigned DMin = DFD->getMinRequiredArguments(); 404 unsigned EMin = EFD->getMinRequiredArguments(); 405 // If D has more default arguments, it is preferred. 406 if (DMin != EMin) 407 return DMin < EMin; 408 // FIXME: When we track visibility for default function arguments, check 409 // that we pick the declaration with more visible default arguments. 410 } 411 412 // Pick the template with more default template arguments. 413 if (const auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) { 414 const auto *ETD = cast<TemplateDecl>(EUnderlying); 415 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments(); 416 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments(); 417 // If D has more default arguments, it is preferred. Note that default 418 // arguments (and their visibility) is monotonically increasing across the 419 // redeclaration chain, so this is a quick proxy for "is more recent". 420 if (DMin != EMin) 421 return DMin < EMin; 422 // If D has more *visible* default arguments, it is preferred. Note, an 423 // earlier default argument being visible does not imply that a later 424 // default argument is visible, so we can't just check the first one. 425 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size(); 426 I != N; ++I) { 427 if (!S.hasVisibleDefaultArgument( 428 ETD->getTemplateParameters()->getParam(I)) && 429 S.hasVisibleDefaultArgument( 430 DTD->getTemplateParameters()->getParam(I))) 431 return true; 432 } 433 } 434 435 // VarDecl can have incomplete array types, prefer the one with more complete 436 // array type. 437 if (const auto *DVD = dyn_cast<VarDecl>(DUnderlying)) { 438 const auto *EVD = cast<VarDecl>(EUnderlying); 439 if (EVD->getType()->isIncompleteType() && 440 !DVD->getType()->isIncompleteType()) { 441 // Prefer the decl with a more complete type if visible. 442 return S.isVisible(DVD); 443 } 444 return false; // Avoid picking up a newer decl, just because it was newer. 445 } 446 447 // For most kinds of declaration, it doesn't really matter which one we pick. 448 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) { 449 // If the existing declaration is hidden, prefer the new one. Otherwise, 450 // keep what we've got. 451 return !S.isVisible(Existing); 452 } 453 454 // Pick the newer declaration; it might have a more precise type. 455 for (const Decl *Prev = DUnderlying->getPreviousDecl(); Prev; 456 Prev = Prev->getPreviousDecl()) 457 if (Prev == EUnderlying) 458 return true; 459 return false; 460 } 461 462 /// Determine whether \p D can hide a tag declaration. 463 static bool canHideTag(const NamedDecl *D) { 464 // C++ [basic.scope.declarative]p4: 465 // Given a set of declarations in a single declarative region [...] 466 // exactly one declaration shall declare a class name or enumeration name 467 // that is not a typedef name and the other declarations shall all refer to 468 // the same variable, non-static data member, or enumerator, or all refer 469 // to functions and function templates; in this case the class name or 470 // enumeration name is hidden. 471 // C++ [basic.scope.hiding]p2: 472 // A class name or enumeration name can be hidden by the name of a 473 // variable, data member, function, or enumerator declared in the same 474 // scope. 475 // An UnresolvedUsingValueDecl always instantiates to one of these. 476 D = D->getUnderlyingDecl(); 477 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) || 478 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) || 479 isa<UnresolvedUsingValueDecl>(D); 480 } 481 482 /// Resolves the result kind of this lookup. 483 void LookupResult::resolveKind() { 484 unsigned N = Decls.size(); 485 486 // Fast case: no possible ambiguity. 487 if (N == 0) { 488 assert(ResultKind == NotFound || 489 ResultKind == NotFoundInCurrentInstantiation); 490 return; 491 } 492 493 // If there's a single decl, we need to examine it to decide what 494 // kind of lookup this is. 495 if (N == 1) { 496 const NamedDecl *D = (*Decls.begin())->getUnderlyingDecl(); 497 if (isa<FunctionTemplateDecl>(D)) 498 ResultKind = FoundOverloaded; 499 else if (isa<UnresolvedUsingValueDecl>(D)) 500 ResultKind = FoundUnresolvedValue; 501 return; 502 } 503 504 // Don't do any extra resolution if we've already resolved as ambiguous. 505 if (ResultKind == Ambiguous) return; 506 507 llvm::SmallDenseMap<const NamedDecl *, unsigned, 16> Unique; 508 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes; 509 510 bool Ambiguous = false; 511 bool HasTag = false, HasFunction = false; 512 bool HasFunctionTemplate = false, HasUnresolved = false; 513 const NamedDecl *HasNonFunction = nullptr; 514 515 llvm::SmallVector<const NamedDecl *, 4> EquivalentNonFunctions; 516 llvm::BitVector RemovedDecls(N); 517 518 for (unsigned I = 0; I < N; I++) { 519 const NamedDecl *D = Decls[I]->getUnderlyingDecl(); 520 D = cast<NamedDecl>(D->getCanonicalDecl()); 521 522 // Ignore an invalid declaration unless it's the only one left. 523 // Also ignore HLSLBufferDecl which not have name conflict with other Decls. 524 if ((D->isInvalidDecl() || isa<HLSLBufferDecl>(D)) && 525 N - RemovedDecls.count() > 1) { 526 RemovedDecls.set(I); 527 continue; 528 } 529 530 // C++ [basic.scope.hiding]p2: 531 // A class name or enumeration name can be hidden by the name of 532 // an object, function, or enumerator declared in the same 533 // scope. If a class or enumeration name and an object, function, 534 // or enumerator are declared in the same scope (in any order) 535 // with the same name, the class or enumeration name is hidden 536 // wherever the object, function, or enumerator name is visible. 537 if (HideTags && isa<TagDecl>(D)) { 538 bool Hidden = false; 539 for (auto *OtherDecl : Decls) { 540 if (canHideTag(OtherDecl) && 541 getContextForScopeMatching(OtherDecl)->Equals( 542 getContextForScopeMatching(Decls[I]))) { 543 RemovedDecls.set(I); 544 Hidden = true; 545 break; 546 } 547 } 548 if (Hidden) 549 continue; 550 } 551 552 std::optional<unsigned> ExistingI; 553 554 // Redeclarations of types via typedef can occur both within a scope 555 // and, through using declarations and directives, across scopes. There is 556 // no ambiguity if they all refer to the same type, so unique based on the 557 // canonical type. 558 if (const auto *TD = dyn_cast<TypeDecl>(D)) { 559 QualType T = getSema().Context.getTypeDeclType(TD); 560 auto UniqueResult = UniqueTypes.insert( 561 std::make_pair(getSema().Context.getCanonicalType(T), I)); 562 if (!UniqueResult.second) { 563 // The type is not unique. 564 ExistingI = UniqueResult.first->second; 565 } 566 } 567 568 // For non-type declarations, check for a prior lookup result naming this 569 // canonical declaration. 570 if (!ExistingI) { 571 auto UniqueResult = Unique.insert(std::make_pair(D, I)); 572 if (!UniqueResult.second) { 573 // We've seen this entity before. 574 ExistingI = UniqueResult.first->second; 575 } 576 } 577 578 if (ExistingI) { 579 // This is not a unique lookup result. Pick one of the results and 580 // discard the other. 581 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I], 582 Decls[*ExistingI])) 583 Decls[*ExistingI] = Decls[I]; 584 RemovedDecls.set(I); 585 continue; 586 } 587 588 // Otherwise, do some decl type analysis and then continue. 589 590 if (isa<UnresolvedUsingValueDecl>(D)) { 591 HasUnresolved = true; 592 } else if (isa<TagDecl>(D)) { 593 if (HasTag) 594 Ambiguous = true; 595 HasTag = true; 596 } else if (isa<FunctionTemplateDecl>(D)) { 597 HasFunction = true; 598 HasFunctionTemplate = true; 599 } else if (isa<FunctionDecl>(D)) { 600 HasFunction = true; 601 } else { 602 if (HasNonFunction) { 603 // If we're about to create an ambiguity between two declarations that 604 // are equivalent, but one is an internal linkage declaration from one 605 // module and the other is an internal linkage declaration from another 606 // module, just skip it. 607 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction, 608 D)) { 609 EquivalentNonFunctions.push_back(D); 610 RemovedDecls.set(I); 611 continue; 612 } 613 614 Ambiguous = true; 615 } 616 HasNonFunction = D; 617 } 618 } 619 620 // FIXME: This diagnostic should really be delayed until we're done with 621 // the lookup result, in case the ambiguity is resolved by the caller. 622 if (!EquivalentNonFunctions.empty() && !Ambiguous) 623 getSema().diagnoseEquivalentInternalLinkageDeclarations( 624 getNameLoc(), HasNonFunction, EquivalentNonFunctions); 625 626 // Remove decls by replacing them with decls from the end (which 627 // means that we need to iterate from the end) and then truncating 628 // to the new size. 629 for (int I = RemovedDecls.find_last(); I >= 0; I = RemovedDecls.find_prev(I)) 630 Decls[I] = Decls[--N]; 631 Decls.truncate(N); 632 633 if ((HasNonFunction && (HasFunction || HasUnresolved)) || 634 (HideTags && HasTag && (HasFunction || HasNonFunction || HasUnresolved))) 635 Ambiguous = true; 636 637 if (Ambiguous) 638 setAmbiguous(LookupResult::AmbiguousReference); 639 else if (HasUnresolved) 640 ResultKind = LookupResult::FoundUnresolvedValue; 641 else if (N > 1 || HasFunctionTemplate) 642 ResultKind = LookupResult::FoundOverloaded; 643 else 644 ResultKind = LookupResult::Found; 645 } 646 647 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) { 648 CXXBasePaths::const_paths_iterator I, E; 649 for (I = P.begin(), E = P.end(); I != E; ++I) 650 for (DeclContext::lookup_iterator DI = I->Decls, DE = DI.end(); DI != DE; 651 ++DI) 652 addDecl(*DI); 653 } 654 655 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) { 656 Paths = new CXXBasePaths; 657 Paths->swap(P); 658 addDeclsFromBasePaths(*Paths); 659 resolveKind(); 660 setAmbiguous(AmbiguousBaseSubobjects); 661 } 662 663 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) { 664 Paths = new CXXBasePaths; 665 Paths->swap(P); 666 addDeclsFromBasePaths(*Paths); 667 resolveKind(); 668 setAmbiguous(AmbiguousBaseSubobjectTypes); 669 } 670 671 void LookupResult::print(raw_ostream &Out) { 672 Out << Decls.size() << " result(s)"; 673 if (isAmbiguous()) Out << ", ambiguous"; 674 if (Paths) Out << ", base paths present"; 675 676 for (iterator I = begin(), E = end(); I != E; ++I) { 677 Out << "\n"; 678 (*I)->print(Out, 2); 679 } 680 } 681 682 LLVM_DUMP_METHOD void LookupResult::dump() { 683 llvm::errs() << "lookup results for " << getLookupName().getAsString() 684 << ":\n"; 685 for (NamedDecl *D : *this) 686 D->dump(); 687 } 688 689 /// Diagnose a missing builtin type. 690 static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass, 691 llvm::StringRef Name) { 692 S.Diag(SourceLocation(), diag::err_opencl_type_not_found) 693 << TypeClass << Name; 694 return S.Context.VoidTy; 695 } 696 697 /// Lookup an OpenCL enum type. 698 static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name) { 699 LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(), 700 Sema::LookupTagName); 701 S.LookupName(Result, S.TUScope); 702 if (Result.empty()) 703 return diagOpenCLBuiltinTypeError(S, "enum", Name); 704 EnumDecl *Decl = Result.getAsSingle<EnumDecl>(); 705 if (!Decl) 706 return diagOpenCLBuiltinTypeError(S, "enum", Name); 707 return S.Context.getEnumType(Decl); 708 } 709 710 /// Lookup an OpenCL typedef type. 711 static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) { 712 LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(), 713 Sema::LookupOrdinaryName); 714 S.LookupName(Result, S.TUScope); 715 if (Result.empty()) 716 return diagOpenCLBuiltinTypeError(S, "typedef", Name); 717 TypedefNameDecl *Decl = Result.getAsSingle<TypedefNameDecl>(); 718 if (!Decl) 719 return diagOpenCLBuiltinTypeError(S, "typedef", Name); 720 return S.Context.getTypedefType(Decl); 721 } 722 723 /// Get the QualType instances of the return type and arguments for an OpenCL 724 /// builtin function signature. 725 /// \param S (in) The Sema instance. 726 /// \param OpenCLBuiltin (in) The signature currently handled. 727 /// \param GenTypeMaxCnt (out) Maximum number of types contained in a generic 728 /// type used as return type or as argument. 729 /// Only meaningful for generic types, otherwise equals 1. 730 /// \param RetTypes (out) List of the possible return types. 731 /// \param ArgTypes (out) List of the possible argument types. For each 732 /// argument, ArgTypes contains QualTypes for the Cartesian product 733 /// of (vector sizes) x (types) . 734 static void GetQualTypesForOpenCLBuiltin( 735 Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt, 736 SmallVector<QualType, 1> &RetTypes, 737 SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) { 738 // Get the QualType instances of the return types. 739 unsigned Sig = SignatureTable[OpenCLBuiltin.SigTableIndex]; 740 OCL2Qual(S, TypeTable[Sig], RetTypes); 741 GenTypeMaxCnt = RetTypes.size(); 742 743 // Get the QualType instances of the arguments. 744 // First type is the return type, skip it. 745 for (unsigned Index = 1; Index < OpenCLBuiltin.NumTypes; Index++) { 746 SmallVector<QualType, 1> Ty; 747 OCL2Qual(S, TypeTable[SignatureTable[OpenCLBuiltin.SigTableIndex + Index]], 748 Ty); 749 GenTypeMaxCnt = (Ty.size() > GenTypeMaxCnt) ? Ty.size() : GenTypeMaxCnt; 750 ArgTypes.push_back(std::move(Ty)); 751 } 752 } 753 754 /// Create a list of the candidate function overloads for an OpenCL builtin 755 /// function. 756 /// \param Context (in) The ASTContext instance. 757 /// \param GenTypeMaxCnt (in) Maximum number of types contained in a generic 758 /// type used as return type or as argument. 759 /// Only meaningful for generic types, otherwise equals 1. 760 /// \param FunctionList (out) List of FunctionTypes. 761 /// \param RetTypes (in) List of the possible return types. 762 /// \param ArgTypes (in) List of the possible types for the arguments. 763 static void GetOpenCLBuiltinFctOverloads( 764 ASTContext &Context, unsigned GenTypeMaxCnt, 765 std::vector<QualType> &FunctionList, SmallVector<QualType, 1> &RetTypes, 766 SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) { 767 FunctionProtoType::ExtProtoInfo PI( 768 Context.getDefaultCallingConvention(false, false, true)); 769 PI.Variadic = false; 770 771 // Do not attempt to create any FunctionTypes if there are no return types, 772 // which happens when a type belongs to a disabled extension. 773 if (RetTypes.size() == 0) 774 return; 775 776 // Create FunctionTypes for each (gen)type. 777 for (unsigned IGenType = 0; IGenType < GenTypeMaxCnt; IGenType++) { 778 SmallVector<QualType, 5> ArgList; 779 780 for (unsigned A = 0; A < ArgTypes.size(); A++) { 781 // Bail out if there is an argument that has no available types. 782 if (ArgTypes[A].size() == 0) 783 return; 784 785 // Builtins such as "max" have an "sgentype" argument that represents 786 // the corresponding scalar type of a gentype. The number of gentypes 787 // must be a multiple of the number of sgentypes. 788 assert(GenTypeMaxCnt % ArgTypes[A].size() == 0 && 789 "argument type count not compatible with gentype type count"); 790 unsigned Idx = IGenType % ArgTypes[A].size(); 791 ArgList.push_back(ArgTypes[A][Idx]); 792 } 793 794 FunctionList.push_back(Context.getFunctionType( 795 RetTypes[(RetTypes.size() != 1) ? IGenType : 0], ArgList, PI)); 796 } 797 } 798 799 /// When trying to resolve a function name, if isOpenCLBuiltin() returns a 800 /// non-null <Index, Len> pair, then the name is referencing an OpenCL 801 /// builtin function. Add all candidate signatures to the LookUpResult. 802 /// 803 /// \param S (in) The Sema instance. 804 /// \param LR (inout) The LookupResult instance. 805 /// \param II (in) The identifier being resolved. 806 /// \param FctIndex (in) Starting index in the BuiltinTable. 807 /// \param Len (in) The signature list has Len elements. 808 static void InsertOCLBuiltinDeclarationsFromTable(Sema &S, LookupResult &LR, 809 IdentifierInfo *II, 810 const unsigned FctIndex, 811 const unsigned Len) { 812 // The builtin function declaration uses generic types (gentype). 813 bool HasGenType = false; 814 815 // Maximum number of types contained in a generic type used as return type or 816 // as argument. Only meaningful for generic types, otherwise equals 1. 817 unsigned GenTypeMaxCnt; 818 819 ASTContext &Context = S.Context; 820 821 for (unsigned SignatureIndex = 0; SignatureIndex < Len; SignatureIndex++) { 822 const OpenCLBuiltinStruct &OpenCLBuiltin = 823 BuiltinTable[FctIndex + SignatureIndex]; 824 825 // Ignore this builtin function if it is not available in the currently 826 // selected language version. 827 if (!isOpenCLVersionContainedInMask(Context.getLangOpts(), 828 OpenCLBuiltin.Versions)) 829 continue; 830 831 // Ignore this builtin function if it carries an extension macro that is 832 // not defined. This indicates that the extension is not supported by the 833 // target, so the builtin function should not be available. 834 StringRef Extensions = FunctionExtensionTable[OpenCLBuiltin.Extension]; 835 if (!Extensions.empty()) { 836 SmallVector<StringRef, 2> ExtVec; 837 Extensions.split(ExtVec, " "); 838 bool AllExtensionsDefined = true; 839 for (StringRef Ext : ExtVec) { 840 if (!S.getPreprocessor().isMacroDefined(Ext)) { 841 AllExtensionsDefined = false; 842 break; 843 } 844 } 845 if (!AllExtensionsDefined) 846 continue; 847 } 848 849 SmallVector<QualType, 1> RetTypes; 850 SmallVector<SmallVector<QualType, 1>, 5> ArgTypes; 851 852 // Obtain QualType lists for the function signature. 853 GetQualTypesForOpenCLBuiltin(S, OpenCLBuiltin, GenTypeMaxCnt, RetTypes, 854 ArgTypes); 855 if (GenTypeMaxCnt > 1) { 856 HasGenType = true; 857 } 858 859 // Create function overload for each type combination. 860 std::vector<QualType> FunctionList; 861 GetOpenCLBuiltinFctOverloads(Context, GenTypeMaxCnt, FunctionList, RetTypes, 862 ArgTypes); 863 864 SourceLocation Loc = LR.getNameLoc(); 865 DeclContext *Parent = Context.getTranslationUnitDecl(); 866 FunctionDecl *NewOpenCLBuiltin; 867 868 for (const auto &FTy : FunctionList) { 869 NewOpenCLBuiltin = FunctionDecl::Create( 870 Context, Parent, Loc, Loc, II, FTy, /*TInfo=*/nullptr, SC_Extern, 871 S.getCurFPFeatures().isFPConstrained(), false, 872 FTy->isFunctionProtoType()); 873 NewOpenCLBuiltin->setImplicit(); 874 875 // Create Decl objects for each parameter, adding them to the 876 // FunctionDecl. 877 const auto *FP = cast<FunctionProtoType>(FTy); 878 SmallVector<ParmVarDecl *, 4> ParmList; 879 for (unsigned IParm = 0, e = FP->getNumParams(); IParm != e; ++IParm) { 880 ParmVarDecl *Parm = ParmVarDecl::Create( 881 Context, NewOpenCLBuiltin, SourceLocation(), SourceLocation(), 882 nullptr, FP->getParamType(IParm), nullptr, SC_None, nullptr); 883 Parm->setScopeInfo(0, IParm); 884 ParmList.push_back(Parm); 885 } 886 NewOpenCLBuiltin->setParams(ParmList); 887 888 // Add function attributes. 889 if (OpenCLBuiltin.IsPure) 890 NewOpenCLBuiltin->addAttr(PureAttr::CreateImplicit(Context)); 891 if (OpenCLBuiltin.IsConst) 892 NewOpenCLBuiltin->addAttr(ConstAttr::CreateImplicit(Context)); 893 if (OpenCLBuiltin.IsConv) 894 NewOpenCLBuiltin->addAttr(ConvergentAttr::CreateImplicit(Context)); 895 896 if (!S.getLangOpts().OpenCLCPlusPlus) 897 NewOpenCLBuiltin->addAttr(OverloadableAttr::CreateImplicit(Context)); 898 899 LR.addDecl(NewOpenCLBuiltin); 900 } 901 } 902 903 // If we added overloads, need to resolve the lookup result. 904 if (Len > 1 || HasGenType) 905 LR.resolveKind(); 906 } 907 908 /// Lookup a builtin function, when name lookup would otherwise 909 /// fail. 910 bool Sema::LookupBuiltin(LookupResult &R) { 911 Sema::LookupNameKind NameKind = R.getLookupKind(); 912 913 // If we didn't find a use of this identifier, and if the identifier 914 // corresponds to a compiler builtin, create the decl object for the builtin 915 // now, injecting it into translation unit scope, and return it. 916 if (NameKind == Sema::LookupOrdinaryName || 917 NameKind == Sema::LookupRedeclarationWithLinkage) { 918 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo(); 919 if (II) { 920 if (getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) { 921 if (II == getASTContext().getMakeIntegerSeqName()) { 922 R.addDecl(getASTContext().getMakeIntegerSeqDecl()); 923 return true; 924 } else if (II == getASTContext().getTypePackElementName()) { 925 R.addDecl(getASTContext().getTypePackElementDecl()); 926 return true; 927 } 928 } 929 930 // Check if this is an OpenCL Builtin, and if so, insert its overloads. 931 if (getLangOpts().OpenCL && getLangOpts().DeclareOpenCLBuiltins) { 932 auto Index = isOpenCLBuiltin(II->getName()); 933 if (Index.first) { 934 InsertOCLBuiltinDeclarationsFromTable(*this, R, II, Index.first - 1, 935 Index.second); 936 return true; 937 } 938 } 939 940 if (DeclareRISCVVBuiltins || DeclareRISCVSiFiveVectorBuiltins) { 941 if (!RVIntrinsicManager) 942 RVIntrinsicManager = CreateRISCVIntrinsicManager(*this); 943 944 RVIntrinsicManager->InitIntrinsicList(); 945 946 if (RVIntrinsicManager->CreateIntrinsicIfFound(R, II, PP)) 947 return true; 948 } 949 950 // If this is a builtin on this (or all) targets, create the decl. 951 if (unsigned BuiltinID = II->getBuiltinID()) { 952 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined 953 // library functions like 'malloc'. Instead, we'll just error. 954 if ((getLangOpts().CPlusPlus || getLangOpts().OpenCL) && 955 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 956 return false; 957 958 if (NamedDecl *D = 959 LazilyCreateBuiltin(II, BuiltinID, TUScope, 960 R.isForRedeclaration(), R.getNameLoc())) { 961 R.addDecl(D); 962 return true; 963 } 964 } 965 } 966 } 967 968 return false; 969 } 970 971 /// Looks up the declaration of "struct objc_super" and 972 /// saves it for later use in building builtin declaration of 973 /// objc_msgSendSuper and objc_msgSendSuper_stret. 974 static void LookupPredefedObjCSuperType(Sema &Sema, Scope *S) { 975 ASTContext &Context = Sema.Context; 976 LookupResult Result(Sema, &Context.Idents.get("objc_super"), SourceLocation(), 977 Sema::LookupTagName); 978 Sema.LookupName(Result, S); 979 if (Result.getResultKind() == LookupResult::Found) 980 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 981 Context.setObjCSuperType(Context.getTagDeclType(TD)); 982 } 983 984 void Sema::LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID) { 985 if (ID == Builtin::BIobjc_msgSendSuper) 986 LookupPredefedObjCSuperType(*this, S); 987 } 988 989 /// Determine whether we can declare a special member function within 990 /// the class at this point. 991 static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) { 992 // We need to have a definition for the class. 993 if (!Class->getDefinition() || Class->isDependentContext()) 994 return false; 995 996 // We can't be in the middle of defining the class. 997 return !Class->isBeingDefined(); 998 } 999 1000 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) { 1001 if (!CanDeclareSpecialMemberFunction(Class)) 1002 return; 1003 1004 // If the default constructor has not yet been declared, do so now. 1005 if (Class->needsImplicitDefaultConstructor()) 1006 DeclareImplicitDefaultConstructor(Class); 1007 1008 // If the copy constructor has not yet been declared, do so now. 1009 if (Class->needsImplicitCopyConstructor()) 1010 DeclareImplicitCopyConstructor(Class); 1011 1012 // If the copy assignment operator has not yet been declared, do so now. 1013 if (Class->needsImplicitCopyAssignment()) 1014 DeclareImplicitCopyAssignment(Class); 1015 1016 if (getLangOpts().CPlusPlus11) { 1017 // If the move constructor has not yet been declared, do so now. 1018 if (Class->needsImplicitMoveConstructor()) 1019 DeclareImplicitMoveConstructor(Class); 1020 1021 // If the move assignment operator has not yet been declared, do so now. 1022 if (Class->needsImplicitMoveAssignment()) 1023 DeclareImplicitMoveAssignment(Class); 1024 } 1025 1026 // If the destructor has not yet been declared, do so now. 1027 if (Class->needsImplicitDestructor()) 1028 DeclareImplicitDestructor(Class); 1029 } 1030 1031 /// Determine whether this is the name of an implicitly-declared 1032 /// special member function. 1033 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) { 1034 switch (Name.getNameKind()) { 1035 case DeclarationName::CXXConstructorName: 1036 case DeclarationName::CXXDestructorName: 1037 return true; 1038 1039 case DeclarationName::CXXOperatorName: 1040 return Name.getCXXOverloadedOperator() == OO_Equal; 1041 1042 default: 1043 break; 1044 } 1045 1046 return false; 1047 } 1048 1049 /// If there are any implicit member functions with the given name 1050 /// that need to be declared in the given declaration context, do so. 1051 static void DeclareImplicitMemberFunctionsWithName(Sema &S, 1052 DeclarationName Name, 1053 SourceLocation Loc, 1054 const DeclContext *DC) { 1055 if (!DC) 1056 return; 1057 1058 switch (Name.getNameKind()) { 1059 case DeclarationName::CXXConstructorName: 1060 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 1061 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) { 1062 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record); 1063 if (Record->needsImplicitDefaultConstructor()) 1064 S.DeclareImplicitDefaultConstructor(Class); 1065 if (Record->needsImplicitCopyConstructor()) 1066 S.DeclareImplicitCopyConstructor(Class); 1067 if (S.getLangOpts().CPlusPlus11 && 1068 Record->needsImplicitMoveConstructor()) 1069 S.DeclareImplicitMoveConstructor(Class); 1070 } 1071 break; 1072 1073 case DeclarationName::CXXDestructorName: 1074 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 1075 if (Record->getDefinition() && Record->needsImplicitDestructor() && 1076 CanDeclareSpecialMemberFunction(Record)) 1077 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record)); 1078 break; 1079 1080 case DeclarationName::CXXOperatorName: 1081 if (Name.getCXXOverloadedOperator() != OO_Equal) 1082 break; 1083 1084 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) { 1085 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) { 1086 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record); 1087 if (Record->needsImplicitCopyAssignment()) 1088 S.DeclareImplicitCopyAssignment(Class); 1089 if (S.getLangOpts().CPlusPlus11 && 1090 Record->needsImplicitMoveAssignment()) 1091 S.DeclareImplicitMoveAssignment(Class); 1092 } 1093 } 1094 break; 1095 1096 case DeclarationName::CXXDeductionGuideName: 1097 S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc); 1098 break; 1099 1100 default: 1101 break; 1102 } 1103 } 1104 1105 // Adds all qualifying matches for a name within a decl context to the 1106 // given lookup result. Returns true if any matches were found. 1107 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) { 1108 bool Found = false; 1109 1110 // Lazily declare C++ special member functions. 1111 if (S.getLangOpts().CPlusPlus) 1112 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(), 1113 DC); 1114 1115 // Perform lookup into this declaration context. 1116 DeclContext::lookup_result DR = DC->lookup(R.getLookupName()); 1117 for (NamedDecl *D : DR) { 1118 if ((D = R.getAcceptableDecl(D))) { 1119 R.addDecl(D); 1120 Found = true; 1121 } 1122 } 1123 1124 if (!Found && DC->isTranslationUnit() && S.LookupBuiltin(R)) 1125 return true; 1126 1127 if (R.getLookupName().getNameKind() 1128 != DeclarationName::CXXConversionFunctionName || 1129 R.getLookupName().getCXXNameType()->isDependentType() || 1130 !isa<CXXRecordDecl>(DC)) 1131 return Found; 1132 1133 // C++ [temp.mem]p6: 1134 // A specialization of a conversion function template is not found by 1135 // name lookup. Instead, any conversion function templates visible in the 1136 // context of the use are considered. [...] 1137 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 1138 if (!Record->isCompleteDefinition()) 1139 return Found; 1140 1141 // For conversion operators, 'operator auto' should only match 1142 // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered 1143 // as a candidate for template substitution. 1144 auto *ContainedDeducedType = 1145 R.getLookupName().getCXXNameType()->getContainedDeducedType(); 1146 if (R.getLookupName().getNameKind() == 1147 DeclarationName::CXXConversionFunctionName && 1148 ContainedDeducedType && ContainedDeducedType->isUndeducedType()) 1149 return Found; 1150 1151 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(), 1152 UEnd = Record->conversion_end(); U != UEnd; ++U) { 1153 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U); 1154 if (!ConvTemplate) 1155 continue; 1156 1157 // When we're performing lookup for the purposes of redeclaration, just 1158 // add the conversion function template. When we deduce template 1159 // arguments for specializations, we'll end up unifying the return 1160 // type of the new declaration with the type of the function template. 1161 if (R.isForRedeclaration()) { 1162 R.addDecl(ConvTemplate); 1163 Found = true; 1164 continue; 1165 } 1166 1167 // C++ [temp.mem]p6: 1168 // [...] For each such operator, if argument deduction succeeds 1169 // (14.9.2.3), the resulting specialization is used as if found by 1170 // name lookup. 1171 // 1172 // When referencing a conversion function for any purpose other than 1173 // a redeclaration (such that we'll be building an expression with the 1174 // result), perform template argument deduction and place the 1175 // specialization into the result set. We do this to avoid forcing all 1176 // callers to perform special deduction for conversion functions. 1177 TemplateDeductionInfo Info(R.getNameLoc()); 1178 FunctionDecl *Specialization = nullptr; 1179 1180 const FunctionProtoType *ConvProto 1181 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>(); 1182 assert(ConvProto && "Nonsensical conversion function template type"); 1183 1184 // Compute the type of the function that we would expect the conversion 1185 // function to have, if it were to match the name given. 1186 // FIXME: Calling convention! 1187 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo(); 1188 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C); 1189 EPI.ExceptionSpec = EST_None; 1190 QualType ExpectedType = R.getSema().Context.getFunctionType( 1191 R.getLookupName().getCXXNameType(), std::nullopt, EPI); 1192 1193 // Perform template argument deduction against the type that we would 1194 // expect the function to have. 1195 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType, 1196 Specialization, Info) 1197 == Sema::TDK_Success) { 1198 R.addDecl(Specialization); 1199 Found = true; 1200 } 1201 } 1202 1203 return Found; 1204 } 1205 1206 // Performs C++ unqualified lookup into the given file context. 1207 static bool CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context, 1208 const DeclContext *NS, 1209 UnqualUsingDirectiveSet &UDirs) { 1210 1211 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!"); 1212 1213 // Perform direct name lookup into the LookupCtx. 1214 bool Found = LookupDirect(S, R, NS); 1215 1216 // Perform direct name lookup into the namespaces nominated by the 1217 // using directives whose common ancestor is this namespace. 1218 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS)) 1219 if (LookupDirect(S, R, UUE.getNominatedNamespace())) 1220 Found = true; 1221 1222 R.resolveKind(); 1223 1224 return Found; 1225 } 1226 1227 static bool isNamespaceOrTranslationUnitScope(Scope *S) { 1228 if (DeclContext *Ctx = S->getEntity()) 1229 return Ctx->isFileContext(); 1230 return false; 1231 } 1232 1233 /// Find the outer declaration context from this scope. This indicates the 1234 /// context that we should search up to (exclusive) before considering the 1235 /// parent of the specified scope. 1236 static DeclContext *findOuterContext(Scope *S) { 1237 for (Scope *OuterS = S->getParent(); OuterS; OuterS = OuterS->getParent()) 1238 if (DeclContext *DC = OuterS->getLookupEntity()) 1239 return DC; 1240 return nullptr; 1241 } 1242 1243 namespace { 1244 /// An RAII object to specify that we want to find block scope extern 1245 /// declarations. 1246 struct FindLocalExternScope { 1247 FindLocalExternScope(LookupResult &R) 1248 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() & 1249 Decl::IDNS_LocalExtern) { 1250 R.setFindLocalExtern(R.getIdentifierNamespace() & 1251 (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator)); 1252 } 1253 void restore() { 1254 R.setFindLocalExtern(OldFindLocalExtern); 1255 } 1256 ~FindLocalExternScope() { 1257 restore(); 1258 } 1259 LookupResult &R; 1260 bool OldFindLocalExtern; 1261 }; 1262 } // end anonymous namespace 1263 1264 bool Sema::CppLookupName(LookupResult &R, Scope *S) { 1265 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup"); 1266 1267 DeclarationName Name = R.getLookupName(); 1268 Sema::LookupNameKind NameKind = R.getLookupKind(); 1269 1270 // If this is the name of an implicitly-declared special member function, 1271 // go through the scope stack to implicitly declare 1272 if (isImplicitlyDeclaredMemberFunctionName(Name)) { 1273 for (Scope *PreS = S; PreS; PreS = PreS->getParent()) 1274 if (DeclContext *DC = PreS->getEntity()) 1275 DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC); 1276 } 1277 1278 // Implicitly declare member functions with the name we're looking for, if in 1279 // fact we are in a scope where it matters. 1280 1281 Scope *Initial = S; 1282 IdentifierResolver::iterator 1283 I = IdResolver.begin(Name), 1284 IEnd = IdResolver.end(); 1285 1286 // First we lookup local scope. 1287 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir] 1288 // ...During unqualified name lookup (3.4.1), the names appear as if 1289 // they were declared in the nearest enclosing namespace which contains 1290 // both the using-directive and the nominated namespace. 1291 // [Note: in this context, "contains" means "contains directly or 1292 // indirectly". 1293 // 1294 // For example: 1295 // namespace A { int i; } 1296 // void foo() { 1297 // int i; 1298 // { 1299 // using namespace A; 1300 // ++i; // finds local 'i', A::i appears at global scope 1301 // } 1302 // } 1303 // 1304 UnqualUsingDirectiveSet UDirs(*this); 1305 bool VisitedUsingDirectives = false; 1306 bool LeftStartingScope = false; 1307 1308 // When performing a scope lookup, we want to find local extern decls. 1309 FindLocalExternScope FindLocals(R); 1310 1311 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) { 1312 bool SearchNamespaceScope = true; 1313 // Check whether the IdResolver has anything in this scope. 1314 for (; I != IEnd && S->isDeclScope(*I); ++I) { 1315 if (NamedDecl *ND = R.getAcceptableDecl(*I)) { 1316 if (NameKind == LookupRedeclarationWithLinkage && 1317 !(*I)->isTemplateParameter()) { 1318 // If it's a template parameter, we still find it, so we can diagnose 1319 // the invalid redeclaration. 1320 1321 // Determine whether this (or a previous) declaration is 1322 // out-of-scope. 1323 if (!LeftStartingScope && !Initial->isDeclScope(*I)) 1324 LeftStartingScope = true; 1325 1326 // If we found something outside of our starting scope that 1327 // does not have linkage, skip it. 1328 if (LeftStartingScope && !((*I)->hasLinkage())) { 1329 R.setShadowed(); 1330 continue; 1331 } 1332 } else { 1333 // We found something in this scope, we should not look at the 1334 // namespace scope 1335 SearchNamespaceScope = false; 1336 } 1337 R.addDecl(ND); 1338 } 1339 } 1340 if (!SearchNamespaceScope) { 1341 R.resolveKind(); 1342 if (S->isClassScope()) 1343 if (auto *Record = dyn_cast_if_present<CXXRecordDecl>(S->getEntity())) 1344 R.setNamingClass(Record); 1345 return true; 1346 } 1347 1348 if (NameKind == LookupLocalFriendName && !S->isClassScope()) { 1349 // C++11 [class.friend]p11: 1350 // If a friend declaration appears in a local class and the name 1351 // specified is an unqualified name, a prior declaration is 1352 // looked up without considering scopes that are outside the 1353 // innermost enclosing non-class scope. 1354 return false; 1355 } 1356 1357 if (DeclContext *Ctx = S->getLookupEntity()) { 1358 DeclContext *OuterCtx = findOuterContext(S); 1359 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) { 1360 // We do not directly look into transparent contexts, since 1361 // those entities will be found in the nearest enclosing 1362 // non-transparent context. 1363 if (Ctx->isTransparentContext()) 1364 continue; 1365 1366 // We do not look directly into function or method contexts, 1367 // since all of the local variables and parameters of the 1368 // function/method are present within the Scope. 1369 if (Ctx->isFunctionOrMethod()) { 1370 // If we have an Objective-C instance method, look for ivars 1371 // in the corresponding interface. 1372 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { 1373 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo()) 1374 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) { 1375 ObjCInterfaceDecl *ClassDeclared; 1376 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable( 1377 Name.getAsIdentifierInfo(), 1378 ClassDeclared)) { 1379 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) { 1380 R.addDecl(ND); 1381 R.resolveKind(); 1382 return true; 1383 } 1384 } 1385 } 1386 } 1387 1388 continue; 1389 } 1390 1391 // If this is a file context, we need to perform unqualified name 1392 // lookup considering using directives. 1393 if (Ctx->isFileContext()) { 1394 // If we haven't handled using directives yet, do so now. 1395 if (!VisitedUsingDirectives) { 1396 // Add using directives from this context up to the top level. 1397 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) { 1398 if (UCtx->isTransparentContext()) 1399 continue; 1400 1401 UDirs.visit(UCtx, UCtx); 1402 } 1403 1404 // Find the innermost file scope, so we can add using directives 1405 // from local scopes. 1406 Scope *InnermostFileScope = S; 1407 while (InnermostFileScope && 1408 !isNamespaceOrTranslationUnitScope(InnermostFileScope)) 1409 InnermostFileScope = InnermostFileScope->getParent(); 1410 UDirs.visitScopeChain(Initial, InnermostFileScope); 1411 1412 UDirs.done(); 1413 1414 VisitedUsingDirectives = true; 1415 } 1416 1417 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) { 1418 R.resolveKind(); 1419 return true; 1420 } 1421 1422 continue; 1423 } 1424 1425 // Perform qualified name lookup into this context. 1426 // FIXME: In some cases, we know that every name that could be found by 1427 // this qualified name lookup will also be on the identifier chain. For 1428 // example, inside a class without any base classes, we never need to 1429 // perform qualified lookup because all of the members are on top of the 1430 // identifier chain. 1431 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true)) 1432 return true; 1433 } 1434 } 1435 } 1436 1437 // Stop if we ran out of scopes. 1438 // FIXME: This really, really shouldn't be happening. 1439 if (!S) return false; 1440 1441 // If we are looking for members, no need to look into global/namespace scope. 1442 if (NameKind == LookupMemberName) 1443 return false; 1444 1445 // Collect UsingDirectiveDecls in all scopes, and recursively all 1446 // nominated namespaces by those using-directives. 1447 // 1448 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we 1449 // don't build it for each lookup! 1450 if (!VisitedUsingDirectives) { 1451 UDirs.visitScopeChain(Initial, S); 1452 UDirs.done(); 1453 } 1454 1455 // If we're not performing redeclaration lookup, do not look for local 1456 // extern declarations outside of a function scope. 1457 if (!R.isForRedeclaration()) 1458 FindLocals.restore(); 1459 1460 // Lookup namespace scope, and global scope. 1461 // Unqualified name lookup in C++ requires looking into scopes 1462 // that aren't strictly lexical, and therefore we walk through the 1463 // context as well as walking through the scopes. 1464 for (; S; S = S->getParent()) { 1465 // Check whether the IdResolver has anything in this scope. 1466 bool Found = false; 1467 for (; I != IEnd && S->isDeclScope(*I); ++I) { 1468 if (NamedDecl *ND = R.getAcceptableDecl(*I)) { 1469 // We found something. Look for anything else in our scope 1470 // with this same name and in an acceptable identifier 1471 // namespace, so that we can construct an overload set if we 1472 // need to. 1473 Found = true; 1474 R.addDecl(ND); 1475 } 1476 } 1477 1478 if (Found && S->isTemplateParamScope()) { 1479 R.resolveKind(); 1480 return true; 1481 } 1482 1483 DeclContext *Ctx = S->getLookupEntity(); 1484 if (Ctx) { 1485 DeclContext *OuterCtx = findOuterContext(S); 1486 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) { 1487 // We do not directly look into transparent contexts, since 1488 // those entities will be found in the nearest enclosing 1489 // non-transparent context. 1490 if (Ctx->isTransparentContext()) 1491 continue; 1492 1493 // If we have a context, and it's not a context stashed in the 1494 // template parameter scope for an out-of-line definition, also 1495 // look into that context. 1496 if (!(Found && S->isTemplateParamScope())) { 1497 assert(Ctx->isFileContext() && 1498 "We should have been looking only at file context here already."); 1499 1500 // Look into context considering using-directives. 1501 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) 1502 Found = true; 1503 } 1504 1505 if (Found) { 1506 R.resolveKind(); 1507 return true; 1508 } 1509 1510 if (R.isForRedeclaration() && !Ctx->isTransparentContext()) 1511 return false; 1512 } 1513 } 1514 1515 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext()) 1516 return false; 1517 } 1518 1519 return !R.empty(); 1520 } 1521 1522 void Sema::makeMergedDefinitionVisible(NamedDecl *ND) { 1523 if (auto *M = getCurrentModule()) 1524 Context.mergeDefinitionIntoModule(ND, M); 1525 else 1526 // We're not building a module; just make the definition visible. 1527 ND->setVisibleDespiteOwningModule(); 1528 1529 // If ND is a template declaration, make the template parameters 1530 // visible too. They're not (necessarily) within a mergeable DeclContext. 1531 if (auto *TD = dyn_cast<TemplateDecl>(ND)) 1532 for (auto *Param : *TD->getTemplateParameters()) 1533 makeMergedDefinitionVisible(Param); 1534 } 1535 1536 /// Find the module in which the given declaration was defined. 1537 static Module *getDefiningModule(Sema &S, Decl *Entity) { 1538 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) { 1539 // If this function was instantiated from a template, the defining module is 1540 // the module containing the pattern. 1541 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 1542 Entity = Pattern; 1543 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) { 1544 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern()) 1545 Entity = Pattern; 1546 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) { 1547 if (auto *Pattern = ED->getTemplateInstantiationPattern()) 1548 Entity = Pattern; 1549 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) { 1550 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern()) 1551 Entity = Pattern; 1552 } 1553 1554 // Walk up to the containing context. That might also have been instantiated 1555 // from a template. 1556 DeclContext *Context = Entity->getLexicalDeclContext(); 1557 if (Context->isFileContext()) 1558 return S.getOwningModule(Entity); 1559 return getDefiningModule(S, cast<Decl>(Context)); 1560 } 1561 1562 llvm::DenseSet<Module*> &Sema::getLookupModules() { 1563 unsigned N = CodeSynthesisContexts.size(); 1564 for (unsigned I = CodeSynthesisContextLookupModules.size(); 1565 I != N; ++I) { 1566 Module *M = CodeSynthesisContexts[I].Entity ? 1567 getDefiningModule(*this, CodeSynthesisContexts[I].Entity) : 1568 nullptr; 1569 if (M && !LookupModulesCache.insert(M).second) 1570 M = nullptr; 1571 CodeSynthesisContextLookupModules.push_back(M); 1572 } 1573 return LookupModulesCache; 1574 } 1575 1576 /// Determine if we could use all the declarations in the module. 1577 bool Sema::isUsableModule(const Module *M) { 1578 assert(M && "We shouldn't check nullness for module here"); 1579 // Return quickly if we cached the result. 1580 if (UsableModuleUnitsCache.count(M)) 1581 return true; 1582 1583 // If M is the global module fragment of the current translation unit. So it 1584 // should be usable. 1585 // [module.global.frag]p1: 1586 // The global module fragment can be used to provide declarations that are 1587 // attached to the global module and usable within the module unit. 1588 if (M == TheGlobalModuleFragment || M == TheImplicitGlobalModuleFragment || 1589 M == TheExportedImplicitGlobalModuleFragment || 1590 // If M is the module we're parsing, it should be usable. This covers the 1591 // private module fragment. The private module fragment is usable only if 1592 // it is within the current module unit. And it must be the current 1593 // parsing module unit if it is within the current module unit according 1594 // to the grammar of the private module fragment. NOTE: This is covered by 1595 // the following condition. The intention of the check is to avoid string 1596 // comparison as much as possible. 1597 M == getCurrentModule() || 1598 // The module unit which is in the same module with the current module 1599 // unit is usable. 1600 // 1601 // FIXME: Here we judge if they are in the same module by comparing the 1602 // string. Is there any better solution? 1603 M->getPrimaryModuleInterfaceName() == 1604 llvm::StringRef(getLangOpts().CurrentModule).split(':').first) { 1605 UsableModuleUnitsCache.insert(M); 1606 return true; 1607 } 1608 1609 return false; 1610 } 1611 1612 bool Sema::hasVisibleMergedDefinition(const NamedDecl *Def) { 1613 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def)) 1614 if (isModuleVisible(Merged)) 1615 return true; 1616 return false; 1617 } 1618 1619 bool Sema::hasMergedDefinitionInCurrentModule(const NamedDecl *Def) { 1620 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def)) 1621 if (isUsableModule(Merged)) 1622 return true; 1623 return false; 1624 } 1625 1626 template <typename ParmDecl> 1627 static bool 1628 hasAcceptableDefaultArgument(Sema &S, const ParmDecl *D, 1629 llvm::SmallVectorImpl<Module *> *Modules, 1630 Sema::AcceptableKind Kind) { 1631 if (!D->hasDefaultArgument()) 1632 return false; 1633 1634 llvm::SmallPtrSet<const ParmDecl *, 4> Visited; 1635 while (D && Visited.insert(D).second) { 1636 auto &DefaultArg = D->getDefaultArgStorage(); 1637 if (!DefaultArg.isInherited() && S.isAcceptable(D, Kind)) 1638 return true; 1639 1640 if (!DefaultArg.isInherited() && Modules) { 1641 auto *NonConstD = const_cast<ParmDecl*>(D); 1642 Modules->push_back(S.getOwningModule(NonConstD)); 1643 } 1644 1645 // If there was a previous default argument, maybe its parameter is 1646 // acceptable. 1647 D = DefaultArg.getInheritedFrom(); 1648 } 1649 return false; 1650 } 1651 1652 bool Sema::hasAcceptableDefaultArgument( 1653 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules, 1654 Sema::AcceptableKind Kind) { 1655 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D)) 1656 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind); 1657 1658 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D)) 1659 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind); 1660 1661 return ::hasAcceptableDefaultArgument( 1662 *this, cast<TemplateTemplateParmDecl>(D), Modules, Kind); 1663 } 1664 1665 bool Sema::hasVisibleDefaultArgument(const NamedDecl *D, 1666 llvm::SmallVectorImpl<Module *> *Modules) { 1667 return hasAcceptableDefaultArgument(D, Modules, 1668 Sema::AcceptableKind::Visible); 1669 } 1670 1671 bool Sema::hasReachableDefaultArgument( 1672 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { 1673 return hasAcceptableDefaultArgument(D, Modules, 1674 Sema::AcceptableKind::Reachable); 1675 } 1676 1677 template <typename Filter> 1678 static bool 1679 hasAcceptableDeclarationImpl(Sema &S, const NamedDecl *D, 1680 llvm::SmallVectorImpl<Module *> *Modules, Filter F, 1681 Sema::AcceptableKind Kind) { 1682 bool HasFilteredRedecls = false; 1683 1684 for (auto *Redecl : D->redecls()) { 1685 auto *R = cast<NamedDecl>(Redecl); 1686 if (!F(R)) 1687 continue; 1688 1689 if (S.isAcceptable(R, Kind)) 1690 return true; 1691 1692 HasFilteredRedecls = true; 1693 1694 if (Modules) 1695 Modules->push_back(R->getOwningModule()); 1696 } 1697 1698 // Only return false if there is at least one redecl that is not filtered out. 1699 if (HasFilteredRedecls) 1700 return false; 1701 1702 return true; 1703 } 1704 1705 static bool 1706 hasAcceptableExplicitSpecialization(Sema &S, const NamedDecl *D, 1707 llvm::SmallVectorImpl<Module *> *Modules, 1708 Sema::AcceptableKind Kind) { 1709 return hasAcceptableDeclarationImpl( 1710 S, D, Modules, 1711 [](const NamedDecl *D) { 1712 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) 1713 return RD->getTemplateSpecializationKind() == 1714 TSK_ExplicitSpecialization; 1715 if (auto *FD = dyn_cast<FunctionDecl>(D)) 1716 return FD->getTemplateSpecializationKind() == 1717 TSK_ExplicitSpecialization; 1718 if (auto *VD = dyn_cast<VarDecl>(D)) 1719 return VD->getTemplateSpecializationKind() == 1720 TSK_ExplicitSpecialization; 1721 llvm_unreachable("unknown explicit specialization kind"); 1722 }, 1723 Kind); 1724 } 1725 1726 bool Sema::hasVisibleExplicitSpecialization( 1727 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { 1728 return ::hasAcceptableExplicitSpecialization(*this, D, Modules, 1729 Sema::AcceptableKind::Visible); 1730 } 1731 1732 bool Sema::hasReachableExplicitSpecialization( 1733 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { 1734 return ::hasAcceptableExplicitSpecialization(*this, D, Modules, 1735 Sema::AcceptableKind::Reachable); 1736 } 1737 1738 static bool 1739 hasAcceptableMemberSpecialization(Sema &S, const NamedDecl *D, 1740 llvm::SmallVectorImpl<Module *> *Modules, 1741 Sema::AcceptableKind Kind) { 1742 assert(isa<CXXRecordDecl>(D->getDeclContext()) && 1743 "not a member specialization"); 1744 return hasAcceptableDeclarationImpl( 1745 S, D, Modules, 1746 [](const NamedDecl *D) { 1747 // If the specialization is declared at namespace scope, then it's a 1748 // member specialization declaration. If it's lexically inside the class 1749 // definition then it was instantiated. 1750 // 1751 // FIXME: This is a hack. There should be a better way to determine 1752 // this. 1753 // FIXME: What about MS-style explicit specializations declared within a 1754 // class definition? 1755 return D->getLexicalDeclContext()->isFileContext(); 1756 }, 1757 Kind); 1758 } 1759 1760 bool Sema::hasVisibleMemberSpecialization( 1761 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { 1762 return hasAcceptableMemberSpecialization(*this, D, Modules, 1763 Sema::AcceptableKind::Visible); 1764 } 1765 1766 bool Sema::hasReachableMemberSpecialization( 1767 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { 1768 return hasAcceptableMemberSpecialization(*this, D, Modules, 1769 Sema::AcceptableKind::Reachable); 1770 } 1771 1772 /// Determine whether a declaration is acceptable to name lookup. 1773 /// 1774 /// This routine determines whether the declaration D is acceptable in the 1775 /// current lookup context, taking into account the current template 1776 /// instantiation stack. During template instantiation, a declaration is 1777 /// acceptable if it is acceptable from a module containing any entity on the 1778 /// template instantiation path (by instantiating a template, you allow it to 1779 /// see the declarations that your module can see, including those later on in 1780 /// your module). 1781 bool LookupResult::isAcceptableSlow(Sema &SemaRef, NamedDecl *D, 1782 Sema::AcceptableKind Kind) { 1783 assert(!D->isUnconditionallyVisible() && 1784 "should not call this: not in slow case"); 1785 1786 Module *DeclModule = SemaRef.getOwningModule(D); 1787 assert(DeclModule && "hidden decl has no owning module"); 1788 1789 // If the owning module is visible, the decl is acceptable. 1790 if (SemaRef.isModuleVisible(DeclModule, 1791 D->isInvisibleOutsideTheOwningModule())) 1792 return true; 1793 1794 // Determine whether a decl context is a file context for the purpose of 1795 // visibility/reachability. This looks through some (export and linkage spec) 1796 // transparent contexts, but not others (enums). 1797 auto IsEffectivelyFileContext = [](const DeclContext *DC) { 1798 return DC->isFileContext() || isa<LinkageSpecDecl>(DC) || 1799 isa<ExportDecl>(DC); 1800 }; 1801 1802 // If this declaration is not at namespace scope 1803 // then it is acceptable if its lexical parent has a acceptable definition. 1804 DeclContext *DC = D->getLexicalDeclContext(); 1805 if (DC && !IsEffectivelyFileContext(DC)) { 1806 // For a parameter, check whether our current template declaration's 1807 // lexical context is acceptable, not whether there's some other acceptable 1808 // definition of it, because parameters aren't "within" the definition. 1809 // 1810 // In C++ we need to check for a acceptable definition due to ODR merging, 1811 // and in C we must not because each declaration of a function gets its own 1812 // set of declarations for tags in prototype scope. 1813 bool AcceptableWithinParent; 1814 if (D->isTemplateParameter()) { 1815 bool SearchDefinitions = true; 1816 if (const auto *DCD = dyn_cast<Decl>(DC)) { 1817 if (const auto *TD = DCD->getDescribedTemplate()) { 1818 TemplateParameterList *TPL = TD->getTemplateParameters(); 1819 auto Index = getDepthAndIndex(D).second; 1820 SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D; 1821 } 1822 } 1823 if (SearchDefinitions) 1824 AcceptableWithinParent = 1825 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind); 1826 else 1827 AcceptableWithinParent = 1828 isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind); 1829 } else if (isa<ParmVarDecl>(D) || 1830 (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus)) 1831 AcceptableWithinParent = isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind); 1832 else if (D->isModulePrivate()) { 1833 // A module-private declaration is only acceptable if an enclosing lexical 1834 // parent was merged with another definition in the current module. 1835 AcceptableWithinParent = false; 1836 do { 1837 if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) { 1838 AcceptableWithinParent = true; 1839 break; 1840 } 1841 DC = DC->getLexicalParent(); 1842 } while (!IsEffectivelyFileContext(DC)); 1843 } else { 1844 AcceptableWithinParent = 1845 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind); 1846 } 1847 1848 if (AcceptableWithinParent && SemaRef.CodeSynthesisContexts.empty() && 1849 Kind == Sema::AcceptableKind::Visible && 1850 // FIXME: Do something better in this case. 1851 !SemaRef.getLangOpts().ModulesLocalVisibility) { 1852 // Cache the fact that this declaration is implicitly visible because 1853 // its parent has a visible definition. 1854 D->setVisibleDespiteOwningModule(); 1855 } 1856 return AcceptableWithinParent; 1857 } 1858 1859 if (Kind == Sema::AcceptableKind::Visible) 1860 return false; 1861 1862 assert(Kind == Sema::AcceptableKind::Reachable && 1863 "Additional Sema::AcceptableKind?"); 1864 return isReachableSlow(SemaRef, D); 1865 } 1866 1867 bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) { 1868 // The module might be ordinarily visible. For a module-private query, that 1869 // means it is part of the current module. 1870 if (ModulePrivate && isUsableModule(M)) 1871 return true; 1872 1873 // For a query which is not module-private, that means it is in our visible 1874 // module set. 1875 if (!ModulePrivate && VisibleModules.isVisible(M)) 1876 return true; 1877 1878 // Otherwise, it might be visible by virtue of the query being within a 1879 // template instantiation or similar that is permitted to look inside M. 1880 1881 // Find the extra places where we need to look. 1882 const auto &LookupModules = getLookupModules(); 1883 if (LookupModules.empty()) 1884 return false; 1885 1886 // If our lookup set contains the module, it's visible. 1887 if (LookupModules.count(M)) 1888 return true; 1889 1890 // The global module fragments are visible to its corresponding module unit. 1891 // So the global module fragment should be visible if the its corresponding 1892 // module unit is visible. 1893 if (M->isGlobalModule() && LookupModules.count(M->getTopLevelModule())) 1894 return true; 1895 1896 // For a module-private query, that's everywhere we get to look. 1897 if (ModulePrivate) 1898 return false; 1899 1900 // Check whether M is transitively exported to an import of the lookup set. 1901 return llvm::any_of(LookupModules, [&](const Module *LookupM) { 1902 return LookupM->isModuleVisible(M); 1903 }); 1904 } 1905 1906 // FIXME: Return false directly if we don't have an interface dependency on the 1907 // translation unit containing D. 1908 bool LookupResult::isReachableSlow(Sema &SemaRef, NamedDecl *D) { 1909 assert(!isVisible(SemaRef, D) && "Shouldn't call the slow case.\n"); 1910 1911 Module *DeclModule = SemaRef.getOwningModule(D); 1912 assert(DeclModule && "hidden decl has no owning module"); 1913 1914 // Entities in header like modules are reachable only if they're visible. 1915 if (DeclModule->isHeaderLikeModule()) 1916 return false; 1917 1918 if (!D->isInAnotherModuleUnit()) 1919 return true; 1920 1921 // [module.reach]/p3: 1922 // A declaration D is reachable from a point P if: 1923 // ... 1924 // - D is not discarded ([module.global.frag]), appears in a translation unit 1925 // that is reachable from P, and does not appear within a private module 1926 // fragment. 1927 // 1928 // A declaration that's discarded in the GMF should be module-private. 1929 if (D->isModulePrivate()) 1930 return false; 1931 1932 // [module.reach]/p1 1933 // A translation unit U is necessarily reachable from a point P if U is a 1934 // module interface unit on which the translation unit containing P has an 1935 // interface dependency, or the translation unit containing P imports U, in 1936 // either case prior to P ([module.import]). 1937 // 1938 // [module.import]/p10 1939 // A translation unit has an interface dependency on a translation unit U if 1940 // it contains a declaration (possibly a module-declaration) that imports U 1941 // or if it has an interface dependency on a translation unit that has an 1942 // interface dependency on U. 1943 // 1944 // So we could conclude the module unit U is necessarily reachable if: 1945 // (1) The module unit U is module interface unit. 1946 // (2) The current unit has an interface dependency on the module unit U. 1947 // 1948 // Here we only check for the first condition. Since we couldn't see 1949 // DeclModule if it isn't (transitively) imported. 1950 if (DeclModule->getTopLevelModule()->isModuleInterfaceUnit()) 1951 return true; 1952 1953 // [module.reach]/p2 1954 // Additional translation units on 1955 // which the point within the program has an interface dependency may be 1956 // considered reachable, but it is unspecified which are and under what 1957 // circumstances. 1958 // 1959 // The decision here is to treat all additional tranditional units as 1960 // unreachable. 1961 return false; 1962 } 1963 1964 bool Sema::isAcceptableSlow(const NamedDecl *D, Sema::AcceptableKind Kind) { 1965 return LookupResult::isAcceptable(*this, const_cast<NamedDecl *>(D), Kind); 1966 } 1967 1968 bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) { 1969 // FIXME: If there are both visible and hidden declarations, we need to take 1970 // into account whether redeclaration is possible. Example: 1971 // 1972 // Non-imported module: 1973 // int f(T); // #1 1974 // Some TU: 1975 // static int f(U); // #2, not a redeclaration of #1 1976 // int f(T); // #3, finds both, should link with #1 if T != U, but 1977 // // with #2 if T == U; neither should be ambiguous. 1978 for (auto *D : R) { 1979 if (isVisible(D)) 1980 return true; 1981 assert(D->isExternallyDeclarable() && 1982 "should not have hidden, non-externally-declarable result here"); 1983 } 1984 1985 // This function is called once "New" is essentially complete, but before a 1986 // previous declaration is attached. We can't query the linkage of "New" in 1987 // general, because attaching the previous declaration can change the 1988 // linkage of New to match the previous declaration. 1989 // 1990 // However, because we've just determined that there is no *visible* prior 1991 // declaration, we can compute the linkage here. There are two possibilities: 1992 // 1993 // * This is not a redeclaration; it's safe to compute the linkage now. 1994 // 1995 // * This is a redeclaration of a prior declaration that is externally 1996 // redeclarable. In that case, the linkage of the declaration is not 1997 // changed by attaching the prior declaration, because both are externally 1998 // declarable (and thus ExternalLinkage or VisibleNoLinkage). 1999 // 2000 // FIXME: This is subtle and fragile. 2001 return New->isExternallyDeclarable(); 2002 } 2003 2004 /// Retrieve the visible declaration corresponding to D, if any. 2005 /// 2006 /// This routine determines whether the declaration D is visible in the current 2007 /// module, with the current imports. If not, it checks whether any 2008 /// redeclaration of D is visible, and if so, returns that declaration. 2009 /// 2010 /// \returns D, or a visible previous declaration of D, whichever is more recent 2011 /// and visible. If no declaration of D is visible, returns null. 2012 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D, 2013 unsigned IDNS) { 2014 assert(!LookupResult::isAvailableForLookup(SemaRef, D) && "not in slow case"); 2015 2016 for (auto *RD : D->redecls()) { 2017 // Don't bother with extra checks if we already know this one isn't visible. 2018 if (RD == D) 2019 continue; 2020 2021 auto ND = cast<NamedDecl>(RD); 2022 // FIXME: This is wrong in the case where the previous declaration is not 2023 // visible in the same scope as D. This needs to be done much more 2024 // carefully. 2025 if (ND->isInIdentifierNamespace(IDNS) && 2026 LookupResult::isAvailableForLookup(SemaRef, ND)) 2027 return ND; 2028 } 2029 2030 return nullptr; 2031 } 2032 2033 bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D, 2034 llvm::SmallVectorImpl<Module *> *Modules) { 2035 assert(!isVisible(D) && "not in slow case"); 2036 return hasAcceptableDeclarationImpl( 2037 *this, D, Modules, [](const NamedDecl *) { return true; }, 2038 Sema::AcceptableKind::Visible); 2039 } 2040 2041 bool Sema::hasReachableDeclarationSlow( 2042 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { 2043 assert(!isReachable(D) && "not in slow case"); 2044 return hasAcceptableDeclarationImpl( 2045 *this, D, Modules, [](const NamedDecl *) { return true; }, 2046 Sema::AcceptableKind::Reachable); 2047 } 2048 2049 NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const { 2050 if (auto *ND = dyn_cast<NamespaceDecl>(D)) { 2051 // Namespaces are a bit of a special case: we expect there to be a lot of 2052 // redeclarations of some namespaces, all declarations of a namespace are 2053 // essentially interchangeable, all declarations are found by name lookup 2054 // if any is, and namespaces are never looked up during template 2055 // instantiation. So we benefit from caching the check in this case, and 2056 // it is correct to do so. 2057 auto *Key = ND->getCanonicalDecl(); 2058 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key)) 2059 return Acceptable; 2060 auto *Acceptable = isVisible(getSema(), Key) 2061 ? Key 2062 : findAcceptableDecl(getSema(), Key, IDNS); 2063 if (Acceptable) 2064 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable)); 2065 return Acceptable; 2066 } 2067 2068 return findAcceptableDecl(getSema(), D, IDNS); 2069 } 2070 2071 bool LookupResult::isVisible(Sema &SemaRef, NamedDecl *D) { 2072 // If this declaration is already visible, return it directly. 2073 if (D->isUnconditionallyVisible()) 2074 return true; 2075 2076 // During template instantiation, we can refer to hidden declarations, if 2077 // they were visible in any module along the path of instantiation. 2078 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Visible); 2079 } 2080 2081 bool LookupResult::isReachable(Sema &SemaRef, NamedDecl *D) { 2082 if (D->isUnconditionallyVisible()) 2083 return true; 2084 2085 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Reachable); 2086 } 2087 2088 bool LookupResult::isAvailableForLookup(Sema &SemaRef, NamedDecl *ND) { 2089 // We should check the visibility at the callsite already. 2090 if (isVisible(SemaRef, ND)) 2091 return true; 2092 2093 // Deduction guide lives in namespace scope generally, but it is just a 2094 // hint to the compilers. What we actually lookup for is the generated member 2095 // of the corresponding template. So it is sufficient to check the 2096 // reachability of the template decl. 2097 if (auto *DeductionGuide = ND->getDeclName().getCXXDeductionGuideTemplate()) 2098 return SemaRef.hasReachableDefinition(DeductionGuide); 2099 2100 // FIXME: The lookup for allocation function is a standalone process. 2101 // (We can find the logics in Sema::FindAllocationFunctions) 2102 // 2103 // Such structure makes it a problem when we instantiate a template 2104 // declaration using placement allocation function if the placement 2105 // allocation function is invisible. 2106 // (See https://github.com/llvm/llvm-project/issues/59601) 2107 // 2108 // Here we workaround it by making the placement allocation functions 2109 // always acceptable. The downside is that we can't diagnose the direct 2110 // use of the invisible placement allocation functions. (Although such uses 2111 // should be rare). 2112 if (auto *FD = dyn_cast<FunctionDecl>(ND); 2113 FD && FD->isReservedGlobalPlacementOperator()) 2114 return true; 2115 2116 auto *DC = ND->getDeclContext(); 2117 // If ND is not visible and it is at namespace scope, it shouldn't be found 2118 // by name lookup. 2119 if (DC->isFileContext()) 2120 return false; 2121 2122 // [module.interface]p7 2123 // Class and enumeration member names can be found by name lookup in any 2124 // context in which a definition of the type is reachable. 2125 // 2126 // FIXME: The current implementation didn't consider about scope. For example, 2127 // ``` 2128 // // m.cppm 2129 // export module m; 2130 // enum E1 { e1 }; 2131 // // Use.cpp 2132 // import m; 2133 // void test() { 2134 // auto a = E1::e1; // Error as expected. 2135 // auto b = e1; // Should be error. namespace-scope name e1 is not visible 2136 // } 2137 // ``` 2138 // For the above example, the current implementation would emit error for `a` 2139 // correctly. However, the implementation wouldn't diagnose about `b` now. 2140 // Since we only check the reachability for the parent only. 2141 // See clang/test/CXX/module/module.interface/p7.cpp for example. 2142 if (auto *TD = dyn_cast<TagDecl>(DC)) 2143 return SemaRef.hasReachableDefinition(TD); 2144 2145 return false; 2146 } 2147 2148 /// Perform unqualified name lookup starting from a given 2149 /// scope. 2150 /// 2151 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is 2152 /// used to find names within the current scope. For example, 'x' in 2153 /// @code 2154 /// int x; 2155 /// int f() { 2156 /// return x; // unqualified name look finds 'x' in the global scope 2157 /// } 2158 /// @endcode 2159 /// 2160 /// Different lookup criteria can find different names. For example, a 2161 /// particular scope can have both a struct and a function of the same 2162 /// name, and each can be found by certain lookup criteria. For more 2163 /// information about lookup criteria, see the documentation for the 2164 /// class LookupCriteria. 2165 /// 2166 /// @param S The scope from which unqualified name lookup will 2167 /// begin. If the lookup criteria permits, name lookup may also search 2168 /// in the parent scopes. 2169 /// 2170 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to 2171 /// look up and the lookup kind), and is updated with the results of lookup 2172 /// including zero or more declarations and possibly additional information 2173 /// used to diagnose ambiguities. 2174 /// 2175 /// @returns \c true if lookup succeeded and false otherwise. 2176 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation, 2177 bool ForceNoCPlusPlus) { 2178 DeclarationName Name = R.getLookupName(); 2179 if (!Name) return false; 2180 2181 LookupNameKind NameKind = R.getLookupKind(); 2182 2183 if (!getLangOpts().CPlusPlus || ForceNoCPlusPlus) { 2184 // Unqualified name lookup in C/Objective-C is purely lexical, so 2185 // search in the declarations attached to the name. 2186 if (NameKind == Sema::LookupRedeclarationWithLinkage) { 2187 // Find the nearest non-transparent declaration scope. 2188 while (!(S->getFlags() & Scope::DeclScope) || 2189 (S->getEntity() && S->getEntity()->isTransparentContext())) 2190 S = S->getParent(); 2191 } 2192 2193 // When performing a scope lookup, we want to find local extern decls. 2194 FindLocalExternScope FindLocals(R); 2195 2196 // Scan up the scope chain looking for a decl that matches this 2197 // identifier that is in the appropriate namespace. This search 2198 // should not take long, as shadowing of names is uncommon, and 2199 // deep shadowing is extremely uncommon. 2200 bool LeftStartingScope = false; 2201 2202 for (IdentifierResolver::iterator I = IdResolver.begin(Name), 2203 IEnd = IdResolver.end(); 2204 I != IEnd; ++I) 2205 if (NamedDecl *D = R.getAcceptableDecl(*I)) { 2206 if (NameKind == LookupRedeclarationWithLinkage) { 2207 // Determine whether this (or a previous) declaration is 2208 // out-of-scope. 2209 if (!LeftStartingScope && !S->isDeclScope(*I)) 2210 LeftStartingScope = true; 2211 2212 // If we found something outside of our starting scope that 2213 // does not have linkage, skip it. 2214 if (LeftStartingScope && !((*I)->hasLinkage())) { 2215 R.setShadowed(); 2216 continue; 2217 } 2218 } 2219 else if (NameKind == LookupObjCImplicitSelfParam && 2220 !isa<ImplicitParamDecl>(*I)) 2221 continue; 2222 2223 R.addDecl(D); 2224 2225 // Check whether there are any other declarations with the same name 2226 // and in the same scope. 2227 if (I != IEnd) { 2228 // Find the scope in which this declaration was declared (if it 2229 // actually exists in a Scope). 2230 while (S && !S->isDeclScope(D)) 2231 S = S->getParent(); 2232 2233 // If the scope containing the declaration is the translation unit, 2234 // then we'll need to perform our checks based on the matching 2235 // DeclContexts rather than matching scopes. 2236 if (S && isNamespaceOrTranslationUnitScope(S)) 2237 S = nullptr; 2238 2239 // Compute the DeclContext, if we need it. 2240 DeclContext *DC = nullptr; 2241 if (!S) 2242 DC = (*I)->getDeclContext()->getRedeclContext(); 2243 2244 IdentifierResolver::iterator LastI = I; 2245 for (++LastI; LastI != IEnd; ++LastI) { 2246 if (S) { 2247 // Match based on scope. 2248 if (!S->isDeclScope(*LastI)) 2249 break; 2250 } else { 2251 // Match based on DeclContext. 2252 DeclContext *LastDC 2253 = (*LastI)->getDeclContext()->getRedeclContext(); 2254 if (!LastDC->Equals(DC)) 2255 break; 2256 } 2257 2258 // If the declaration is in the right namespace and visible, add it. 2259 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI)) 2260 R.addDecl(LastD); 2261 } 2262 2263 R.resolveKind(); 2264 } 2265 2266 return true; 2267 } 2268 } else { 2269 // Perform C++ unqualified name lookup. 2270 if (CppLookupName(R, S)) 2271 return true; 2272 } 2273 2274 // If we didn't find a use of this identifier, and if the identifier 2275 // corresponds to a compiler builtin, create the decl object for the builtin 2276 // now, injecting it into translation unit scope, and return it. 2277 if (AllowBuiltinCreation && LookupBuiltin(R)) 2278 return true; 2279 2280 // If we didn't find a use of this identifier, the ExternalSource 2281 // may be able to handle the situation. 2282 // Note: some lookup failures are expected! 2283 // See e.g. R.isForRedeclaration(). 2284 return (ExternalSource && ExternalSource->LookupUnqualified(R, S)); 2285 } 2286 2287 /// Perform qualified name lookup in the namespaces nominated by 2288 /// using directives by the given context. 2289 /// 2290 /// C++98 [namespace.qual]p2: 2291 /// Given X::m (where X is a user-declared namespace), or given \::m 2292 /// (where X is the global namespace), let S be the set of all 2293 /// declarations of m in X and in the transitive closure of all 2294 /// namespaces nominated by using-directives in X and its used 2295 /// namespaces, except that using-directives are ignored in any 2296 /// namespace, including X, directly containing one or more 2297 /// declarations of m. No namespace is searched more than once in 2298 /// the lookup of a name. If S is the empty set, the program is 2299 /// ill-formed. Otherwise, if S has exactly one member, or if the 2300 /// context of the reference is a using-declaration 2301 /// (namespace.udecl), S is the required set of declarations of 2302 /// m. Otherwise if the use of m is not one that allows a unique 2303 /// declaration to be chosen from S, the program is ill-formed. 2304 /// 2305 /// C++98 [namespace.qual]p5: 2306 /// During the lookup of a qualified namespace member name, if the 2307 /// lookup finds more than one declaration of the member, and if one 2308 /// declaration introduces a class name or enumeration name and the 2309 /// other declarations either introduce the same object, the same 2310 /// enumerator or a set of functions, the non-type name hides the 2311 /// class or enumeration name if and only if the declarations are 2312 /// from the same namespace; otherwise (the declarations are from 2313 /// different namespaces), the program is ill-formed. 2314 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R, 2315 DeclContext *StartDC) { 2316 assert(StartDC->isFileContext() && "start context is not a file context"); 2317 2318 // We have not yet looked into these namespaces, much less added 2319 // their "using-children" to the queue. 2320 SmallVector<NamespaceDecl*, 8> Queue; 2321 2322 // We have at least added all these contexts to the queue. 2323 llvm::SmallPtrSet<DeclContext*, 8> Visited; 2324 Visited.insert(StartDC); 2325 2326 // We have already looked into the initial namespace; seed the queue 2327 // with its using-children. 2328 for (auto *I : StartDC->using_directives()) { 2329 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace(); 2330 if (S.isVisible(I) && Visited.insert(ND).second) 2331 Queue.push_back(ND); 2332 } 2333 2334 // The easiest way to implement the restriction in [namespace.qual]p5 2335 // is to check whether any of the individual results found a tag 2336 // and, if so, to declare an ambiguity if the final result is not 2337 // a tag. 2338 bool FoundTag = false; 2339 bool FoundNonTag = false; 2340 2341 LookupResult LocalR(LookupResult::Temporary, R); 2342 2343 bool Found = false; 2344 while (!Queue.empty()) { 2345 NamespaceDecl *ND = Queue.pop_back_val(); 2346 2347 // We go through some convolutions here to avoid copying results 2348 // between LookupResults. 2349 bool UseLocal = !R.empty(); 2350 LookupResult &DirectR = UseLocal ? LocalR : R; 2351 bool FoundDirect = LookupDirect(S, DirectR, ND); 2352 2353 if (FoundDirect) { 2354 // First do any local hiding. 2355 DirectR.resolveKind(); 2356 2357 // If the local result is a tag, remember that. 2358 if (DirectR.isSingleTagDecl()) 2359 FoundTag = true; 2360 else 2361 FoundNonTag = true; 2362 2363 // Append the local results to the total results if necessary. 2364 if (UseLocal) { 2365 R.addAllDecls(LocalR); 2366 LocalR.clear(); 2367 } 2368 } 2369 2370 // If we find names in this namespace, ignore its using directives. 2371 if (FoundDirect) { 2372 Found = true; 2373 continue; 2374 } 2375 2376 for (auto *I : ND->using_directives()) { 2377 NamespaceDecl *Nom = I->getNominatedNamespace(); 2378 if (S.isVisible(I) && Visited.insert(Nom).second) 2379 Queue.push_back(Nom); 2380 } 2381 } 2382 2383 if (Found) { 2384 if (FoundTag && FoundNonTag) 2385 R.setAmbiguousQualifiedTagHiding(); 2386 else 2387 R.resolveKind(); 2388 } 2389 2390 return Found; 2391 } 2392 2393 /// Perform qualified name lookup into a given context. 2394 /// 2395 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find 2396 /// names when the context of those names is explicit specified, e.g., 2397 /// "std::vector" or "x->member", or as part of unqualified name lookup. 2398 /// 2399 /// Different lookup criteria can find different names. For example, a 2400 /// particular scope can have both a struct and a function of the same 2401 /// name, and each can be found by certain lookup criteria. For more 2402 /// information about lookup criteria, see the documentation for the 2403 /// class LookupCriteria. 2404 /// 2405 /// \param R captures both the lookup criteria and any lookup results found. 2406 /// 2407 /// \param LookupCtx The context in which qualified name lookup will 2408 /// search. If the lookup criteria permits, name lookup may also search 2409 /// in the parent contexts or (for C++ classes) base classes. 2410 /// 2411 /// \param InUnqualifiedLookup true if this is qualified name lookup that 2412 /// occurs as part of unqualified name lookup. 2413 /// 2414 /// \returns true if lookup succeeded, false if it failed. 2415 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 2416 bool InUnqualifiedLookup) { 2417 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context"); 2418 2419 if (!R.getLookupName()) 2420 return false; 2421 2422 // Make sure that the declaration context is complete. 2423 assert((!isa<TagDecl>(LookupCtx) || 2424 LookupCtx->isDependentContext() || 2425 cast<TagDecl>(LookupCtx)->isCompleteDefinition() || 2426 cast<TagDecl>(LookupCtx)->isBeingDefined()) && 2427 "Declaration context must already be complete!"); 2428 2429 struct QualifiedLookupInScope { 2430 bool oldVal; 2431 DeclContext *Context; 2432 // Set flag in DeclContext informing debugger that we're looking for qualified name 2433 QualifiedLookupInScope(DeclContext *ctx) 2434 : oldVal(ctx->shouldUseQualifiedLookup()), Context(ctx) { 2435 ctx->setUseQualifiedLookup(); 2436 } 2437 ~QualifiedLookupInScope() { 2438 Context->setUseQualifiedLookup(oldVal); 2439 } 2440 } QL(LookupCtx); 2441 2442 if (LookupDirect(*this, R, LookupCtx)) { 2443 R.resolveKind(); 2444 if (isa<CXXRecordDecl>(LookupCtx)) 2445 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx)); 2446 return true; 2447 } 2448 2449 // Don't descend into implied contexts for redeclarations. 2450 // C++98 [namespace.qual]p6: 2451 // In a declaration for a namespace member in which the 2452 // declarator-id is a qualified-id, given that the qualified-id 2453 // for the namespace member has the form 2454 // nested-name-specifier unqualified-id 2455 // the unqualified-id shall name a member of the namespace 2456 // designated by the nested-name-specifier. 2457 // See also [class.mfct]p5 and [class.static.data]p2. 2458 if (R.isForRedeclaration()) 2459 return false; 2460 2461 // If this is a namespace, look it up in the implied namespaces. 2462 if (LookupCtx->isFileContext()) 2463 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx); 2464 2465 // If this isn't a C++ class, we aren't allowed to look into base 2466 // classes, we're done. 2467 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx); 2468 if (!LookupRec || !LookupRec->getDefinition()) 2469 return false; 2470 2471 // We're done for lookups that can never succeed for C++ classes. 2472 if (R.getLookupKind() == LookupOperatorName || 2473 R.getLookupKind() == LookupNamespaceName || 2474 R.getLookupKind() == LookupObjCProtocolName || 2475 R.getLookupKind() == LookupLabel) 2476 return false; 2477 2478 // If we're performing qualified name lookup into a dependent class, 2479 // then we are actually looking into a current instantiation. If we have any 2480 // dependent base classes, then we either have to delay lookup until 2481 // template instantiation time (at which point all bases will be available) 2482 // or we have to fail. 2483 if (!InUnqualifiedLookup && LookupRec->isDependentContext() && 2484 LookupRec->hasAnyDependentBases()) { 2485 R.setNotFoundInCurrentInstantiation(); 2486 return false; 2487 } 2488 2489 // Perform lookup into our base classes. 2490 2491 DeclarationName Name = R.getLookupName(); 2492 unsigned IDNS = R.getIdentifierNamespace(); 2493 2494 // Look for this member in our base classes. 2495 auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier, 2496 CXXBasePath &Path) -> bool { 2497 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 2498 // Drop leading non-matching lookup results from the declaration list so 2499 // we don't need to consider them again below. 2500 for (Path.Decls = BaseRecord->lookup(Name).begin(); 2501 Path.Decls != Path.Decls.end(); ++Path.Decls) { 2502 if ((*Path.Decls)->isInIdentifierNamespace(IDNS)) 2503 return true; 2504 } 2505 return false; 2506 }; 2507 2508 CXXBasePaths Paths; 2509 Paths.setOrigin(LookupRec); 2510 if (!LookupRec->lookupInBases(BaseCallback, Paths)) 2511 return false; 2512 2513 R.setNamingClass(LookupRec); 2514 2515 // C++ [class.member.lookup]p2: 2516 // [...] If the resulting set of declarations are not all from 2517 // sub-objects of the same type, or the set has a nonstatic member 2518 // and includes members from distinct sub-objects, there is an 2519 // ambiguity and the program is ill-formed. Otherwise that set is 2520 // the result of the lookup. 2521 QualType SubobjectType; 2522 int SubobjectNumber = 0; 2523 AccessSpecifier SubobjectAccess = AS_none; 2524 2525 // Check whether the given lookup result contains only static members. 2526 auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) { 2527 for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I) 2528 if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember()) 2529 return false; 2530 return true; 2531 }; 2532 2533 bool TemplateNameLookup = R.isTemplateNameLookup(); 2534 2535 // Determine whether two sets of members contain the same members, as 2536 // required by C++ [class.member.lookup]p6. 2537 auto HasSameDeclarations = [&](DeclContext::lookup_iterator A, 2538 DeclContext::lookup_iterator B) { 2539 using Iterator = DeclContextLookupResult::iterator; 2540 using Result = const void *; 2541 2542 auto Next = [&](Iterator &It, Iterator End) -> Result { 2543 while (It != End) { 2544 NamedDecl *ND = *It++; 2545 if (!ND->isInIdentifierNamespace(IDNS)) 2546 continue; 2547 2548 // C++ [temp.local]p3: 2549 // A lookup that finds an injected-class-name (10.2) can result in 2550 // an ambiguity in certain cases (for example, if it is found in 2551 // more than one base class). If all of the injected-class-names 2552 // that are found refer to specializations of the same class 2553 // template, and if the name is used as a template-name, the 2554 // reference refers to the class template itself and not a 2555 // specialization thereof, and is not ambiguous. 2556 if (TemplateNameLookup) 2557 if (auto *TD = getAsTemplateNameDecl(ND)) 2558 ND = TD; 2559 2560 // C++ [class.member.lookup]p3: 2561 // type declarations (including injected-class-names) are replaced by 2562 // the types they designate 2563 if (const TypeDecl *TD = dyn_cast<TypeDecl>(ND->getUnderlyingDecl())) { 2564 QualType T = Context.getTypeDeclType(TD); 2565 return T.getCanonicalType().getAsOpaquePtr(); 2566 } 2567 2568 return ND->getUnderlyingDecl()->getCanonicalDecl(); 2569 } 2570 return nullptr; 2571 }; 2572 2573 // We'll often find the declarations are in the same order. Handle this 2574 // case (and the special case of only one declaration) efficiently. 2575 Iterator AIt = A, BIt = B, AEnd, BEnd; 2576 while (true) { 2577 Result AResult = Next(AIt, AEnd); 2578 Result BResult = Next(BIt, BEnd); 2579 if (!AResult && !BResult) 2580 return true; 2581 if (!AResult || !BResult) 2582 return false; 2583 if (AResult != BResult) { 2584 // Found a mismatch; carefully check both lists, accounting for the 2585 // possibility of declarations appearing more than once. 2586 llvm::SmallDenseMap<Result, bool, 32> AResults; 2587 for (; AResult; AResult = Next(AIt, AEnd)) 2588 AResults.insert({AResult, /*FoundInB*/false}); 2589 unsigned Found = 0; 2590 for (; BResult; BResult = Next(BIt, BEnd)) { 2591 auto It = AResults.find(BResult); 2592 if (It == AResults.end()) 2593 return false; 2594 if (!It->second) { 2595 It->second = true; 2596 ++Found; 2597 } 2598 } 2599 return AResults.size() == Found; 2600 } 2601 } 2602 }; 2603 2604 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end(); 2605 Path != PathEnd; ++Path) { 2606 const CXXBasePathElement &PathElement = Path->back(); 2607 2608 // Pick the best (i.e. most permissive i.e. numerically lowest) access 2609 // across all paths. 2610 SubobjectAccess = std::min(SubobjectAccess, Path->Access); 2611 2612 // Determine whether we're looking at a distinct sub-object or not. 2613 if (SubobjectType.isNull()) { 2614 // This is the first subobject we've looked at. Record its type. 2615 SubobjectType = Context.getCanonicalType(PathElement.Base->getType()); 2616 SubobjectNumber = PathElement.SubobjectNumber; 2617 continue; 2618 } 2619 2620 if (SubobjectType != 2621 Context.getCanonicalType(PathElement.Base->getType())) { 2622 // We found members of the given name in two subobjects of 2623 // different types. If the declaration sets aren't the same, this 2624 // lookup is ambiguous. 2625 // 2626 // FIXME: The language rule says that this applies irrespective of 2627 // whether the sets contain only static members. 2628 if (HasOnlyStaticMembers(Path->Decls) && 2629 HasSameDeclarations(Paths.begin()->Decls, Path->Decls)) 2630 continue; 2631 2632 R.setAmbiguousBaseSubobjectTypes(Paths); 2633 return true; 2634 } 2635 2636 // FIXME: This language rule no longer exists. Checking for ambiguous base 2637 // subobjects should be done as part of formation of a class member access 2638 // expression (when converting the object parameter to the member's type). 2639 if (SubobjectNumber != PathElement.SubobjectNumber) { 2640 // We have a different subobject of the same type. 2641 2642 // C++ [class.member.lookup]p5: 2643 // A static member, a nested type or an enumerator defined in 2644 // a base class T can unambiguously be found even if an object 2645 // has more than one base class subobject of type T. 2646 if (HasOnlyStaticMembers(Path->Decls)) 2647 continue; 2648 2649 // We have found a nonstatic member name in multiple, distinct 2650 // subobjects. Name lookup is ambiguous. 2651 R.setAmbiguousBaseSubobjects(Paths); 2652 return true; 2653 } 2654 } 2655 2656 // Lookup in a base class succeeded; return these results. 2657 2658 for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end(); 2659 I != E; ++I) { 2660 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess, 2661 (*I)->getAccess()); 2662 if (NamedDecl *ND = R.getAcceptableDecl(*I)) 2663 R.addDecl(ND, AS); 2664 } 2665 R.resolveKind(); 2666 return true; 2667 } 2668 2669 /// Performs qualified name lookup or special type of lookup for 2670 /// "__super::" scope specifier. 2671 /// 2672 /// This routine is a convenience overload meant to be called from contexts 2673 /// that need to perform a qualified name lookup with an optional C++ scope 2674 /// specifier that might require special kind of lookup. 2675 /// 2676 /// \param R captures both the lookup criteria and any lookup results found. 2677 /// 2678 /// \param LookupCtx The context in which qualified name lookup will 2679 /// search. 2680 /// 2681 /// \param SS An optional C++ scope-specifier. 2682 /// 2683 /// \returns true if lookup succeeded, false if it failed. 2684 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 2685 CXXScopeSpec &SS) { 2686 auto *NNS = SS.getScopeRep(); 2687 if (NNS && NNS->getKind() == NestedNameSpecifier::Super) 2688 return LookupInSuper(R, NNS->getAsRecordDecl()); 2689 else 2690 2691 return LookupQualifiedName(R, LookupCtx); 2692 } 2693 2694 /// Performs name lookup for a name that was parsed in the 2695 /// source code, and may contain a C++ scope specifier. 2696 /// 2697 /// This routine is a convenience routine meant to be called from 2698 /// contexts that receive a name and an optional C++ scope specifier 2699 /// (e.g., "N::M::x"). It will then perform either qualified or 2700 /// unqualified name lookup (with LookupQualifiedName or LookupName, 2701 /// respectively) on the given name and return those results. It will 2702 /// perform a special type of lookup for "__super::" scope specifier. 2703 /// 2704 /// @param S The scope from which unqualified name lookup will 2705 /// begin. 2706 /// 2707 /// @param SS An optional C++ scope-specifier, e.g., "::N::M". 2708 /// 2709 /// @param EnteringContext Indicates whether we are going to enter the 2710 /// context of the scope-specifier SS (if present). 2711 /// 2712 /// @returns True if any decls were found (but possibly ambiguous) 2713 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 2714 bool AllowBuiltinCreation, bool EnteringContext) { 2715 if (SS && SS->isInvalid()) { 2716 // When the scope specifier is invalid, don't even look for 2717 // anything. 2718 return false; 2719 } 2720 2721 if (SS && SS->isSet()) { 2722 NestedNameSpecifier *NNS = SS->getScopeRep(); 2723 if (NNS->getKind() == NestedNameSpecifier::Super) 2724 return LookupInSuper(R, NNS->getAsRecordDecl()); 2725 2726 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) { 2727 // We have resolved the scope specifier to a particular declaration 2728 // contex, and will perform name lookup in that context. 2729 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC)) 2730 return false; 2731 2732 R.setContextRange(SS->getRange()); 2733 return LookupQualifiedName(R, DC); 2734 } 2735 2736 // We could not resolve the scope specified to a specific declaration 2737 // context, which means that SS refers to an unknown specialization. 2738 // Name lookup can't find anything in this case. 2739 R.setNotFoundInCurrentInstantiation(); 2740 R.setContextRange(SS->getRange()); 2741 return false; 2742 } 2743 2744 // Perform unqualified name lookup starting in the given scope. 2745 return LookupName(R, S, AllowBuiltinCreation); 2746 } 2747 2748 /// Perform qualified name lookup into all base classes of the given 2749 /// class. 2750 /// 2751 /// \param R captures both the lookup criteria and any lookup results found. 2752 /// 2753 /// \param Class The context in which qualified name lookup will 2754 /// search. Name lookup will search in all base classes merging the results. 2755 /// 2756 /// @returns True if any decls were found (but possibly ambiguous) 2757 bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) { 2758 // The access-control rules we use here are essentially the rules for 2759 // doing a lookup in Class that just magically skipped the direct 2760 // members of Class itself. That is, the naming class is Class, and the 2761 // access includes the access of the base. 2762 for (const auto &BaseSpec : Class->bases()) { 2763 CXXRecordDecl *RD = cast<CXXRecordDecl>( 2764 BaseSpec.getType()->castAs<RecordType>()->getDecl()); 2765 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind()); 2766 Result.setBaseObjectType(Context.getRecordType(Class)); 2767 LookupQualifiedName(Result, RD); 2768 2769 // Copy the lookup results into the target, merging the base's access into 2770 // the path access. 2771 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) { 2772 R.addDecl(I.getDecl(), 2773 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(), 2774 I.getAccess())); 2775 } 2776 2777 Result.suppressDiagnostics(); 2778 } 2779 2780 R.resolveKind(); 2781 R.setNamingClass(Class); 2782 2783 return !R.empty(); 2784 } 2785 2786 /// Produce a diagnostic describing the ambiguity that resulted 2787 /// from name lookup. 2788 /// 2789 /// \param Result The result of the ambiguous lookup to be diagnosed. 2790 void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) { 2791 assert(Result.isAmbiguous() && "Lookup result must be ambiguous"); 2792 2793 DeclarationName Name = Result.getLookupName(); 2794 SourceLocation NameLoc = Result.getNameLoc(); 2795 SourceRange LookupRange = Result.getContextRange(); 2796 2797 switch (Result.getAmbiguityKind()) { 2798 case LookupResult::AmbiguousBaseSubobjects: { 2799 CXXBasePaths *Paths = Result.getBasePaths(); 2800 QualType SubobjectType = Paths->front().back().Base->getType(); 2801 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects) 2802 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths) 2803 << LookupRange; 2804 2805 DeclContext::lookup_iterator Found = Paths->front().Decls; 2806 while (isa<CXXMethodDecl>(*Found) && 2807 cast<CXXMethodDecl>(*Found)->isStatic()) 2808 ++Found; 2809 2810 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found); 2811 break; 2812 } 2813 2814 case LookupResult::AmbiguousBaseSubobjectTypes: { 2815 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types) 2816 << Name << LookupRange; 2817 2818 CXXBasePaths *Paths = Result.getBasePaths(); 2819 std::set<const NamedDecl *> DeclsPrinted; 2820 for (CXXBasePaths::paths_iterator Path = Paths->begin(), 2821 PathEnd = Paths->end(); 2822 Path != PathEnd; ++Path) { 2823 const NamedDecl *D = *Path->Decls; 2824 if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace())) 2825 continue; 2826 if (DeclsPrinted.insert(D).second) { 2827 if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl())) 2828 Diag(D->getLocation(), diag::note_ambiguous_member_type_found) 2829 << TD->getUnderlyingType(); 2830 else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl())) 2831 Diag(D->getLocation(), diag::note_ambiguous_member_type_found) 2832 << Context.getTypeDeclType(TD); 2833 else 2834 Diag(D->getLocation(), diag::note_ambiguous_member_found); 2835 } 2836 } 2837 break; 2838 } 2839 2840 case LookupResult::AmbiguousTagHiding: { 2841 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange; 2842 2843 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls; 2844 2845 for (auto *D : Result) 2846 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 2847 TagDecls.insert(TD); 2848 Diag(TD->getLocation(), diag::note_hidden_tag); 2849 } 2850 2851 for (auto *D : Result) 2852 if (!isa<TagDecl>(D)) 2853 Diag(D->getLocation(), diag::note_hiding_object); 2854 2855 // For recovery purposes, go ahead and implement the hiding. 2856 LookupResult::Filter F = Result.makeFilter(); 2857 while (F.hasNext()) { 2858 if (TagDecls.count(F.next())) 2859 F.erase(); 2860 } 2861 F.done(); 2862 break; 2863 } 2864 2865 case LookupResult::AmbiguousReference: { 2866 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange; 2867 2868 for (auto *D : Result) 2869 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D; 2870 break; 2871 } 2872 } 2873 } 2874 2875 namespace { 2876 struct AssociatedLookup { 2877 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc, 2878 Sema::AssociatedNamespaceSet &Namespaces, 2879 Sema::AssociatedClassSet &Classes) 2880 : S(S), Namespaces(Namespaces), Classes(Classes), 2881 InstantiationLoc(InstantiationLoc) { 2882 } 2883 2884 bool addClassTransitive(CXXRecordDecl *RD) { 2885 Classes.insert(RD); 2886 return ClassesTransitive.insert(RD); 2887 } 2888 2889 Sema &S; 2890 Sema::AssociatedNamespaceSet &Namespaces; 2891 Sema::AssociatedClassSet &Classes; 2892 SourceLocation InstantiationLoc; 2893 2894 private: 2895 Sema::AssociatedClassSet ClassesTransitive; 2896 }; 2897 } // end anonymous namespace 2898 2899 static void 2900 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T); 2901 2902 // Given the declaration context \param Ctx of a class, class template or 2903 // enumeration, add the associated namespaces to \param Namespaces as described 2904 // in [basic.lookup.argdep]p2. 2905 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces, 2906 DeclContext *Ctx) { 2907 // The exact wording has been changed in C++14 as a result of 2908 // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally 2909 // to all language versions since it is possible to return a local type 2910 // from a lambda in C++11. 2911 // 2912 // C++14 [basic.lookup.argdep]p2: 2913 // If T is a class type [...]. Its associated namespaces are the innermost 2914 // enclosing namespaces of its associated classes. [...] 2915 // 2916 // If T is an enumeration type, its associated namespace is the innermost 2917 // enclosing namespace of its declaration. [...] 2918 2919 // We additionally skip inline namespaces. The innermost non-inline namespace 2920 // contains all names of all its nested inline namespaces anyway, so we can 2921 // replace the entire inline namespace tree with its root. 2922 while (!Ctx->isFileContext() || Ctx->isInlineNamespace()) 2923 Ctx = Ctx->getParent(); 2924 2925 Namespaces.insert(Ctx->getPrimaryContext()); 2926 } 2927 2928 // Add the associated classes and namespaces for argument-dependent 2929 // lookup that involves a template argument (C++ [basic.lookup.argdep]p2). 2930 static void 2931 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 2932 const TemplateArgument &Arg) { 2933 // C++ [basic.lookup.argdep]p2, last bullet: 2934 // -- [...] ; 2935 switch (Arg.getKind()) { 2936 case TemplateArgument::Null: 2937 break; 2938 2939 case TemplateArgument::Type: 2940 // [...] the namespaces and classes associated with the types of the 2941 // template arguments provided for template type parameters (excluding 2942 // template template parameters) 2943 addAssociatedClassesAndNamespaces(Result, Arg.getAsType()); 2944 break; 2945 2946 case TemplateArgument::Template: 2947 case TemplateArgument::TemplateExpansion: { 2948 // [...] the namespaces in which any template template arguments are 2949 // defined; and the classes in which any member templates used as 2950 // template template arguments are defined. 2951 TemplateName Template = Arg.getAsTemplateOrTemplatePattern(); 2952 if (ClassTemplateDecl *ClassTemplate 2953 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) { 2954 DeclContext *Ctx = ClassTemplate->getDeclContext(); 2955 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 2956 Result.Classes.insert(EnclosingClass); 2957 // Add the associated namespace for this class. 2958 CollectEnclosingNamespace(Result.Namespaces, Ctx); 2959 } 2960 break; 2961 } 2962 2963 case TemplateArgument::Declaration: 2964 case TemplateArgument::Integral: 2965 case TemplateArgument::Expression: 2966 case TemplateArgument::NullPtr: 2967 // [Note: non-type template arguments do not contribute to the set of 2968 // associated namespaces. ] 2969 break; 2970 2971 case TemplateArgument::Pack: 2972 for (const auto &P : Arg.pack_elements()) 2973 addAssociatedClassesAndNamespaces(Result, P); 2974 break; 2975 } 2976 } 2977 2978 // Add the associated classes and namespaces for argument-dependent lookup 2979 // with an argument of class type (C++ [basic.lookup.argdep]p2). 2980 static void 2981 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 2982 CXXRecordDecl *Class) { 2983 2984 // Just silently ignore anything whose name is __va_list_tag. 2985 if (Class->getDeclName() == Result.S.VAListTagName) 2986 return; 2987 2988 // C++ [basic.lookup.argdep]p2: 2989 // [...] 2990 // -- If T is a class type (including unions), its associated 2991 // classes are: the class itself; the class of which it is a 2992 // member, if any; and its direct and indirect base classes. 2993 // Its associated namespaces are the innermost enclosing 2994 // namespaces of its associated classes. 2995 2996 // Add the class of which it is a member, if any. 2997 DeclContext *Ctx = Class->getDeclContext(); 2998 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 2999 Result.Classes.insert(EnclosingClass); 3000 3001 // Add the associated namespace for this class. 3002 CollectEnclosingNamespace(Result.Namespaces, Ctx); 3003 3004 // -- If T is a template-id, its associated namespaces and classes are 3005 // the namespace in which the template is defined; for member 3006 // templates, the member template's class; the namespaces and classes 3007 // associated with the types of the template arguments provided for 3008 // template type parameters (excluding template template parameters); the 3009 // namespaces in which any template template arguments are defined; and 3010 // the classes in which any member templates used as template template 3011 // arguments are defined. [Note: non-type template arguments do not 3012 // contribute to the set of associated namespaces. ] 3013 if (ClassTemplateSpecializationDecl *Spec 3014 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) { 3015 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext(); 3016 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 3017 Result.Classes.insert(EnclosingClass); 3018 // Add the associated namespace for this class. 3019 CollectEnclosingNamespace(Result.Namespaces, Ctx); 3020 3021 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 3022 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 3023 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]); 3024 } 3025 3026 // Add the class itself. If we've already transitively visited this class, 3027 // we don't need to visit base classes. 3028 if (!Result.addClassTransitive(Class)) 3029 return; 3030 3031 // Only recurse into base classes for complete types. 3032 if (!Result.S.isCompleteType(Result.InstantiationLoc, 3033 Result.S.Context.getRecordType(Class))) 3034 return; 3035 3036 // Add direct and indirect base classes along with their associated 3037 // namespaces. 3038 SmallVector<CXXRecordDecl *, 32> Bases; 3039 Bases.push_back(Class); 3040 while (!Bases.empty()) { 3041 // Pop this class off the stack. 3042 Class = Bases.pop_back_val(); 3043 3044 // Visit the base classes. 3045 for (const auto &Base : Class->bases()) { 3046 const RecordType *BaseType = Base.getType()->getAs<RecordType>(); 3047 // In dependent contexts, we do ADL twice, and the first time around, 3048 // the base type might be a dependent TemplateSpecializationType, or a 3049 // TemplateTypeParmType. If that happens, simply ignore it. 3050 // FIXME: If we want to support export, we probably need to add the 3051 // namespace of the template in a TemplateSpecializationType, or even 3052 // the classes and namespaces of known non-dependent arguments. 3053 if (!BaseType) 3054 continue; 3055 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 3056 if (Result.addClassTransitive(BaseDecl)) { 3057 // Find the associated namespace for this base class. 3058 DeclContext *BaseCtx = BaseDecl->getDeclContext(); 3059 CollectEnclosingNamespace(Result.Namespaces, BaseCtx); 3060 3061 // Make sure we visit the bases of this base class. 3062 if (BaseDecl->bases_begin() != BaseDecl->bases_end()) 3063 Bases.push_back(BaseDecl); 3064 } 3065 } 3066 } 3067 } 3068 3069 // Add the associated classes and namespaces for 3070 // argument-dependent lookup with an argument of type T 3071 // (C++ [basic.lookup.koenig]p2). 3072 static void 3073 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) { 3074 // C++ [basic.lookup.koenig]p2: 3075 // 3076 // For each argument type T in the function call, there is a set 3077 // of zero or more associated namespaces and a set of zero or more 3078 // associated classes to be considered. The sets of namespaces and 3079 // classes is determined entirely by the types of the function 3080 // arguments (and the namespace of any template template 3081 // argument). Typedef names and using-declarations used to specify 3082 // the types do not contribute to this set. The sets of namespaces 3083 // and classes are determined in the following way: 3084 3085 SmallVector<const Type *, 16> Queue; 3086 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr(); 3087 3088 while (true) { 3089 switch (T->getTypeClass()) { 3090 3091 #define TYPE(Class, Base) 3092 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3093 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 3094 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 3095 #define ABSTRACT_TYPE(Class, Base) 3096 #include "clang/AST/TypeNodes.inc" 3097 // T is canonical. We can also ignore dependent types because 3098 // we don't need to do ADL at the definition point, but if we 3099 // wanted to implement template export (or if we find some other 3100 // use for associated classes and namespaces...) this would be 3101 // wrong. 3102 break; 3103 3104 // -- If T is a pointer to U or an array of U, its associated 3105 // namespaces and classes are those associated with U. 3106 case Type::Pointer: 3107 T = cast<PointerType>(T)->getPointeeType().getTypePtr(); 3108 continue; 3109 case Type::ConstantArray: 3110 case Type::IncompleteArray: 3111 case Type::VariableArray: 3112 T = cast<ArrayType>(T)->getElementType().getTypePtr(); 3113 continue; 3114 3115 // -- If T is a fundamental type, its associated sets of 3116 // namespaces and classes are both empty. 3117 case Type::Builtin: 3118 break; 3119 3120 // -- If T is a class type (including unions), its associated 3121 // classes are: the class itself; the class of which it is 3122 // a member, if any; and its direct and indirect base classes. 3123 // Its associated namespaces are the innermost enclosing 3124 // namespaces of its associated classes. 3125 case Type::Record: { 3126 CXXRecordDecl *Class = 3127 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl()); 3128 addAssociatedClassesAndNamespaces(Result, Class); 3129 break; 3130 } 3131 3132 // -- If T is an enumeration type, its associated namespace 3133 // is the innermost enclosing namespace of its declaration. 3134 // If it is a class member, its associated class is the 3135 // member’s class; else it has no associated class. 3136 case Type::Enum: { 3137 EnumDecl *Enum = cast<EnumType>(T)->getDecl(); 3138 3139 DeclContext *Ctx = Enum->getDeclContext(); 3140 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 3141 Result.Classes.insert(EnclosingClass); 3142 3143 // Add the associated namespace for this enumeration. 3144 CollectEnclosingNamespace(Result.Namespaces, Ctx); 3145 3146 break; 3147 } 3148 3149 // -- If T is a function type, its associated namespaces and 3150 // classes are those associated with the function parameter 3151 // types and those associated with the return type. 3152 case Type::FunctionProto: { 3153 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 3154 for (const auto &Arg : Proto->param_types()) 3155 Queue.push_back(Arg.getTypePtr()); 3156 // fallthrough 3157 [[fallthrough]]; 3158 } 3159 case Type::FunctionNoProto: { 3160 const FunctionType *FnType = cast<FunctionType>(T); 3161 T = FnType->getReturnType().getTypePtr(); 3162 continue; 3163 } 3164 3165 // -- If T is a pointer to a member function of a class X, its 3166 // associated namespaces and classes are those associated 3167 // with the function parameter types and return type, 3168 // together with those associated with X. 3169 // 3170 // -- If T is a pointer to a data member of class X, its 3171 // associated namespaces and classes are those associated 3172 // with the member type together with those associated with 3173 // X. 3174 case Type::MemberPointer: { 3175 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T); 3176 3177 // Queue up the class type into which this points. 3178 Queue.push_back(MemberPtr->getClass()); 3179 3180 // And directly continue with the pointee type. 3181 T = MemberPtr->getPointeeType().getTypePtr(); 3182 continue; 3183 } 3184 3185 // As an extension, treat this like a normal pointer. 3186 case Type::BlockPointer: 3187 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr(); 3188 continue; 3189 3190 // References aren't covered by the standard, but that's such an 3191 // obvious defect that we cover them anyway. 3192 case Type::LValueReference: 3193 case Type::RValueReference: 3194 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr(); 3195 continue; 3196 3197 // These are fundamental types. 3198 case Type::Vector: 3199 case Type::ExtVector: 3200 case Type::ConstantMatrix: 3201 case Type::Complex: 3202 case Type::BitInt: 3203 break; 3204 3205 // Non-deduced auto types only get here for error cases. 3206 case Type::Auto: 3207 case Type::DeducedTemplateSpecialization: 3208 break; 3209 3210 // If T is an Objective-C object or interface type, or a pointer to an 3211 // object or interface type, the associated namespace is the global 3212 // namespace. 3213 case Type::ObjCObject: 3214 case Type::ObjCInterface: 3215 case Type::ObjCObjectPointer: 3216 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl()); 3217 break; 3218 3219 // Atomic types are just wrappers; use the associations of the 3220 // contained type. 3221 case Type::Atomic: 3222 T = cast<AtomicType>(T)->getValueType().getTypePtr(); 3223 continue; 3224 case Type::Pipe: 3225 T = cast<PipeType>(T)->getElementType().getTypePtr(); 3226 continue; 3227 } 3228 3229 if (Queue.empty()) 3230 break; 3231 T = Queue.pop_back_val(); 3232 } 3233 } 3234 3235 /// Find the associated classes and namespaces for 3236 /// argument-dependent lookup for a call with the given set of 3237 /// arguments. 3238 /// 3239 /// This routine computes the sets of associated classes and associated 3240 /// namespaces searched by argument-dependent lookup 3241 /// (C++ [basic.lookup.argdep]) for a given set of arguments. 3242 void Sema::FindAssociatedClassesAndNamespaces( 3243 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, 3244 AssociatedNamespaceSet &AssociatedNamespaces, 3245 AssociatedClassSet &AssociatedClasses) { 3246 AssociatedNamespaces.clear(); 3247 AssociatedClasses.clear(); 3248 3249 AssociatedLookup Result(*this, InstantiationLoc, 3250 AssociatedNamespaces, AssociatedClasses); 3251 3252 // C++ [basic.lookup.koenig]p2: 3253 // For each argument type T in the function call, there is a set 3254 // of zero or more associated namespaces and a set of zero or more 3255 // associated classes to be considered. The sets of namespaces and 3256 // classes is determined entirely by the types of the function 3257 // arguments (and the namespace of any template template 3258 // argument). 3259 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 3260 Expr *Arg = Args[ArgIdx]; 3261 3262 if (Arg->getType() != Context.OverloadTy) { 3263 addAssociatedClassesAndNamespaces(Result, Arg->getType()); 3264 continue; 3265 } 3266 3267 // [...] In addition, if the argument is the name or address of a 3268 // set of overloaded functions and/or function templates, its 3269 // associated classes and namespaces are the union of those 3270 // associated with each of the members of the set: the namespace 3271 // in which the function or function template is defined and the 3272 // classes and namespaces associated with its (non-dependent) 3273 // parameter types and return type. 3274 OverloadExpr *OE = OverloadExpr::find(Arg).Expression; 3275 3276 for (const NamedDecl *D : OE->decls()) { 3277 // Look through any using declarations to find the underlying function. 3278 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction(); 3279 3280 // Add the classes and namespaces associated with the parameter 3281 // types and return type of this function. 3282 addAssociatedClassesAndNamespaces(Result, FDecl->getType()); 3283 } 3284 } 3285 } 3286 3287 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name, 3288 SourceLocation Loc, 3289 LookupNameKind NameKind, 3290 RedeclarationKind Redecl) { 3291 LookupResult R(*this, Name, Loc, NameKind, Redecl); 3292 LookupName(R, S); 3293 return R.getAsSingle<NamedDecl>(); 3294 } 3295 3296 /// Find the protocol with the given name, if any. 3297 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II, 3298 SourceLocation IdLoc, 3299 RedeclarationKind Redecl) { 3300 Decl *D = LookupSingleName(TUScope, II, IdLoc, 3301 LookupObjCProtocolName, Redecl); 3302 return cast_or_null<ObjCProtocolDecl>(D); 3303 } 3304 3305 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 3306 UnresolvedSetImpl &Functions) { 3307 // C++ [over.match.oper]p3: 3308 // -- The set of non-member candidates is the result of the 3309 // unqualified lookup of operator@ in the context of the 3310 // expression according to the usual rules for name lookup in 3311 // unqualified function calls (3.4.2) except that all member 3312 // functions are ignored. 3313 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 3314 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName); 3315 LookupName(Operators, S); 3316 3317 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous"); 3318 Functions.append(Operators.begin(), Operators.end()); 3319 } 3320 3321 Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD, 3322 CXXSpecialMember SM, 3323 bool ConstArg, 3324 bool VolatileArg, 3325 bool RValueThis, 3326 bool ConstThis, 3327 bool VolatileThis) { 3328 assert(CanDeclareSpecialMemberFunction(RD) && 3329 "doing special member lookup into record that isn't fully complete"); 3330 RD = RD->getDefinition(); 3331 if (RValueThis || ConstThis || VolatileThis) 3332 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) && 3333 "constructors and destructors always have unqualified lvalue this"); 3334 if (ConstArg || VolatileArg) 3335 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) && 3336 "parameter-less special members can't have qualified arguments"); 3337 3338 // FIXME: Get the caller to pass in a location for the lookup. 3339 SourceLocation LookupLoc = RD->getLocation(); 3340 3341 llvm::FoldingSetNodeID ID; 3342 ID.AddPointer(RD); 3343 ID.AddInteger(SM); 3344 ID.AddInteger(ConstArg); 3345 ID.AddInteger(VolatileArg); 3346 ID.AddInteger(RValueThis); 3347 ID.AddInteger(ConstThis); 3348 ID.AddInteger(VolatileThis); 3349 3350 void *InsertPoint; 3351 SpecialMemberOverloadResultEntry *Result = 3352 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint); 3353 3354 // This was already cached 3355 if (Result) 3356 return *Result; 3357 3358 Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>(); 3359 Result = new (Result) SpecialMemberOverloadResultEntry(ID); 3360 SpecialMemberCache.InsertNode(Result, InsertPoint); 3361 3362 if (SM == CXXDestructor) { 3363 if (RD->needsImplicitDestructor()) { 3364 runWithSufficientStackSpace(RD->getLocation(), [&] { 3365 DeclareImplicitDestructor(RD); 3366 }); 3367 } 3368 CXXDestructorDecl *DD = RD->getDestructor(); 3369 Result->setMethod(DD); 3370 Result->setKind(DD && !DD->isDeleted() 3371 ? SpecialMemberOverloadResult::Success 3372 : SpecialMemberOverloadResult::NoMemberOrDeleted); 3373 return *Result; 3374 } 3375 3376 // Prepare for overload resolution. Here we construct a synthetic argument 3377 // if necessary and make sure that implicit functions are declared. 3378 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD)); 3379 DeclarationName Name; 3380 Expr *Arg = nullptr; 3381 unsigned NumArgs; 3382 3383 QualType ArgType = CanTy; 3384 ExprValueKind VK = VK_LValue; 3385 3386 if (SM == CXXDefaultConstructor) { 3387 Name = Context.DeclarationNames.getCXXConstructorName(CanTy); 3388 NumArgs = 0; 3389 if (RD->needsImplicitDefaultConstructor()) { 3390 runWithSufficientStackSpace(RD->getLocation(), [&] { 3391 DeclareImplicitDefaultConstructor(RD); 3392 }); 3393 } 3394 } else { 3395 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) { 3396 Name = Context.DeclarationNames.getCXXConstructorName(CanTy); 3397 if (RD->needsImplicitCopyConstructor()) { 3398 runWithSufficientStackSpace(RD->getLocation(), [&] { 3399 DeclareImplicitCopyConstructor(RD); 3400 }); 3401 } 3402 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) { 3403 runWithSufficientStackSpace(RD->getLocation(), [&] { 3404 DeclareImplicitMoveConstructor(RD); 3405 }); 3406 } 3407 } else { 3408 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 3409 if (RD->needsImplicitCopyAssignment()) { 3410 runWithSufficientStackSpace(RD->getLocation(), [&] { 3411 DeclareImplicitCopyAssignment(RD); 3412 }); 3413 } 3414 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) { 3415 runWithSufficientStackSpace(RD->getLocation(), [&] { 3416 DeclareImplicitMoveAssignment(RD); 3417 }); 3418 } 3419 } 3420 3421 if (ConstArg) 3422 ArgType.addConst(); 3423 if (VolatileArg) 3424 ArgType.addVolatile(); 3425 3426 // This isn't /really/ specified by the standard, but it's implied 3427 // we should be working from a PRValue in the case of move to ensure 3428 // that we prefer to bind to rvalue references, and an LValue in the 3429 // case of copy to ensure we don't bind to rvalue references. 3430 // Possibly an XValue is actually correct in the case of move, but 3431 // there is no semantic difference for class types in this restricted 3432 // case. 3433 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment) 3434 VK = VK_LValue; 3435 else 3436 VK = VK_PRValue; 3437 } 3438 3439 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK); 3440 3441 if (SM != CXXDefaultConstructor) { 3442 NumArgs = 1; 3443 Arg = &FakeArg; 3444 } 3445 3446 // Create the object argument 3447 QualType ThisTy = CanTy; 3448 if (ConstThis) 3449 ThisTy.addConst(); 3450 if (VolatileThis) 3451 ThisTy.addVolatile(); 3452 Expr::Classification Classification = 3453 OpaqueValueExpr(LookupLoc, ThisTy, RValueThis ? VK_PRValue : VK_LValue) 3454 .Classify(Context); 3455 3456 // Now we perform lookup on the name we computed earlier and do overload 3457 // resolution. Lookup is only performed directly into the class since there 3458 // will always be a (possibly implicit) declaration to shadow any others. 3459 OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal); 3460 DeclContext::lookup_result R = RD->lookup(Name); 3461 3462 if (R.empty()) { 3463 // We might have no default constructor because we have a lambda's closure 3464 // type, rather than because there's some other declared constructor. 3465 // Every class has a copy/move constructor, copy/move assignment, and 3466 // destructor. 3467 assert(SM == CXXDefaultConstructor && 3468 "lookup for a constructor or assignment operator was empty"); 3469 Result->setMethod(nullptr); 3470 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); 3471 return *Result; 3472 } 3473 3474 // Copy the candidates as our processing of them may load new declarations 3475 // from an external source and invalidate lookup_result. 3476 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end()); 3477 3478 for (NamedDecl *CandDecl : Candidates) { 3479 if (CandDecl->isInvalidDecl()) 3480 continue; 3481 3482 DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public); 3483 auto CtorInfo = getConstructorInfo(Cand); 3484 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) { 3485 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment) 3486 AddMethodCandidate(M, Cand, RD, ThisTy, Classification, 3487 llvm::ArrayRef(&Arg, NumArgs), OCS, true); 3488 else if (CtorInfo) 3489 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl, 3490 llvm::ArrayRef(&Arg, NumArgs), OCS, 3491 /*SuppressUserConversions*/ true); 3492 else 3493 AddOverloadCandidate(M, Cand, llvm::ArrayRef(&Arg, NumArgs), OCS, 3494 /*SuppressUserConversions*/ true); 3495 } else if (FunctionTemplateDecl *Tmpl = 3496 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) { 3497 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment) 3498 AddMethodTemplateCandidate(Tmpl, Cand, RD, nullptr, ThisTy, 3499 Classification, 3500 llvm::ArrayRef(&Arg, NumArgs), OCS, true); 3501 else if (CtorInfo) 3502 AddTemplateOverloadCandidate(CtorInfo.ConstructorTmpl, 3503 CtorInfo.FoundDecl, nullptr, 3504 llvm::ArrayRef(&Arg, NumArgs), OCS, true); 3505 else 3506 AddTemplateOverloadCandidate(Tmpl, Cand, nullptr, 3507 llvm::ArrayRef(&Arg, NumArgs), OCS, true); 3508 } else { 3509 assert(isa<UsingDecl>(Cand.getDecl()) && 3510 "illegal Kind of operator = Decl"); 3511 } 3512 } 3513 3514 OverloadCandidateSet::iterator Best; 3515 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) { 3516 case OR_Success: 3517 Result->setMethod(cast<CXXMethodDecl>(Best->Function)); 3518 Result->setKind(SpecialMemberOverloadResult::Success); 3519 break; 3520 3521 case OR_Deleted: 3522 Result->setMethod(cast<CXXMethodDecl>(Best->Function)); 3523 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); 3524 break; 3525 3526 case OR_Ambiguous: 3527 Result->setMethod(nullptr); 3528 Result->setKind(SpecialMemberOverloadResult::Ambiguous); 3529 break; 3530 3531 case OR_No_Viable_Function: 3532 Result->setMethod(nullptr); 3533 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); 3534 break; 3535 } 3536 3537 return *Result; 3538 } 3539 3540 /// Look up the default constructor for the given class. 3541 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) { 3542 SpecialMemberOverloadResult Result = 3543 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false, 3544 false, false); 3545 3546 return cast_or_null<CXXConstructorDecl>(Result.getMethod()); 3547 } 3548 3549 /// Look up the copying constructor for the given class. 3550 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class, 3551 unsigned Quals) { 3552 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 3553 "non-const, non-volatile qualifiers for copy ctor arg"); 3554 SpecialMemberOverloadResult Result = 3555 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const, 3556 Quals & Qualifiers::Volatile, false, false, false); 3557 3558 return cast_or_null<CXXConstructorDecl>(Result.getMethod()); 3559 } 3560 3561 /// Look up the moving constructor for the given class. 3562 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class, 3563 unsigned Quals) { 3564 SpecialMemberOverloadResult Result = 3565 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const, 3566 Quals & Qualifiers::Volatile, false, false, false); 3567 3568 return cast_or_null<CXXConstructorDecl>(Result.getMethod()); 3569 } 3570 3571 /// Look up the constructors for the given class. 3572 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) { 3573 // If the implicit constructors have not yet been declared, do so now. 3574 if (CanDeclareSpecialMemberFunction(Class)) { 3575 runWithSufficientStackSpace(Class->getLocation(), [&] { 3576 if (Class->needsImplicitDefaultConstructor()) 3577 DeclareImplicitDefaultConstructor(Class); 3578 if (Class->needsImplicitCopyConstructor()) 3579 DeclareImplicitCopyConstructor(Class); 3580 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor()) 3581 DeclareImplicitMoveConstructor(Class); 3582 }); 3583 } 3584 3585 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class)); 3586 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T); 3587 return Class->lookup(Name); 3588 } 3589 3590 /// Look up the copying assignment operator for the given class. 3591 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class, 3592 unsigned Quals, bool RValueThis, 3593 unsigned ThisQuals) { 3594 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 3595 "non-const, non-volatile qualifiers for copy assignment arg"); 3596 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 3597 "non-const, non-volatile qualifiers for copy assignment this"); 3598 SpecialMemberOverloadResult Result = 3599 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const, 3600 Quals & Qualifiers::Volatile, RValueThis, 3601 ThisQuals & Qualifiers::Const, 3602 ThisQuals & Qualifiers::Volatile); 3603 3604 return Result.getMethod(); 3605 } 3606 3607 /// Look up the moving assignment operator for the given class. 3608 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class, 3609 unsigned Quals, 3610 bool RValueThis, 3611 unsigned ThisQuals) { 3612 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 3613 "non-const, non-volatile qualifiers for copy assignment this"); 3614 SpecialMemberOverloadResult Result = 3615 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const, 3616 Quals & Qualifiers::Volatile, RValueThis, 3617 ThisQuals & Qualifiers::Const, 3618 ThisQuals & Qualifiers::Volatile); 3619 3620 return Result.getMethod(); 3621 } 3622 3623 /// Look for the destructor of the given class. 3624 /// 3625 /// During semantic analysis, this routine should be used in lieu of 3626 /// CXXRecordDecl::getDestructor(). 3627 /// 3628 /// \returns The destructor for this class. 3629 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) { 3630 return cast_or_null<CXXDestructorDecl>( 3631 LookupSpecialMember(Class, CXXDestructor, false, false, false, false, 3632 false) 3633 .getMethod()); 3634 } 3635 3636 /// LookupLiteralOperator - Determine which literal operator should be used for 3637 /// a user-defined literal, per C++11 [lex.ext]. 3638 /// 3639 /// Normal overload resolution is not used to select which literal operator to 3640 /// call for a user-defined literal. Look up the provided literal operator name, 3641 /// and filter the results to the appropriate set for the given argument types. 3642 Sema::LiteralOperatorLookupResult 3643 Sema::LookupLiteralOperator(Scope *S, LookupResult &R, 3644 ArrayRef<QualType> ArgTys, bool AllowRaw, 3645 bool AllowTemplate, bool AllowStringTemplatePack, 3646 bool DiagnoseMissing, StringLiteral *StringLit) { 3647 LookupName(R, S); 3648 assert(R.getResultKind() != LookupResult::Ambiguous && 3649 "literal operator lookup can't be ambiguous"); 3650 3651 // Filter the lookup results appropriately. 3652 LookupResult::Filter F = R.makeFilter(); 3653 3654 bool AllowCooked = true; 3655 bool FoundRaw = false; 3656 bool FoundTemplate = false; 3657 bool FoundStringTemplatePack = false; 3658 bool FoundCooked = false; 3659 3660 while (F.hasNext()) { 3661 Decl *D = F.next(); 3662 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) 3663 D = USD->getTargetDecl(); 3664 3665 // If the declaration we found is invalid, skip it. 3666 if (D->isInvalidDecl()) { 3667 F.erase(); 3668 continue; 3669 } 3670 3671 bool IsRaw = false; 3672 bool IsTemplate = false; 3673 bool IsStringTemplatePack = false; 3674 bool IsCooked = false; 3675 3676 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 3677 if (FD->getNumParams() == 1 && 3678 FD->getParamDecl(0)->getType()->getAs<PointerType>()) 3679 IsRaw = true; 3680 else if (FD->getNumParams() == ArgTys.size()) { 3681 IsCooked = true; 3682 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) { 3683 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType(); 3684 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) { 3685 IsCooked = false; 3686 break; 3687 } 3688 } 3689 } 3690 } 3691 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) { 3692 TemplateParameterList *Params = FD->getTemplateParameters(); 3693 if (Params->size() == 1) { 3694 IsTemplate = true; 3695 if (!Params->getParam(0)->isTemplateParameterPack() && !StringLit) { 3696 // Implied but not stated: user-defined integer and floating literals 3697 // only ever use numeric literal operator templates, not templates 3698 // taking a parameter of class type. 3699 F.erase(); 3700 continue; 3701 } 3702 3703 // A string literal template is only considered if the string literal 3704 // is a well-formed template argument for the template parameter. 3705 if (StringLit) { 3706 SFINAETrap Trap(*this); 3707 SmallVector<TemplateArgument, 1> SugaredChecked, CanonicalChecked; 3708 TemplateArgumentLoc Arg(TemplateArgument(StringLit), StringLit); 3709 if (CheckTemplateArgument( 3710 Params->getParam(0), Arg, FD, R.getNameLoc(), R.getNameLoc(), 3711 0, SugaredChecked, CanonicalChecked, CTAK_Specified) || 3712 Trap.hasErrorOccurred()) 3713 IsTemplate = false; 3714 } 3715 } else { 3716 IsStringTemplatePack = true; 3717 } 3718 } 3719 3720 if (AllowTemplate && StringLit && IsTemplate) { 3721 FoundTemplate = true; 3722 AllowRaw = false; 3723 AllowCooked = false; 3724 AllowStringTemplatePack = false; 3725 if (FoundRaw || FoundCooked || FoundStringTemplatePack) { 3726 F.restart(); 3727 FoundRaw = FoundCooked = FoundStringTemplatePack = false; 3728 } 3729 } else if (AllowCooked && IsCooked) { 3730 FoundCooked = true; 3731 AllowRaw = false; 3732 AllowTemplate = StringLit; 3733 AllowStringTemplatePack = false; 3734 if (FoundRaw || FoundTemplate || FoundStringTemplatePack) { 3735 // Go through again and remove the raw and template decls we've 3736 // already found. 3737 F.restart(); 3738 FoundRaw = FoundTemplate = FoundStringTemplatePack = false; 3739 } 3740 } else if (AllowRaw && IsRaw) { 3741 FoundRaw = true; 3742 } else if (AllowTemplate && IsTemplate) { 3743 FoundTemplate = true; 3744 } else if (AllowStringTemplatePack && IsStringTemplatePack) { 3745 FoundStringTemplatePack = true; 3746 } else { 3747 F.erase(); 3748 } 3749 } 3750 3751 F.done(); 3752 3753 // Per C++20 [lex.ext]p5, we prefer the template form over the non-template 3754 // form for string literal operator templates. 3755 if (StringLit && FoundTemplate) 3756 return LOLR_Template; 3757 3758 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching 3759 // parameter type, that is used in preference to a raw literal operator 3760 // or literal operator template. 3761 if (FoundCooked) 3762 return LOLR_Cooked; 3763 3764 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal 3765 // operator template, but not both. 3766 if (FoundRaw && FoundTemplate) { 3767 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 3768 for (const NamedDecl *D : R) 3769 NoteOverloadCandidate(D, D->getUnderlyingDecl()->getAsFunction()); 3770 return LOLR_Error; 3771 } 3772 3773 if (FoundRaw) 3774 return LOLR_Raw; 3775 3776 if (FoundTemplate) 3777 return LOLR_Template; 3778 3779 if (FoundStringTemplatePack) 3780 return LOLR_StringTemplatePack; 3781 3782 // Didn't find anything we could use. 3783 if (DiagnoseMissing) { 3784 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator) 3785 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0] 3786 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw 3787 << (AllowTemplate || AllowStringTemplatePack); 3788 return LOLR_Error; 3789 } 3790 3791 return LOLR_ErrorNoDiagnostic; 3792 } 3793 3794 void ADLResult::insert(NamedDecl *New) { 3795 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())]; 3796 3797 // If we haven't yet seen a decl for this key, or the last decl 3798 // was exactly this one, we're done. 3799 if (Old == nullptr || Old == New) { 3800 Old = New; 3801 return; 3802 } 3803 3804 // Otherwise, decide which is a more recent redeclaration. 3805 FunctionDecl *OldFD = Old->getAsFunction(); 3806 FunctionDecl *NewFD = New->getAsFunction(); 3807 3808 FunctionDecl *Cursor = NewFD; 3809 while (true) { 3810 Cursor = Cursor->getPreviousDecl(); 3811 3812 // If we got to the end without finding OldFD, OldFD is the newer 3813 // declaration; leave things as they are. 3814 if (!Cursor) return; 3815 3816 // If we do find OldFD, then NewFD is newer. 3817 if (Cursor == OldFD) break; 3818 3819 // Otherwise, keep looking. 3820 } 3821 3822 Old = New; 3823 } 3824 3825 void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, 3826 ArrayRef<Expr *> Args, ADLResult &Result) { 3827 // Find all of the associated namespaces and classes based on the 3828 // arguments we have. 3829 AssociatedNamespaceSet AssociatedNamespaces; 3830 AssociatedClassSet AssociatedClasses; 3831 FindAssociatedClassesAndNamespaces(Loc, Args, 3832 AssociatedNamespaces, 3833 AssociatedClasses); 3834 3835 // C++ [basic.lookup.argdep]p3: 3836 // Let X be the lookup set produced by unqualified lookup (3.4.1) 3837 // and let Y be the lookup set produced by argument dependent 3838 // lookup (defined as follows). If X contains [...] then Y is 3839 // empty. Otherwise Y is the set of declarations found in the 3840 // namespaces associated with the argument types as described 3841 // below. The set of declarations found by the lookup of the name 3842 // is the union of X and Y. 3843 // 3844 // Here, we compute Y and add its members to the overloaded 3845 // candidate set. 3846 for (auto *NS : AssociatedNamespaces) { 3847 // When considering an associated namespace, the lookup is the 3848 // same as the lookup performed when the associated namespace is 3849 // used as a qualifier (3.4.3.2) except that: 3850 // 3851 // -- Any using-directives in the associated namespace are 3852 // ignored. 3853 // 3854 // -- Any namespace-scope friend functions declared in 3855 // associated classes are visible within their respective 3856 // namespaces even if they are not visible during an ordinary 3857 // lookup (11.4). 3858 // 3859 // C++20 [basic.lookup.argdep] p4.3 3860 // -- are exported, are attached to a named module M, do not appear 3861 // in the translation unit containing the point of the lookup, and 3862 // have the same innermost enclosing non-inline namespace scope as 3863 // a declaration of an associated entity attached to M. 3864 DeclContext::lookup_result R = NS->lookup(Name); 3865 for (auto *D : R) { 3866 auto *Underlying = D; 3867 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 3868 Underlying = USD->getTargetDecl(); 3869 3870 if (!isa<FunctionDecl>(Underlying) && 3871 !isa<FunctionTemplateDecl>(Underlying)) 3872 continue; 3873 3874 // The declaration is visible to argument-dependent lookup if either 3875 // it's ordinarily visible or declared as a friend in an associated 3876 // class. 3877 bool Visible = false; 3878 for (D = D->getMostRecentDecl(); D; 3879 D = cast_or_null<NamedDecl>(D->getPreviousDecl())) { 3880 if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) { 3881 if (isVisible(D)) { 3882 Visible = true; 3883 break; 3884 } 3885 3886 if (!getLangOpts().CPlusPlusModules) 3887 continue; 3888 3889 if (D->isInExportDeclContext()) { 3890 Module *FM = D->getOwningModule(); 3891 // C++20 [basic.lookup.argdep] p4.3 .. are exported ... 3892 // exports are only valid in module purview and outside of any 3893 // PMF (although a PMF should not even be present in a module 3894 // with an import). 3895 assert(FM && FM->isModulePurview() && !FM->isPrivateModule() && 3896 "bad export context"); 3897 // .. are attached to a named module M, do not appear in the 3898 // translation unit containing the point of the lookup.. 3899 if (D->isInAnotherModuleUnit() && 3900 llvm::any_of(AssociatedClasses, [&](auto *E) { 3901 // ... and have the same innermost enclosing non-inline 3902 // namespace scope as a declaration of an associated entity 3903 // attached to M 3904 if (E->getOwningModule() != FM) 3905 return false; 3906 // TODO: maybe this could be cached when generating the 3907 // associated namespaces / entities. 3908 DeclContext *Ctx = E->getDeclContext(); 3909 while (!Ctx->isFileContext() || Ctx->isInlineNamespace()) 3910 Ctx = Ctx->getParent(); 3911 return Ctx == NS; 3912 })) { 3913 Visible = true; 3914 break; 3915 } 3916 } 3917 } else if (D->getFriendObjectKind()) { 3918 auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext()); 3919 // [basic.lookup.argdep]p4: 3920 // Argument-dependent lookup finds all declarations of functions and 3921 // function templates that 3922 // - ... 3923 // - are declared as a friend ([class.friend]) of any class with a 3924 // reachable definition in the set of associated entities, 3925 // 3926 // FIXME: If there's a merged definition of D that is reachable, then 3927 // the friend declaration should be considered. 3928 if (AssociatedClasses.count(RD) && isReachable(D)) { 3929 Visible = true; 3930 break; 3931 } 3932 } 3933 } 3934 3935 // FIXME: Preserve D as the FoundDecl. 3936 if (Visible) 3937 Result.insert(Underlying); 3938 } 3939 } 3940 } 3941 3942 //---------------------------------------------------------------------------- 3943 // Search for all visible declarations. 3944 //---------------------------------------------------------------------------- 3945 VisibleDeclConsumer::~VisibleDeclConsumer() { } 3946 3947 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; } 3948 3949 namespace { 3950 3951 class ShadowContextRAII; 3952 3953 class VisibleDeclsRecord { 3954 public: 3955 /// An entry in the shadow map, which is optimized to store a 3956 /// single declaration (the common case) but can also store a list 3957 /// of declarations. 3958 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry; 3959 3960 private: 3961 /// A mapping from declaration names to the declarations that have 3962 /// this name within a particular scope. 3963 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; 3964 3965 /// A list of shadow maps, which is used to model name hiding. 3966 std::list<ShadowMap> ShadowMaps; 3967 3968 /// The declaration contexts we have already visited. 3969 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts; 3970 3971 friend class ShadowContextRAII; 3972 3973 public: 3974 /// Determine whether we have already visited this context 3975 /// (and, if not, note that we are going to visit that context now). 3976 bool visitedContext(DeclContext *Ctx) { 3977 return !VisitedContexts.insert(Ctx).second; 3978 } 3979 3980 bool alreadyVisitedContext(DeclContext *Ctx) { 3981 return VisitedContexts.count(Ctx); 3982 } 3983 3984 /// Determine whether the given declaration is hidden in the 3985 /// current scope. 3986 /// 3987 /// \returns the declaration that hides the given declaration, or 3988 /// NULL if no such declaration exists. 3989 NamedDecl *checkHidden(NamedDecl *ND); 3990 3991 /// Add a declaration to the current shadow map. 3992 void add(NamedDecl *ND) { 3993 ShadowMaps.back()[ND->getDeclName()].push_back(ND); 3994 } 3995 }; 3996 3997 /// RAII object that records when we've entered a shadow context. 3998 class ShadowContextRAII { 3999 VisibleDeclsRecord &Visible; 4000 4001 typedef VisibleDeclsRecord::ShadowMap ShadowMap; 4002 4003 public: 4004 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) { 4005 Visible.ShadowMaps.emplace_back(); 4006 } 4007 4008 ~ShadowContextRAII() { 4009 Visible.ShadowMaps.pop_back(); 4010 } 4011 }; 4012 4013 } // end anonymous namespace 4014 4015 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) { 4016 unsigned IDNS = ND->getIdentifierNamespace(); 4017 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin(); 4018 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend(); 4019 SM != SMEnd; ++SM) { 4020 ShadowMap::iterator Pos = SM->find(ND->getDeclName()); 4021 if (Pos == SM->end()) 4022 continue; 4023 4024 for (auto *D : Pos->second) { 4025 // A tag declaration does not hide a non-tag declaration. 4026 if (D->hasTagIdentifierNamespace() && 4027 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | 4028 Decl::IDNS_ObjCProtocol))) 4029 continue; 4030 4031 // Protocols are in distinct namespaces from everything else. 4032 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) 4033 || (IDNS & Decl::IDNS_ObjCProtocol)) && 4034 D->getIdentifierNamespace() != IDNS) 4035 continue; 4036 4037 // Functions and function templates in the same scope overload 4038 // rather than hide. FIXME: Look for hiding based on function 4039 // signatures! 4040 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() && 4041 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() && 4042 SM == ShadowMaps.rbegin()) 4043 continue; 4044 4045 // A shadow declaration that's created by a resolved using declaration 4046 // is not hidden by the same using declaration. 4047 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) && 4048 cast<UsingShadowDecl>(ND)->getIntroducer() == D) 4049 continue; 4050 4051 // We've found a declaration that hides this one. 4052 return D; 4053 } 4054 } 4055 4056 return nullptr; 4057 } 4058 4059 namespace { 4060 class LookupVisibleHelper { 4061 public: 4062 LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases, 4063 bool LoadExternal) 4064 : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases), 4065 LoadExternal(LoadExternal) {} 4066 4067 void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind, 4068 bool IncludeGlobalScope) { 4069 // Determine the set of using directives available during 4070 // unqualified name lookup. 4071 Scope *Initial = S; 4072 UnqualUsingDirectiveSet UDirs(SemaRef); 4073 if (SemaRef.getLangOpts().CPlusPlus) { 4074 // Find the first namespace or translation-unit scope. 4075 while (S && !isNamespaceOrTranslationUnitScope(S)) 4076 S = S->getParent(); 4077 4078 UDirs.visitScopeChain(Initial, S); 4079 } 4080 UDirs.done(); 4081 4082 // Look for visible declarations. 4083 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind); 4084 Result.setAllowHidden(Consumer.includeHiddenDecls()); 4085 if (!IncludeGlobalScope) 4086 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl()); 4087 ShadowContextRAII Shadow(Visited); 4088 lookupInScope(Initial, Result, UDirs); 4089 } 4090 4091 void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx, 4092 Sema::LookupNameKind Kind, bool IncludeGlobalScope) { 4093 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind); 4094 Result.setAllowHidden(Consumer.includeHiddenDecls()); 4095 if (!IncludeGlobalScope) 4096 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl()); 4097 4098 ShadowContextRAII Shadow(Visited); 4099 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true, 4100 /*InBaseClass=*/false); 4101 } 4102 4103 private: 4104 void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result, 4105 bool QualifiedNameLookup, bool InBaseClass) { 4106 if (!Ctx) 4107 return; 4108 4109 // Make sure we don't visit the same context twice. 4110 if (Visited.visitedContext(Ctx->getPrimaryContext())) 4111 return; 4112 4113 Consumer.EnteredContext(Ctx); 4114 4115 // Outside C++, lookup results for the TU live on identifiers. 4116 if (isa<TranslationUnitDecl>(Ctx) && 4117 !Result.getSema().getLangOpts().CPlusPlus) { 4118 auto &S = Result.getSema(); 4119 auto &Idents = S.Context.Idents; 4120 4121 // Ensure all external identifiers are in the identifier table. 4122 if (LoadExternal) 4123 if (IdentifierInfoLookup *External = 4124 Idents.getExternalIdentifierLookup()) { 4125 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers()); 4126 for (StringRef Name = Iter->Next(); !Name.empty(); 4127 Name = Iter->Next()) 4128 Idents.get(Name); 4129 } 4130 4131 // Walk all lookup results in the TU for each identifier. 4132 for (const auto &Ident : Idents) { 4133 for (auto I = S.IdResolver.begin(Ident.getValue()), 4134 E = S.IdResolver.end(); 4135 I != E; ++I) { 4136 if (S.IdResolver.isDeclInScope(*I, Ctx)) { 4137 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) { 4138 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass); 4139 Visited.add(ND); 4140 } 4141 } 4142 } 4143 } 4144 4145 return; 4146 } 4147 4148 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx)) 4149 Result.getSema().ForceDeclarationOfImplicitMembers(Class); 4150 4151 llvm::SmallVector<NamedDecl *, 4> DeclsToVisit; 4152 // We sometimes skip loading namespace-level results (they tend to be huge). 4153 bool Load = LoadExternal || 4154 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx)); 4155 // Enumerate all of the results in this context. 4156 for (DeclContextLookupResult R : 4157 Load ? Ctx->lookups() 4158 : Ctx->noload_lookups(/*PreserveInternalState=*/false)) 4159 for (auto *D : R) 4160 // Rather than visit immediately, we put ND into a vector and visit 4161 // all decls, in order, outside of this loop. The reason is that 4162 // Consumer.FoundDecl() and LookupResult::getAcceptableDecl(D) 4163 // may invalidate the iterators used in the two 4164 // loops above. 4165 DeclsToVisit.push_back(D); 4166 4167 for (auto *D : DeclsToVisit) 4168 if (auto *ND = Result.getAcceptableDecl(D)) { 4169 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass); 4170 Visited.add(ND); 4171 } 4172 4173 DeclsToVisit.clear(); 4174 4175 // Traverse using directives for qualified name lookup. 4176 if (QualifiedNameLookup) { 4177 ShadowContextRAII Shadow(Visited); 4178 for (auto *I : Ctx->using_directives()) { 4179 if (!Result.getSema().isVisible(I)) 4180 continue; 4181 lookupInDeclContext(I->getNominatedNamespace(), Result, 4182 QualifiedNameLookup, InBaseClass); 4183 } 4184 } 4185 4186 // Traverse the contexts of inherited C++ classes. 4187 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) { 4188 if (!Record->hasDefinition()) 4189 return; 4190 4191 for (const auto &B : Record->bases()) { 4192 QualType BaseType = B.getType(); 4193 4194 RecordDecl *RD; 4195 if (BaseType->isDependentType()) { 4196 if (!IncludeDependentBases) { 4197 // Don't look into dependent bases, because name lookup can't look 4198 // there anyway. 4199 continue; 4200 } 4201 const auto *TST = BaseType->getAs<TemplateSpecializationType>(); 4202 if (!TST) 4203 continue; 4204 TemplateName TN = TST->getTemplateName(); 4205 const auto *TD = 4206 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl()); 4207 if (!TD) 4208 continue; 4209 RD = TD->getTemplatedDecl(); 4210 } else { 4211 const auto *Record = BaseType->getAs<RecordType>(); 4212 if (!Record) 4213 continue; 4214 RD = Record->getDecl(); 4215 } 4216 4217 // FIXME: It would be nice to be able to determine whether referencing 4218 // a particular member would be ambiguous. For example, given 4219 // 4220 // struct A { int member; }; 4221 // struct B { int member; }; 4222 // struct C : A, B { }; 4223 // 4224 // void f(C *c) { c->### } 4225 // 4226 // accessing 'member' would result in an ambiguity. However, we 4227 // could be smart enough to qualify the member with the base 4228 // class, e.g., 4229 // 4230 // c->B::member 4231 // 4232 // or 4233 // 4234 // c->A::member 4235 4236 // Find results in this base class (and its bases). 4237 ShadowContextRAII Shadow(Visited); 4238 lookupInDeclContext(RD, Result, QualifiedNameLookup, 4239 /*InBaseClass=*/true); 4240 } 4241 } 4242 4243 // Traverse the contexts of Objective-C classes. 4244 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) { 4245 // Traverse categories. 4246 for (auto *Cat : IFace->visible_categories()) { 4247 ShadowContextRAII Shadow(Visited); 4248 lookupInDeclContext(Cat, Result, QualifiedNameLookup, 4249 /*InBaseClass=*/false); 4250 } 4251 4252 // Traverse protocols. 4253 for (auto *I : IFace->all_referenced_protocols()) { 4254 ShadowContextRAII Shadow(Visited); 4255 lookupInDeclContext(I, Result, QualifiedNameLookup, 4256 /*InBaseClass=*/false); 4257 } 4258 4259 // Traverse the superclass. 4260 if (IFace->getSuperClass()) { 4261 ShadowContextRAII Shadow(Visited); 4262 lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup, 4263 /*InBaseClass=*/true); 4264 } 4265 4266 // If there is an implementation, traverse it. We do this to find 4267 // synthesized ivars. 4268 if (IFace->getImplementation()) { 4269 ShadowContextRAII Shadow(Visited); 4270 lookupInDeclContext(IFace->getImplementation(), Result, 4271 QualifiedNameLookup, InBaseClass); 4272 } 4273 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) { 4274 for (auto *I : Protocol->protocols()) { 4275 ShadowContextRAII Shadow(Visited); 4276 lookupInDeclContext(I, Result, QualifiedNameLookup, 4277 /*InBaseClass=*/false); 4278 } 4279 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) { 4280 for (auto *I : Category->protocols()) { 4281 ShadowContextRAII Shadow(Visited); 4282 lookupInDeclContext(I, Result, QualifiedNameLookup, 4283 /*InBaseClass=*/false); 4284 } 4285 4286 // If there is an implementation, traverse it. 4287 if (Category->getImplementation()) { 4288 ShadowContextRAII Shadow(Visited); 4289 lookupInDeclContext(Category->getImplementation(), Result, 4290 QualifiedNameLookup, /*InBaseClass=*/true); 4291 } 4292 } 4293 } 4294 4295 void lookupInScope(Scope *S, LookupResult &Result, 4296 UnqualUsingDirectiveSet &UDirs) { 4297 // No clients run in this mode and it's not supported. Please add tests and 4298 // remove the assertion if you start relying on it. 4299 assert(!IncludeDependentBases && "Unsupported flag for lookupInScope"); 4300 4301 if (!S) 4302 return; 4303 4304 if (!S->getEntity() || 4305 (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) || 4306 (S->getEntity())->isFunctionOrMethod()) { 4307 FindLocalExternScope FindLocals(Result); 4308 // Walk through the declarations in this Scope. The consumer might add new 4309 // decls to the scope as part of deserialization, so make a copy first. 4310 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end()); 4311 for (Decl *D : ScopeDecls) { 4312 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 4313 if ((ND = Result.getAcceptableDecl(ND))) { 4314 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false); 4315 Visited.add(ND); 4316 } 4317 } 4318 } 4319 4320 DeclContext *Entity = S->getLookupEntity(); 4321 if (Entity) { 4322 // Look into this scope's declaration context, along with any of its 4323 // parent lookup contexts (e.g., enclosing classes), up to the point 4324 // where we hit the context stored in the next outer scope. 4325 DeclContext *OuterCtx = findOuterContext(S); 4326 4327 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx); 4328 Ctx = Ctx->getLookupParent()) { 4329 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { 4330 if (Method->isInstanceMethod()) { 4331 // For instance methods, look for ivars in the method's interface. 4332 LookupResult IvarResult(Result.getSema(), Result.getLookupName(), 4333 Result.getNameLoc(), 4334 Sema::LookupMemberName); 4335 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) { 4336 lookupInDeclContext(IFace, IvarResult, 4337 /*QualifiedNameLookup=*/false, 4338 /*InBaseClass=*/false); 4339 } 4340 } 4341 4342 // We've already performed all of the name lookup that we need 4343 // to for Objective-C methods; the next context will be the 4344 // outer scope. 4345 break; 4346 } 4347 4348 if (Ctx->isFunctionOrMethod()) 4349 continue; 4350 4351 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false, 4352 /*InBaseClass=*/false); 4353 } 4354 } else if (!S->getParent()) { 4355 // Look into the translation unit scope. We walk through the translation 4356 // unit's declaration context, because the Scope itself won't have all of 4357 // the declarations if we loaded a precompiled header. 4358 // FIXME: We would like the translation unit's Scope object to point to 4359 // the translation unit, so we don't need this special "if" branch. 4360 // However, doing so would force the normal C++ name-lookup code to look 4361 // into the translation unit decl when the IdentifierInfo chains would 4362 // suffice. Once we fix that problem (which is part of a more general 4363 // "don't look in DeclContexts unless we have to" optimization), we can 4364 // eliminate this. 4365 Entity = Result.getSema().Context.getTranslationUnitDecl(); 4366 lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false, 4367 /*InBaseClass=*/false); 4368 } 4369 4370 if (Entity) { 4371 // Lookup visible declarations in any namespaces found by using 4372 // directives. 4373 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity)) 4374 lookupInDeclContext( 4375 const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result, 4376 /*QualifiedNameLookup=*/false, 4377 /*InBaseClass=*/false); 4378 } 4379 4380 // Lookup names in the parent scope. 4381 ShadowContextRAII Shadow(Visited); 4382 lookupInScope(S->getParent(), Result, UDirs); 4383 } 4384 4385 private: 4386 VisibleDeclsRecord Visited; 4387 VisibleDeclConsumer &Consumer; 4388 bool IncludeDependentBases; 4389 bool LoadExternal; 4390 }; 4391 } // namespace 4392 4393 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind, 4394 VisibleDeclConsumer &Consumer, 4395 bool IncludeGlobalScope, bool LoadExternal) { 4396 LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false, 4397 LoadExternal); 4398 H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope); 4399 } 4400 4401 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 4402 VisibleDeclConsumer &Consumer, 4403 bool IncludeGlobalScope, 4404 bool IncludeDependentBases, bool LoadExternal) { 4405 LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal); 4406 H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope); 4407 } 4408 4409 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name. 4410 /// If GnuLabelLoc is a valid source location, then this is a definition 4411 /// of an __label__ label name, otherwise it is a normal label definition 4412 /// or use. 4413 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc, 4414 SourceLocation GnuLabelLoc) { 4415 // Do a lookup to see if we have a label with this name already. 4416 NamedDecl *Res = nullptr; 4417 4418 if (GnuLabelLoc.isValid()) { 4419 // Local label definitions always shadow existing labels. 4420 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc); 4421 Scope *S = CurScope; 4422 PushOnScopeChains(Res, S, true); 4423 return cast<LabelDecl>(Res); 4424 } 4425 4426 // Not a GNU local label. 4427 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration); 4428 // If we found a label, check to see if it is in the same context as us. 4429 // When in a Block, we don't want to reuse a label in an enclosing function. 4430 if (Res && Res->getDeclContext() != CurContext) 4431 Res = nullptr; 4432 if (!Res) { 4433 // If not forward referenced or defined already, create the backing decl. 4434 Res = LabelDecl::Create(Context, CurContext, Loc, II); 4435 Scope *S = CurScope->getFnParent(); 4436 assert(S && "Not in a function?"); 4437 PushOnScopeChains(Res, S, true); 4438 } 4439 return cast<LabelDecl>(Res); 4440 } 4441 4442 //===----------------------------------------------------------------------===// 4443 // Typo correction 4444 //===----------------------------------------------------------------------===// 4445 4446 static bool isCandidateViable(CorrectionCandidateCallback &CCC, 4447 TypoCorrection &Candidate) { 4448 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate)); 4449 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance; 4450 } 4451 4452 static void LookupPotentialTypoResult(Sema &SemaRef, 4453 LookupResult &Res, 4454 IdentifierInfo *Name, 4455 Scope *S, CXXScopeSpec *SS, 4456 DeclContext *MemberContext, 4457 bool EnteringContext, 4458 bool isObjCIvarLookup, 4459 bool FindHidden); 4460 4461 /// Check whether the declarations found for a typo correction are 4462 /// visible. Set the correction's RequiresImport flag to true if none of the 4463 /// declarations are visible, false otherwise. 4464 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) { 4465 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end(); 4466 4467 for (/**/; DI != DE; ++DI) 4468 if (!LookupResult::isVisible(SemaRef, *DI)) 4469 break; 4470 // No filtering needed if all decls are visible. 4471 if (DI == DE) { 4472 TC.setRequiresImport(false); 4473 return; 4474 } 4475 4476 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI); 4477 bool AnyVisibleDecls = !NewDecls.empty(); 4478 4479 for (/**/; DI != DE; ++DI) { 4480 if (LookupResult::isVisible(SemaRef, *DI)) { 4481 if (!AnyVisibleDecls) { 4482 // Found a visible decl, discard all hidden ones. 4483 AnyVisibleDecls = true; 4484 NewDecls.clear(); 4485 } 4486 NewDecls.push_back(*DI); 4487 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate()) 4488 NewDecls.push_back(*DI); 4489 } 4490 4491 if (NewDecls.empty()) 4492 TC = TypoCorrection(); 4493 else { 4494 TC.setCorrectionDecls(NewDecls); 4495 TC.setRequiresImport(!AnyVisibleDecls); 4496 } 4497 } 4498 4499 // Fill the supplied vector with the IdentifierInfo pointers for each piece of 4500 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::", 4501 // fill the vector with the IdentifierInfo pointers for "foo" and "bar"). 4502 static void getNestedNameSpecifierIdentifiers( 4503 NestedNameSpecifier *NNS, 4504 SmallVectorImpl<const IdentifierInfo*> &Identifiers) { 4505 if (NestedNameSpecifier *Prefix = NNS->getPrefix()) 4506 getNestedNameSpecifierIdentifiers(Prefix, Identifiers); 4507 else 4508 Identifiers.clear(); 4509 4510 const IdentifierInfo *II = nullptr; 4511 4512 switch (NNS->getKind()) { 4513 case NestedNameSpecifier::Identifier: 4514 II = NNS->getAsIdentifier(); 4515 break; 4516 4517 case NestedNameSpecifier::Namespace: 4518 if (NNS->getAsNamespace()->isAnonymousNamespace()) 4519 return; 4520 II = NNS->getAsNamespace()->getIdentifier(); 4521 break; 4522 4523 case NestedNameSpecifier::NamespaceAlias: 4524 II = NNS->getAsNamespaceAlias()->getIdentifier(); 4525 break; 4526 4527 case NestedNameSpecifier::TypeSpecWithTemplate: 4528 case NestedNameSpecifier::TypeSpec: 4529 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier(); 4530 break; 4531 4532 case NestedNameSpecifier::Global: 4533 case NestedNameSpecifier::Super: 4534 return; 4535 } 4536 4537 if (II) 4538 Identifiers.push_back(II); 4539 } 4540 4541 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding, 4542 DeclContext *Ctx, bool InBaseClass) { 4543 // Don't consider hidden names for typo correction. 4544 if (Hiding) 4545 return; 4546 4547 // Only consider entities with identifiers for names, ignoring 4548 // special names (constructors, overloaded operators, selectors, 4549 // etc.). 4550 IdentifierInfo *Name = ND->getIdentifier(); 4551 if (!Name) 4552 return; 4553 4554 // Only consider visible declarations and declarations from modules with 4555 // names that exactly match. 4556 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo) 4557 return; 4558 4559 FoundName(Name->getName()); 4560 } 4561 4562 void TypoCorrectionConsumer::FoundName(StringRef Name) { 4563 // Compute the edit distance between the typo and the name of this 4564 // entity, and add the identifier to the list of results. 4565 addName(Name, nullptr); 4566 } 4567 4568 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) { 4569 // Compute the edit distance between the typo and this keyword, 4570 // and add the keyword to the list of results. 4571 addName(Keyword, nullptr, nullptr, true); 4572 } 4573 4574 void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND, 4575 NestedNameSpecifier *NNS, bool isKeyword) { 4576 // Use a simple length-based heuristic to determine the minimum possible 4577 // edit distance. If the minimum isn't good enough, bail out early. 4578 StringRef TypoStr = Typo->getName(); 4579 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size()); 4580 if (MinED && TypoStr.size() / MinED < 3) 4581 return; 4582 4583 // Compute an upper bound on the allowable edit distance, so that the 4584 // edit-distance algorithm can short-circuit. 4585 unsigned UpperBound = (TypoStr.size() + 2) / 3; 4586 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound); 4587 if (ED > UpperBound) return; 4588 4589 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED); 4590 if (isKeyword) TC.makeKeyword(); 4591 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo()); 4592 addCorrection(TC); 4593 } 4594 4595 static const unsigned MaxTypoDistanceResultSets = 5; 4596 4597 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) { 4598 StringRef TypoStr = Typo->getName(); 4599 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName(); 4600 4601 // For very short typos, ignore potential corrections that have a different 4602 // base identifier from the typo or which have a normalized edit distance 4603 // longer than the typo itself. 4604 if (TypoStr.size() < 3 && 4605 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size())) 4606 return; 4607 4608 // If the correction is resolved but is not viable, ignore it. 4609 if (Correction.isResolved()) { 4610 checkCorrectionVisibility(SemaRef, Correction); 4611 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction)) 4612 return; 4613 } 4614 4615 TypoResultList &CList = 4616 CorrectionResults[Correction.getEditDistance(false)][Name]; 4617 4618 if (!CList.empty() && !CList.back().isResolved()) 4619 CList.pop_back(); 4620 if (NamedDecl *NewND = Correction.getCorrectionDecl()) { 4621 auto RI = llvm::find_if(CList, [NewND](const TypoCorrection &TypoCorr) { 4622 return TypoCorr.getCorrectionDecl() == NewND; 4623 }); 4624 if (RI != CList.end()) { 4625 // The Correction refers to a decl already in the list. No insertion is 4626 // necessary and all further cases will return. 4627 4628 auto IsDeprecated = [](Decl *D) { 4629 while (D) { 4630 if (D->isDeprecated()) 4631 return true; 4632 D = llvm::dyn_cast_or_null<NamespaceDecl>(D->getDeclContext()); 4633 } 4634 return false; 4635 }; 4636 4637 // Prefer non deprecated Corrections over deprecated and only then 4638 // sort using an alphabetical order. 4639 std::pair<bool, std::string> NewKey = { 4640 IsDeprecated(Correction.getFoundDecl()), 4641 Correction.getAsString(SemaRef.getLangOpts())}; 4642 4643 std::pair<bool, std::string> PrevKey = { 4644 IsDeprecated(RI->getFoundDecl()), 4645 RI->getAsString(SemaRef.getLangOpts())}; 4646 4647 if (NewKey < PrevKey) 4648 *RI = Correction; 4649 return; 4650 } 4651 } 4652 if (CList.empty() || Correction.isResolved()) 4653 CList.push_back(Correction); 4654 4655 while (CorrectionResults.size() > MaxTypoDistanceResultSets) 4656 CorrectionResults.erase(std::prev(CorrectionResults.end())); 4657 } 4658 4659 void TypoCorrectionConsumer::addNamespaces( 4660 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) { 4661 SearchNamespaces = true; 4662 4663 for (auto KNPair : KnownNamespaces) 4664 Namespaces.addNameSpecifier(KNPair.first); 4665 4666 bool SSIsTemplate = false; 4667 if (NestedNameSpecifier *NNS = 4668 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) { 4669 if (const Type *T = NNS->getAsType()) 4670 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization; 4671 } 4672 // Do not transform this into an iterator-based loop. The loop body can 4673 // trigger the creation of further types (through lazy deserialization) and 4674 // invalid iterators into this list. 4675 auto &Types = SemaRef.getASTContext().getTypes(); 4676 for (unsigned I = 0; I != Types.size(); ++I) { 4677 const auto *TI = Types[I]; 4678 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) { 4679 CD = CD->getCanonicalDecl(); 4680 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() && 4681 !CD->isUnion() && CD->getIdentifier() && 4682 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) && 4683 (CD->isBeingDefined() || CD->isCompleteDefinition())) 4684 Namespaces.addNameSpecifier(CD); 4685 } 4686 } 4687 } 4688 4689 const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() { 4690 if (++CurrentTCIndex < ValidatedCorrections.size()) 4691 return ValidatedCorrections[CurrentTCIndex]; 4692 4693 CurrentTCIndex = ValidatedCorrections.size(); 4694 while (!CorrectionResults.empty()) { 4695 auto DI = CorrectionResults.begin(); 4696 if (DI->second.empty()) { 4697 CorrectionResults.erase(DI); 4698 continue; 4699 } 4700 4701 auto RI = DI->second.begin(); 4702 if (RI->second.empty()) { 4703 DI->second.erase(RI); 4704 performQualifiedLookups(); 4705 continue; 4706 } 4707 4708 TypoCorrection TC = RI->second.pop_back_val(); 4709 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) { 4710 ValidatedCorrections.push_back(TC); 4711 return ValidatedCorrections[CurrentTCIndex]; 4712 } 4713 } 4714 return ValidatedCorrections[0]; // The empty correction. 4715 } 4716 4717 bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) { 4718 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo(); 4719 DeclContext *TempMemberContext = MemberContext; 4720 CXXScopeSpec *TempSS = SS.get(); 4721 retry_lookup: 4722 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext, 4723 EnteringContext, 4724 CorrectionValidator->IsObjCIvarLookup, 4725 Name == Typo && !Candidate.WillReplaceSpecifier()); 4726 switch (Result.getResultKind()) { 4727 case LookupResult::NotFound: 4728 case LookupResult::NotFoundInCurrentInstantiation: 4729 case LookupResult::FoundUnresolvedValue: 4730 if (TempSS) { 4731 // Immediately retry the lookup without the given CXXScopeSpec 4732 TempSS = nullptr; 4733 Candidate.WillReplaceSpecifier(true); 4734 goto retry_lookup; 4735 } 4736 if (TempMemberContext) { 4737 if (SS && !TempSS) 4738 TempSS = SS.get(); 4739 TempMemberContext = nullptr; 4740 goto retry_lookup; 4741 } 4742 if (SearchNamespaces) 4743 QualifiedResults.push_back(Candidate); 4744 break; 4745 4746 case LookupResult::Ambiguous: 4747 // We don't deal with ambiguities. 4748 break; 4749 4750 case LookupResult::Found: 4751 case LookupResult::FoundOverloaded: 4752 // Store all of the Decls for overloaded symbols 4753 for (auto *TRD : Result) 4754 Candidate.addCorrectionDecl(TRD); 4755 checkCorrectionVisibility(SemaRef, Candidate); 4756 if (!isCandidateViable(*CorrectionValidator, Candidate)) { 4757 if (SearchNamespaces) 4758 QualifiedResults.push_back(Candidate); 4759 break; 4760 } 4761 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo()); 4762 return true; 4763 } 4764 return false; 4765 } 4766 4767 void TypoCorrectionConsumer::performQualifiedLookups() { 4768 unsigned TypoLen = Typo->getName().size(); 4769 for (const TypoCorrection &QR : QualifiedResults) { 4770 for (const auto &NSI : Namespaces) { 4771 DeclContext *Ctx = NSI.DeclCtx; 4772 const Type *NSType = NSI.NameSpecifier->getAsType(); 4773 4774 // If the current NestedNameSpecifier refers to a class and the 4775 // current correction candidate is the name of that class, then skip 4776 // it as it is unlikely a qualified version of the class' constructor 4777 // is an appropriate correction. 4778 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : 4779 nullptr) { 4780 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo()) 4781 continue; 4782 } 4783 4784 TypoCorrection TC(QR); 4785 TC.ClearCorrectionDecls(); 4786 TC.setCorrectionSpecifier(NSI.NameSpecifier); 4787 TC.setQualifierDistance(NSI.EditDistance); 4788 TC.setCallbackDistance(0); // Reset the callback distance 4789 4790 // If the current correction candidate and namespace combination are 4791 // too far away from the original typo based on the normalized edit 4792 // distance, then skip performing a qualified name lookup. 4793 unsigned TmpED = TC.getEditDistance(true); 4794 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED && 4795 TypoLen / TmpED < 3) 4796 continue; 4797 4798 Result.clear(); 4799 Result.setLookupName(QR.getCorrectionAsIdentifierInfo()); 4800 if (!SemaRef.LookupQualifiedName(Result, Ctx)) 4801 continue; 4802 4803 // Any corrections added below will be validated in subsequent 4804 // iterations of the main while() loop over the Consumer's contents. 4805 switch (Result.getResultKind()) { 4806 case LookupResult::Found: 4807 case LookupResult::FoundOverloaded: { 4808 if (SS && SS->isValid()) { 4809 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts()); 4810 std::string OldQualified; 4811 llvm::raw_string_ostream OldOStream(OldQualified); 4812 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy()); 4813 OldOStream << Typo->getName(); 4814 // If correction candidate would be an identical written qualified 4815 // identifier, then the existing CXXScopeSpec probably included a 4816 // typedef that didn't get accounted for properly. 4817 if (OldOStream.str() == NewQualified) 4818 break; 4819 } 4820 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end(); 4821 TRD != TRDEnd; ++TRD) { 4822 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(), 4823 NSType ? NSType->getAsCXXRecordDecl() 4824 : nullptr, 4825 TRD.getPair()) == Sema::AR_accessible) 4826 TC.addCorrectionDecl(*TRD); 4827 } 4828 if (TC.isResolved()) { 4829 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo()); 4830 addCorrection(TC); 4831 } 4832 break; 4833 } 4834 case LookupResult::NotFound: 4835 case LookupResult::NotFoundInCurrentInstantiation: 4836 case LookupResult::Ambiguous: 4837 case LookupResult::FoundUnresolvedValue: 4838 break; 4839 } 4840 } 4841 } 4842 QualifiedResults.clear(); 4843 } 4844 4845 TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet( 4846 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec) 4847 : Context(Context), CurContextChain(buildContextChain(CurContext)) { 4848 if (NestedNameSpecifier *NNS = 4849 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) { 4850 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier); 4851 NNS->print(SpecifierOStream, Context.getPrintingPolicy()); 4852 4853 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers); 4854 } 4855 // Build the list of identifiers that would be used for an absolute 4856 // (from the global context) NestedNameSpecifier referring to the current 4857 // context. 4858 for (DeclContext *C : llvm::reverse(CurContextChain)) { 4859 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) 4860 CurContextIdentifiers.push_back(ND->getIdentifier()); 4861 } 4862 4863 // Add the global context as a NestedNameSpecifier 4864 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()), 4865 NestedNameSpecifier::GlobalSpecifier(Context), 1}; 4866 DistanceMap[1].push_back(SI); 4867 } 4868 4869 auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain( 4870 DeclContext *Start) -> DeclContextList { 4871 assert(Start && "Building a context chain from a null context"); 4872 DeclContextList Chain; 4873 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr; 4874 DC = DC->getLookupParent()) { 4875 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC); 4876 if (!DC->isInlineNamespace() && !DC->isTransparentContext() && 4877 !(ND && ND->isAnonymousNamespace())) 4878 Chain.push_back(DC->getPrimaryContext()); 4879 } 4880 return Chain; 4881 } 4882 4883 unsigned 4884 TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier( 4885 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) { 4886 unsigned NumSpecifiers = 0; 4887 for (DeclContext *C : llvm::reverse(DeclChain)) { 4888 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) { 4889 NNS = NestedNameSpecifier::Create(Context, NNS, ND); 4890 ++NumSpecifiers; 4891 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) { 4892 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(), 4893 RD->getTypeForDecl()); 4894 ++NumSpecifiers; 4895 } 4896 } 4897 return NumSpecifiers; 4898 } 4899 4900 void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier( 4901 DeclContext *Ctx) { 4902 NestedNameSpecifier *NNS = nullptr; 4903 unsigned NumSpecifiers = 0; 4904 DeclContextList NamespaceDeclChain(buildContextChain(Ctx)); 4905 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain); 4906 4907 // Eliminate common elements from the two DeclContext chains. 4908 for (DeclContext *C : llvm::reverse(CurContextChain)) { 4909 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C) 4910 break; 4911 NamespaceDeclChain.pop_back(); 4912 } 4913 4914 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain 4915 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS); 4916 4917 // Add an explicit leading '::' specifier if needed. 4918 if (NamespaceDeclChain.empty()) { 4919 // Rebuild the NestedNameSpecifier as a globally-qualified specifier. 4920 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 4921 NumSpecifiers = 4922 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS); 4923 } else if (NamedDecl *ND = 4924 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) { 4925 IdentifierInfo *Name = ND->getIdentifier(); 4926 bool SameNameSpecifier = false; 4927 if (llvm::is_contained(CurNameSpecifierIdentifiers, Name)) { 4928 std::string NewNameSpecifier; 4929 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier); 4930 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers; 4931 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers); 4932 NNS->print(SpecifierOStream, Context.getPrintingPolicy()); 4933 SpecifierOStream.flush(); 4934 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier; 4935 } 4936 if (SameNameSpecifier || llvm::is_contained(CurContextIdentifiers, Name)) { 4937 // Rebuild the NestedNameSpecifier as a globally-qualified specifier. 4938 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 4939 NumSpecifiers = 4940 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS); 4941 } 4942 } 4943 4944 // If the built NestedNameSpecifier would be replacing an existing 4945 // NestedNameSpecifier, use the number of component identifiers that 4946 // would need to be changed as the edit distance instead of the number 4947 // of components in the built NestedNameSpecifier. 4948 if (NNS && !CurNameSpecifierIdentifiers.empty()) { 4949 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers; 4950 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers); 4951 NumSpecifiers = 4952 llvm::ComputeEditDistance(llvm::ArrayRef(CurNameSpecifierIdentifiers), 4953 llvm::ArrayRef(NewNameSpecifierIdentifiers)); 4954 } 4955 4956 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers}; 4957 DistanceMap[NumSpecifiers].push_back(SI); 4958 } 4959 4960 /// Perform name lookup for a possible result for typo correction. 4961 static void LookupPotentialTypoResult(Sema &SemaRef, 4962 LookupResult &Res, 4963 IdentifierInfo *Name, 4964 Scope *S, CXXScopeSpec *SS, 4965 DeclContext *MemberContext, 4966 bool EnteringContext, 4967 bool isObjCIvarLookup, 4968 bool FindHidden) { 4969 Res.suppressDiagnostics(); 4970 Res.clear(); 4971 Res.setLookupName(Name); 4972 Res.setAllowHidden(FindHidden); 4973 if (MemberContext) { 4974 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) { 4975 if (isObjCIvarLookup) { 4976 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) { 4977 Res.addDecl(Ivar); 4978 Res.resolveKind(); 4979 return; 4980 } 4981 } 4982 4983 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration( 4984 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { 4985 Res.addDecl(Prop); 4986 Res.resolveKind(); 4987 return; 4988 } 4989 } 4990 4991 SemaRef.LookupQualifiedName(Res, MemberContext); 4992 return; 4993 } 4994 4995 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false, 4996 EnteringContext); 4997 4998 // Fake ivar lookup; this should really be part of 4999 // LookupParsedName. 5000 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) { 5001 if (Method->isInstanceMethod() && Method->getClassInterface() && 5002 (Res.empty() || 5003 (Res.isSingleResult() && 5004 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) { 5005 if (ObjCIvarDecl *IV 5006 = Method->getClassInterface()->lookupInstanceVariable(Name)) { 5007 Res.addDecl(IV); 5008 Res.resolveKind(); 5009 } 5010 } 5011 } 5012 } 5013 5014 /// Add keywords to the consumer as possible typo corrections. 5015 static void AddKeywordsToConsumer(Sema &SemaRef, 5016 TypoCorrectionConsumer &Consumer, 5017 Scope *S, CorrectionCandidateCallback &CCC, 5018 bool AfterNestedNameSpecifier) { 5019 if (AfterNestedNameSpecifier) { 5020 // For 'X::', we know exactly which keywords can appear next. 5021 Consumer.addKeywordResult("template"); 5022 if (CCC.WantExpressionKeywords) 5023 Consumer.addKeywordResult("operator"); 5024 return; 5025 } 5026 5027 if (CCC.WantObjCSuper) 5028 Consumer.addKeywordResult("super"); 5029 5030 if (CCC.WantTypeSpecifiers) { 5031 // Add type-specifier keywords to the set of results. 5032 static const char *const CTypeSpecs[] = { 5033 "char", "const", "double", "enum", "float", "int", "long", "short", 5034 "signed", "struct", "union", "unsigned", "void", "volatile", 5035 "_Complex", "_Imaginary", 5036 // storage-specifiers as well 5037 "extern", "inline", "static", "typedef" 5038 }; 5039 5040 for (const auto *CTS : CTypeSpecs) 5041 Consumer.addKeywordResult(CTS); 5042 5043 if (SemaRef.getLangOpts().C99) 5044 Consumer.addKeywordResult("restrict"); 5045 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) 5046 Consumer.addKeywordResult("bool"); 5047 else if (SemaRef.getLangOpts().C99) 5048 Consumer.addKeywordResult("_Bool"); 5049 5050 if (SemaRef.getLangOpts().CPlusPlus) { 5051 Consumer.addKeywordResult("class"); 5052 Consumer.addKeywordResult("typename"); 5053 Consumer.addKeywordResult("wchar_t"); 5054 5055 if (SemaRef.getLangOpts().CPlusPlus11) { 5056 Consumer.addKeywordResult("char16_t"); 5057 Consumer.addKeywordResult("char32_t"); 5058 Consumer.addKeywordResult("constexpr"); 5059 Consumer.addKeywordResult("decltype"); 5060 Consumer.addKeywordResult("thread_local"); 5061 } 5062 } 5063 5064 if (SemaRef.getLangOpts().GNUKeywords) 5065 Consumer.addKeywordResult("typeof"); 5066 } else if (CCC.WantFunctionLikeCasts) { 5067 static const char *const CastableTypeSpecs[] = { 5068 "char", "double", "float", "int", "long", "short", 5069 "signed", "unsigned", "void" 5070 }; 5071 for (auto *kw : CastableTypeSpecs) 5072 Consumer.addKeywordResult(kw); 5073 } 5074 5075 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) { 5076 Consumer.addKeywordResult("const_cast"); 5077 Consumer.addKeywordResult("dynamic_cast"); 5078 Consumer.addKeywordResult("reinterpret_cast"); 5079 Consumer.addKeywordResult("static_cast"); 5080 } 5081 5082 if (CCC.WantExpressionKeywords) { 5083 Consumer.addKeywordResult("sizeof"); 5084 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) { 5085 Consumer.addKeywordResult("false"); 5086 Consumer.addKeywordResult("true"); 5087 } 5088 5089 if (SemaRef.getLangOpts().CPlusPlus) { 5090 static const char *const CXXExprs[] = { 5091 "delete", "new", "operator", "throw", "typeid" 5092 }; 5093 for (const auto *CE : CXXExprs) 5094 Consumer.addKeywordResult(CE); 5095 5096 if (isa<CXXMethodDecl>(SemaRef.CurContext) && 5097 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance()) 5098 Consumer.addKeywordResult("this"); 5099 5100 if (SemaRef.getLangOpts().CPlusPlus11) { 5101 Consumer.addKeywordResult("alignof"); 5102 Consumer.addKeywordResult("nullptr"); 5103 } 5104 } 5105 5106 if (SemaRef.getLangOpts().C11) { 5107 // FIXME: We should not suggest _Alignof if the alignof macro 5108 // is present. 5109 Consumer.addKeywordResult("_Alignof"); 5110 } 5111 } 5112 5113 if (CCC.WantRemainingKeywords) { 5114 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) { 5115 // Statements. 5116 static const char *const CStmts[] = { 5117 "do", "else", "for", "goto", "if", "return", "switch", "while" }; 5118 for (const auto *CS : CStmts) 5119 Consumer.addKeywordResult(CS); 5120 5121 if (SemaRef.getLangOpts().CPlusPlus) { 5122 Consumer.addKeywordResult("catch"); 5123 Consumer.addKeywordResult("try"); 5124 } 5125 5126 if (S && S->getBreakParent()) 5127 Consumer.addKeywordResult("break"); 5128 5129 if (S && S->getContinueParent()) 5130 Consumer.addKeywordResult("continue"); 5131 5132 if (SemaRef.getCurFunction() && 5133 !SemaRef.getCurFunction()->SwitchStack.empty()) { 5134 Consumer.addKeywordResult("case"); 5135 Consumer.addKeywordResult("default"); 5136 } 5137 } else { 5138 if (SemaRef.getLangOpts().CPlusPlus) { 5139 Consumer.addKeywordResult("namespace"); 5140 Consumer.addKeywordResult("template"); 5141 } 5142 5143 if (S && S->isClassScope()) { 5144 Consumer.addKeywordResult("explicit"); 5145 Consumer.addKeywordResult("friend"); 5146 Consumer.addKeywordResult("mutable"); 5147 Consumer.addKeywordResult("private"); 5148 Consumer.addKeywordResult("protected"); 5149 Consumer.addKeywordResult("public"); 5150 Consumer.addKeywordResult("virtual"); 5151 } 5152 } 5153 5154 if (SemaRef.getLangOpts().CPlusPlus) { 5155 Consumer.addKeywordResult("using"); 5156 5157 if (SemaRef.getLangOpts().CPlusPlus11) 5158 Consumer.addKeywordResult("static_assert"); 5159 } 5160 } 5161 } 5162 5163 std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer( 5164 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind, 5165 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, 5166 DeclContext *MemberContext, bool EnteringContext, 5167 const ObjCObjectPointerType *OPT, bool ErrorRecovery) { 5168 5169 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking || 5170 DisableTypoCorrection) 5171 return nullptr; 5172 5173 // In Microsoft mode, don't perform typo correction in a template member 5174 // function dependent context because it interferes with the "lookup into 5175 // dependent bases of class templates" feature. 5176 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() && 5177 isa<CXXMethodDecl>(CurContext)) 5178 return nullptr; 5179 5180 // We only attempt to correct typos for identifiers. 5181 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); 5182 if (!Typo) 5183 return nullptr; 5184 5185 // If the scope specifier itself was invalid, don't try to correct 5186 // typos. 5187 if (SS && SS->isInvalid()) 5188 return nullptr; 5189 5190 // Never try to correct typos during any kind of code synthesis. 5191 if (!CodeSynthesisContexts.empty()) 5192 return nullptr; 5193 5194 // Don't try to correct 'super'. 5195 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier()) 5196 return nullptr; 5197 5198 // Abort if typo correction already failed for this specific typo. 5199 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo); 5200 if (locs != TypoCorrectionFailures.end() && 5201 locs->second.count(TypoName.getLoc())) 5202 return nullptr; 5203 5204 // Don't try to correct the identifier "vector" when in AltiVec mode. 5205 // TODO: Figure out why typo correction misbehaves in this case, fix it, and 5206 // remove this workaround. 5207 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector")) 5208 return nullptr; 5209 5210 // Provide a stop gap for files that are just seriously broken. Trying 5211 // to correct all typos can turn into a HUGE performance penalty, causing 5212 // some files to take minutes to get rejected by the parser. 5213 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit; 5214 if (Limit && TyposCorrected >= Limit) 5215 return nullptr; 5216 ++TyposCorrected; 5217 5218 // If we're handling a missing symbol error, using modules, and the 5219 // special search all modules option is used, look for a missing import. 5220 if (ErrorRecovery && getLangOpts().Modules && 5221 getLangOpts().ModulesSearchAll) { 5222 // The following has the side effect of loading the missing module. 5223 getModuleLoader().lookupMissingImports(Typo->getName(), 5224 TypoName.getBeginLoc()); 5225 } 5226 5227 // Extend the lifetime of the callback. We delayed this until here 5228 // to avoid allocations in the hot path (which is where no typo correction 5229 // occurs). Note that CorrectionCandidateCallback is polymorphic and 5230 // initially stack-allocated. 5231 std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone(); 5232 auto Consumer = std::make_unique<TypoCorrectionConsumer>( 5233 *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext, 5234 EnteringContext); 5235 5236 // Perform name lookup to find visible, similarly-named entities. 5237 bool IsUnqualifiedLookup = false; 5238 DeclContext *QualifiedDC = MemberContext; 5239 if (MemberContext) { 5240 LookupVisibleDecls(MemberContext, LookupKind, *Consumer); 5241 5242 // Look in qualified interfaces. 5243 if (OPT) { 5244 for (auto *I : OPT->quals()) 5245 LookupVisibleDecls(I, LookupKind, *Consumer); 5246 } 5247 } else if (SS && SS->isSet()) { 5248 QualifiedDC = computeDeclContext(*SS, EnteringContext); 5249 if (!QualifiedDC) 5250 return nullptr; 5251 5252 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer); 5253 } else { 5254 IsUnqualifiedLookup = true; 5255 } 5256 5257 // Determine whether we are going to search in the various namespaces for 5258 // corrections. 5259 bool SearchNamespaces 5260 = getLangOpts().CPlusPlus && 5261 (IsUnqualifiedLookup || (SS && SS->isSet())); 5262 5263 if (IsUnqualifiedLookup || SearchNamespaces) { 5264 // For unqualified lookup, look through all of the names that we have 5265 // seen in this translation unit. 5266 // FIXME: Re-add the ability to skip very unlikely potential corrections. 5267 for (const auto &I : Context.Idents) 5268 Consumer->FoundName(I.getKey()); 5269 5270 // Walk through identifiers in external identifier sources. 5271 // FIXME: Re-add the ability to skip very unlikely potential corrections. 5272 if (IdentifierInfoLookup *External 5273 = Context.Idents.getExternalIdentifierLookup()) { 5274 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers()); 5275 do { 5276 StringRef Name = Iter->Next(); 5277 if (Name.empty()) 5278 break; 5279 5280 Consumer->FoundName(Name); 5281 } while (true); 5282 } 5283 } 5284 5285 AddKeywordsToConsumer(*this, *Consumer, S, 5286 *Consumer->getCorrectionValidator(), 5287 SS && SS->isNotEmpty()); 5288 5289 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going 5290 // to search those namespaces. 5291 if (SearchNamespaces) { 5292 // Load any externally-known namespaces. 5293 if (ExternalSource && !LoadedExternalKnownNamespaces) { 5294 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces; 5295 LoadedExternalKnownNamespaces = true; 5296 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces); 5297 for (auto *N : ExternalKnownNamespaces) 5298 KnownNamespaces[N] = true; 5299 } 5300 5301 Consumer->addNamespaces(KnownNamespaces); 5302 } 5303 5304 return Consumer; 5305 } 5306 5307 /// Try to "correct" a typo in the source code by finding 5308 /// visible declarations whose names are similar to the name that was 5309 /// present in the source code. 5310 /// 5311 /// \param TypoName the \c DeclarationNameInfo structure that contains 5312 /// the name that was present in the source code along with its location. 5313 /// 5314 /// \param LookupKind the name-lookup criteria used to search for the name. 5315 /// 5316 /// \param S the scope in which name lookup occurs. 5317 /// 5318 /// \param SS the nested-name-specifier that precedes the name we're 5319 /// looking for, if present. 5320 /// 5321 /// \param CCC A CorrectionCandidateCallback object that provides further 5322 /// validation of typo correction candidates. It also provides flags for 5323 /// determining the set of keywords permitted. 5324 /// 5325 /// \param MemberContext if non-NULL, the context in which to look for 5326 /// a member access expression. 5327 /// 5328 /// \param EnteringContext whether we're entering the context described by 5329 /// the nested-name-specifier SS. 5330 /// 5331 /// \param OPT when non-NULL, the search for visible declarations will 5332 /// also walk the protocols in the qualified interfaces of \p OPT. 5333 /// 5334 /// \returns a \c TypoCorrection containing the corrected name if the typo 5335 /// along with information such as the \c NamedDecl where the corrected name 5336 /// was declared, and any additional \c NestedNameSpecifier needed to access 5337 /// it (C++ only). The \c TypoCorrection is empty if there is no correction. 5338 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName, 5339 Sema::LookupNameKind LookupKind, 5340 Scope *S, CXXScopeSpec *SS, 5341 CorrectionCandidateCallback &CCC, 5342 CorrectTypoKind Mode, 5343 DeclContext *MemberContext, 5344 bool EnteringContext, 5345 const ObjCObjectPointerType *OPT, 5346 bool RecordFailure) { 5347 // Always let the ExternalSource have the first chance at correction, even 5348 // if we would otherwise have given up. 5349 if (ExternalSource) { 5350 if (TypoCorrection Correction = 5351 ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC, 5352 MemberContext, EnteringContext, OPT)) 5353 return Correction; 5354 } 5355 5356 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver; 5357 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for 5358 // some instances of CTC_Unknown, while WantRemainingKeywords is true 5359 // for CTC_Unknown but not for CTC_ObjCMessageReceiver. 5360 bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords; 5361 5362 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); 5363 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC, 5364 MemberContext, EnteringContext, 5365 OPT, Mode == CTK_ErrorRecovery); 5366 5367 if (!Consumer) 5368 return TypoCorrection(); 5369 5370 // If we haven't found anything, we're done. 5371 if (Consumer->empty()) 5372 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 5373 5374 // Make sure the best edit distance (prior to adding any namespace qualifiers) 5375 // is not more that about a third of the length of the typo's identifier. 5376 unsigned ED = Consumer->getBestEditDistance(true); 5377 unsigned TypoLen = Typo->getName().size(); 5378 if (ED > 0 && TypoLen / ED < 3) 5379 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 5380 5381 TypoCorrection BestTC = Consumer->getNextCorrection(); 5382 TypoCorrection SecondBestTC = Consumer->getNextCorrection(); 5383 if (!BestTC) 5384 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 5385 5386 ED = BestTC.getEditDistance(); 5387 5388 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) { 5389 // If this was an unqualified lookup and we believe the callback 5390 // object wouldn't have filtered out possible corrections, note 5391 // that no correction was found. 5392 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 5393 } 5394 5395 // If only a single name remains, return that result. 5396 if (!SecondBestTC || 5397 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) { 5398 const TypoCorrection &Result = BestTC; 5399 5400 // Don't correct to a keyword that's the same as the typo; the keyword 5401 // wasn't actually in scope. 5402 if (ED == 0 && Result.isKeyword()) 5403 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 5404 5405 TypoCorrection TC = Result; 5406 TC.setCorrectionRange(SS, TypoName); 5407 checkCorrectionVisibility(*this, TC); 5408 return TC; 5409 } else if (SecondBestTC && ObjCMessageReceiver) { 5410 // Prefer 'super' when we're completing in a message-receiver 5411 // context. 5412 5413 if (BestTC.getCorrection().getAsString() != "super") { 5414 if (SecondBestTC.getCorrection().getAsString() == "super") 5415 BestTC = SecondBestTC; 5416 else if ((*Consumer)["super"].front().isKeyword()) 5417 BestTC = (*Consumer)["super"].front(); 5418 } 5419 // Don't correct to a keyword that's the same as the typo; the keyword 5420 // wasn't actually in scope. 5421 if (BestTC.getEditDistance() == 0 || 5422 BestTC.getCorrection().getAsString() != "super") 5423 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 5424 5425 BestTC.setCorrectionRange(SS, TypoName); 5426 return BestTC; 5427 } 5428 5429 // Record the failure's location if needed and return an empty correction. If 5430 // this was an unqualified lookup and we believe the callback object did not 5431 // filter out possible corrections, also cache the failure for the typo. 5432 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC); 5433 } 5434 5435 /// Try to "correct" a typo in the source code by finding 5436 /// visible declarations whose names are similar to the name that was 5437 /// present in the source code. 5438 /// 5439 /// \param TypoName the \c DeclarationNameInfo structure that contains 5440 /// the name that was present in the source code along with its location. 5441 /// 5442 /// \param LookupKind the name-lookup criteria used to search for the name. 5443 /// 5444 /// \param S the scope in which name lookup occurs. 5445 /// 5446 /// \param SS the nested-name-specifier that precedes the name we're 5447 /// looking for, if present. 5448 /// 5449 /// \param CCC A CorrectionCandidateCallback object that provides further 5450 /// validation of typo correction candidates. It also provides flags for 5451 /// determining the set of keywords permitted. 5452 /// 5453 /// \param TDG A TypoDiagnosticGenerator functor that will be used to print 5454 /// diagnostics when the actual typo correction is attempted. 5455 /// 5456 /// \param TRC A TypoRecoveryCallback functor that will be used to build an 5457 /// Expr from a typo correction candidate. 5458 /// 5459 /// \param MemberContext if non-NULL, the context in which to look for 5460 /// a member access expression. 5461 /// 5462 /// \param EnteringContext whether we're entering the context described by 5463 /// the nested-name-specifier SS. 5464 /// 5465 /// \param OPT when non-NULL, the search for visible declarations will 5466 /// also walk the protocols in the qualified interfaces of \p OPT. 5467 /// 5468 /// \returns a new \c TypoExpr that will later be replaced in the AST with an 5469 /// Expr representing the result of performing typo correction, or nullptr if 5470 /// typo correction is not possible. If nullptr is returned, no diagnostics will 5471 /// be emitted and it is the responsibility of the caller to emit any that are 5472 /// needed. 5473 TypoExpr *Sema::CorrectTypoDelayed( 5474 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind, 5475 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, 5476 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, 5477 DeclContext *MemberContext, bool EnteringContext, 5478 const ObjCObjectPointerType *OPT) { 5479 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC, 5480 MemberContext, EnteringContext, 5481 OPT, Mode == CTK_ErrorRecovery); 5482 5483 // Give the external sema source a chance to correct the typo. 5484 TypoCorrection ExternalTypo; 5485 if (ExternalSource && Consumer) { 5486 ExternalTypo = ExternalSource->CorrectTypo( 5487 TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(), 5488 MemberContext, EnteringContext, OPT); 5489 if (ExternalTypo) 5490 Consumer->addCorrection(ExternalTypo); 5491 } 5492 5493 if (!Consumer || Consumer->empty()) 5494 return nullptr; 5495 5496 // Make sure the best edit distance (prior to adding any namespace qualifiers) 5497 // is not more that about a third of the length of the typo's identifier. 5498 unsigned ED = Consumer->getBestEditDistance(true); 5499 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); 5500 if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3) 5501 return nullptr; 5502 ExprEvalContexts.back().NumTypos++; 5503 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC), 5504 TypoName.getLoc()); 5505 } 5506 5507 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) { 5508 if (!CDecl) return; 5509 5510 if (isKeyword()) 5511 CorrectionDecls.clear(); 5512 5513 CorrectionDecls.push_back(CDecl); 5514 5515 if (!CorrectionName) 5516 CorrectionName = CDecl->getDeclName(); 5517 } 5518 5519 std::string TypoCorrection::getAsString(const LangOptions &LO) const { 5520 if (CorrectionNameSpec) { 5521 std::string tmpBuffer; 5522 llvm::raw_string_ostream PrefixOStream(tmpBuffer); 5523 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO)); 5524 PrefixOStream << CorrectionName; 5525 return PrefixOStream.str(); 5526 } 5527 5528 return CorrectionName.getAsString(); 5529 } 5530 5531 bool CorrectionCandidateCallback::ValidateCandidate( 5532 const TypoCorrection &candidate) { 5533 if (!candidate.isResolved()) 5534 return true; 5535 5536 if (candidate.isKeyword()) 5537 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts || 5538 WantRemainingKeywords || WantObjCSuper; 5539 5540 bool HasNonType = false; 5541 bool HasStaticMethod = false; 5542 bool HasNonStaticMethod = false; 5543 for (Decl *D : candidate) { 5544 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) 5545 D = FTD->getTemplatedDecl(); 5546 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 5547 if (Method->isStatic()) 5548 HasStaticMethod = true; 5549 else 5550 HasNonStaticMethod = true; 5551 } 5552 if (!isa<TypeDecl>(D)) 5553 HasNonType = true; 5554 } 5555 5556 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod && 5557 !candidate.getCorrectionSpecifier()) 5558 return false; 5559 5560 return WantTypeSpecifiers || HasNonType; 5561 } 5562 5563 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs, 5564 bool HasExplicitTemplateArgs, 5565 MemberExpr *ME) 5566 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs), 5567 CurContext(SemaRef.CurContext), MemberFn(ME) { 5568 WantTypeSpecifiers = false; 5569 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && 5570 !HasExplicitTemplateArgs && NumArgs == 1; 5571 WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1; 5572 WantRemainingKeywords = false; 5573 } 5574 5575 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) { 5576 if (!candidate.getCorrectionDecl()) 5577 return candidate.isKeyword(); 5578 5579 for (auto *C : candidate) { 5580 FunctionDecl *FD = nullptr; 5581 NamedDecl *ND = C->getUnderlyingDecl(); 5582 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 5583 FD = FTD->getTemplatedDecl(); 5584 if (!HasExplicitTemplateArgs && !FD) { 5585 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 5586 // If the Decl is neither a function nor a template function, 5587 // determine if it is a pointer or reference to a function. If so, 5588 // check against the number of arguments expected for the pointee. 5589 QualType ValType = cast<ValueDecl>(ND)->getType(); 5590 if (ValType.isNull()) 5591 continue; 5592 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 5593 ValType = ValType->getPointeeType(); 5594 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 5595 if (FPT->getNumParams() == NumArgs) 5596 return true; 5597 } 5598 } 5599 5600 // A typo for a function-style cast can look like a function call in C++. 5601 if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr 5602 : isa<TypeDecl>(ND)) && 5603 CurContext->getParentASTContext().getLangOpts().CPlusPlus) 5604 // Only a class or class template can take two or more arguments. 5605 return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND); 5606 5607 // Skip the current candidate if it is not a FunctionDecl or does not accept 5608 // the current number of arguments. 5609 if (!FD || !(FD->getNumParams() >= NumArgs && 5610 FD->getMinRequiredArguments() <= NumArgs)) 5611 continue; 5612 5613 // If the current candidate is a non-static C++ method, skip the candidate 5614 // unless the method being corrected--or the current DeclContext, if the 5615 // function being corrected is not a method--is a method in the same class 5616 // or a descendent class of the candidate's parent class. 5617 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 5618 if (MemberFn || !MD->isStatic()) { 5619 const auto *CurMD = 5620 MemberFn 5621 ? dyn_cast_if_present<CXXMethodDecl>(MemberFn->getMemberDecl()) 5622 : dyn_cast_if_present<CXXMethodDecl>(CurContext); 5623 const CXXRecordDecl *CurRD = 5624 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr; 5625 const CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl(); 5626 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD))) 5627 continue; 5628 } 5629 } 5630 return true; 5631 } 5632 return false; 5633 } 5634 5635 void Sema::diagnoseTypo(const TypoCorrection &Correction, 5636 const PartialDiagnostic &TypoDiag, 5637 bool ErrorRecovery) { 5638 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl), 5639 ErrorRecovery); 5640 } 5641 5642 /// Find which declaration we should import to provide the definition of 5643 /// the given declaration. 5644 static const NamedDecl *getDefinitionToImport(const NamedDecl *D) { 5645 if (const auto *VD = dyn_cast<VarDecl>(D)) 5646 return VD->getDefinition(); 5647 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 5648 return FD->getDefinition(); 5649 if (const auto *TD = dyn_cast<TagDecl>(D)) 5650 return TD->getDefinition(); 5651 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) 5652 return ID->getDefinition(); 5653 if (const auto *PD = dyn_cast<ObjCProtocolDecl>(D)) 5654 return PD->getDefinition(); 5655 if (const auto *TD = dyn_cast<TemplateDecl>(D)) 5656 if (const NamedDecl *TTD = TD->getTemplatedDecl()) 5657 return getDefinitionToImport(TTD); 5658 return nullptr; 5659 } 5660 5661 void Sema::diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, 5662 MissingImportKind MIK, bool Recover) { 5663 // Suggest importing a module providing the definition of this entity, if 5664 // possible. 5665 const NamedDecl *Def = getDefinitionToImport(Decl); 5666 if (!Def) 5667 Def = Decl; 5668 5669 Module *Owner = getOwningModule(Def); 5670 assert(Owner && "definition of hidden declaration is not in a module"); 5671 5672 llvm::SmallVector<Module*, 8> OwningModules; 5673 OwningModules.push_back(Owner); 5674 auto Merged = Context.getModulesWithMergedDefinition(Def); 5675 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end()); 5676 5677 diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK, 5678 Recover); 5679 } 5680 5681 /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic 5682 /// suggesting the addition of a #include of the specified file. 5683 static std::string getHeaderNameForHeader(Preprocessor &PP, const FileEntry *E, 5684 llvm::StringRef IncludingFile) { 5685 bool IsSystem = false; 5686 auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics( 5687 E, IncludingFile, &IsSystem); 5688 return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"'); 5689 } 5690 5691 void Sema::diagnoseMissingImport(SourceLocation UseLoc, const NamedDecl *Decl, 5692 SourceLocation DeclLoc, 5693 ArrayRef<Module *> Modules, 5694 MissingImportKind MIK, bool Recover) { 5695 assert(!Modules.empty()); 5696 5697 auto NotePrevious = [&] { 5698 // FIXME: Suppress the note backtrace even under 5699 // -fdiagnostics-show-note-include-stack. We don't care how this 5700 // declaration was previously reached. 5701 Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK; 5702 }; 5703 5704 // Weed out duplicates from module list. 5705 llvm::SmallVector<Module*, 8> UniqueModules; 5706 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet; 5707 for (auto *M : Modules) { 5708 if (M->isGlobalModule() || M->isPrivateModule()) 5709 continue; 5710 if (UniqueModuleSet.insert(M).second) 5711 UniqueModules.push_back(M); 5712 } 5713 5714 // Try to find a suitable header-name to #include. 5715 std::string HeaderName; 5716 if (const FileEntry *Header = 5717 PP.getHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) { 5718 if (const FileEntry *FE = 5719 SourceMgr.getFileEntryForID(SourceMgr.getFileID(UseLoc))) 5720 HeaderName = getHeaderNameForHeader(PP, Header, FE->tryGetRealPathName()); 5721 } 5722 5723 // If we have a #include we should suggest, or if all definition locations 5724 // were in global module fragments, don't suggest an import. 5725 if (!HeaderName.empty() || UniqueModules.empty()) { 5726 // FIXME: Find a smart place to suggest inserting a #include, and add 5727 // a FixItHint there. 5728 Diag(UseLoc, diag::err_module_unimported_use_header) 5729 << (int)MIK << Decl << !HeaderName.empty() << HeaderName; 5730 // Produce a note showing where the entity was declared. 5731 NotePrevious(); 5732 if (Recover) 5733 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]); 5734 return; 5735 } 5736 5737 Modules = UniqueModules; 5738 5739 if (Modules.size() > 1) { 5740 std::string ModuleList; 5741 unsigned N = 0; 5742 for (const auto *M : Modules) { 5743 ModuleList += "\n "; 5744 if (++N == 5 && N != Modules.size()) { 5745 ModuleList += "[...]"; 5746 break; 5747 } 5748 ModuleList += M->getFullModuleName(); 5749 } 5750 5751 Diag(UseLoc, diag::err_module_unimported_use_multiple) 5752 << (int)MIK << Decl << ModuleList; 5753 } else { 5754 // FIXME: Add a FixItHint that imports the corresponding module. 5755 Diag(UseLoc, diag::err_module_unimported_use) 5756 << (int)MIK << Decl << Modules[0]->getFullModuleName(); 5757 } 5758 5759 NotePrevious(); 5760 5761 // Try to recover by implicitly importing this module. 5762 if (Recover) 5763 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]); 5764 } 5765 5766 /// Diagnose a successfully-corrected typo. Separated from the correction 5767 /// itself to allow external validation of the result, etc. 5768 /// 5769 /// \param Correction The result of performing typo correction. 5770 /// \param TypoDiag The diagnostic to produce. This will have the corrected 5771 /// string added to it (and usually also a fixit). 5772 /// \param PrevNote A note to use when indicating the location of the entity to 5773 /// which we are correcting. Will have the correction string added to it. 5774 /// \param ErrorRecovery If \c true (the default), the caller is going to 5775 /// recover from the typo as if the corrected string had been typed. 5776 /// In this case, \c PDiag must be an error, and we will attach a fixit 5777 /// to it. 5778 void Sema::diagnoseTypo(const TypoCorrection &Correction, 5779 const PartialDiagnostic &TypoDiag, 5780 const PartialDiagnostic &PrevNote, 5781 bool ErrorRecovery) { 5782 std::string CorrectedStr = Correction.getAsString(getLangOpts()); 5783 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts()); 5784 FixItHint FixTypo = FixItHint::CreateReplacement( 5785 Correction.getCorrectionRange(), CorrectedStr); 5786 5787 // Maybe we're just missing a module import. 5788 if (Correction.requiresImport()) { 5789 NamedDecl *Decl = Correction.getFoundDecl(); 5790 assert(Decl && "import required but no declaration to import"); 5791 5792 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl, 5793 MissingImportKind::Declaration, ErrorRecovery); 5794 return; 5795 } 5796 5797 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag) 5798 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint()); 5799 5800 NamedDecl *ChosenDecl = 5801 Correction.isKeyword() ? nullptr : Correction.getFoundDecl(); 5802 if (PrevNote.getDiagID() && ChosenDecl) 5803 Diag(ChosenDecl->getLocation(), PrevNote) 5804 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo); 5805 5806 // Add any extra diagnostics. 5807 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics()) 5808 Diag(Correction.getCorrectionRange().getBegin(), PD); 5809 } 5810 5811 TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, 5812 TypoDiagnosticGenerator TDG, 5813 TypoRecoveryCallback TRC, 5814 SourceLocation TypoLoc) { 5815 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer"); 5816 auto TE = new (Context) TypoExpr(Context.DependentTy, TypoLoc); 5817 auto &State = DelayedTypos[TE]; 5818 State.Consumer = std::move(TCC); 5819 State.DiagHandler = std::move(TDG); 5820 State.RecoveryHandler = std::move(TRC); 5821 if (TE) 5822 TypoExprs.push_back(TE); 5823 return TE; 5824 } 5825 5826 const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const { 5827 auto Entry = DelayedTypos.find(TE); 5828 assert(Entry != DelayedTypos.end() && 5829 "Failed to get the state for a TypoExpr!"); 5830 return Entry->second; 5831 } 5832 5833 void Sema::clearDelayedTypo(TypoExpr *TE) { 5834 DelayedTypos.erase(TE); 5835 } 5836 5837 void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) { 5838 DeclarationNameInfo Name(II, IILoc); 5839 LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration); 5840 R.suppressDiagnostics(); 5841 R.setHideTags(false); 5842 LookupName(R, S); 5843 R.dump(); 5844 } 5845 5846 void Sema::ActOnPragmaDump(Expr *E) { 5847 E->dump(); 5848 } 5849