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