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