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