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