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