1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the actions class which performs semantic analysis and
11 // builds an AST out of a parse stream.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Sema/SemaInternal.h"
16 #include "clang/Sema/DelayedDiagnostic.h"
17 #include "TargetAttributesSema.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/APFloat.h"
21 #include "clang/Sema/CXXFieldCollector.h"
22 #include "clang/Sema/TemplateDeduction.h"
23 #include "clang/Sema/ExternalSemaSource.h"
24 #include "clang/Sema/ObjCMethodList.h"
25 #include "clang/Sema/PrettyDeclStackTrace.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "clang/Sema/SemaConsumer.h"
29 #include "clang/AST/ASTContext.h"
30 #include "clang/AST/ASTDiagnostic.h"
31 #include "clang/AST/DeclCXX.h"
32 #include "clang/AST/DeclObjC.h"
33 #include "clang/AST/Expr.h"
34 #include "clang/AST/ExprCXX.h"
35 #include "clang/AST/StmtCXX.h"
36 #include "clang/Lex/Preprocessor.h"
37 #include "clang/Basic/FileManager.h"
38 #include "clang/Basic/PartialDiagnostic.h"
39 #include "clang/Basic/TargetInfo.h"
40 using namespace clang;
43 FunctionScopeInfo::~FunctionScopeInfo() { }
45 void FunctionScopeInfo::Clear() {
46 HasBranchProtectedScope = false;
47 HasBranchIntoScope = false;
48 HasIndirectGoto = false;
53 PossiblyUnreachableDiags.clear();
56 BlockScopeInfo::~BlockScopeInfo() { }
58 PrintingPolicy Sema::getPrintingPolicy() const {
59 PrintingPolicy Policy = Context.getPrintingPolicy();
60 Policy.Bool = getLangOptions().Bool;
62 if (MacroInfo *BoolMacro = PP.getMacroInfo(&Context.Idents.get("bool"))) {
63 Policy.Bool = BoolMacro->isObjectLike() &&
64 BoolMacro->getNumTokens() == 1 &&
65 BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
72 void Sema::ActOnTranslationUnitScope(Scope *S) {
74 PushDeclContext(S, Context.getTranslationUnitDecl());
76 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
78 if (PP.getLangOptions().ObjC1) {
79 // Synthesize "@class Protocol;
80 if (Context.getObjCProtoType().isNull()) {
81 ObjCInterfaceDecl *ProtocolDecl =
82 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
83 &Context.Idents.get("Protocol"),
84 SourceLocation(), true);
85 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
86 PushOnScopeChains(ProtocolDecl, TUScope, false);
91 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
92 TranslationUnitKind TUKind,
93 CodeCompleteConsumer *CodeCompleter)
94 : TheTargetAttributesSema(0), FPFeatures(pp.getLangOptions()),
95 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
96 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
97 CollectStats(false), ExternalSource(0), CodeCompleter(CodeCompleter),
98 CurContext(0), OriginalLexicalContext(0),
99 PackContext(0), MSStructPragmaOn(false), VisContext(0),
100 ExprNeedsCleanups(0), LateTemplateParser(0), OpaqueParser(0),
101 IdResolver(pp.getLangOptions()), CXXTypeInfoDecl(0), MSVCGuidDecl(0),
102 GlobalNewDeleteDeclared(false),
103 ObjCShouldCallSuperDealloc(false),
104 ObjCShouldCallSuperFinalize(false),
106 NumSFINAEErrors(0), SuppressAccessChecking(false),
107 AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
108 NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
109 CurrentInstantiationScope(0), TyposCorrected(0),
110 AnalysisWarnings(*this)
113 LoadedExternalKnownNamespaces = false;
115 if (getLangOptions().CPlusPlus)
116 FieldCollector.reset(new CXXFieldCollector());
118 // Tell diagnostics how to render things from the AST library.
119 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
122 ExprEvalContexts.push_back(
123 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0, false));
125 FunctionScopes.push_back(new FunctionScopeInfo(Diags));
128 void Sema::Initialize() {
129 // Tell the AST consumer about this Sema object.
130 Consumer.Initialize(Context);
132 // FIXME: Isn't this redundant with the initialization above?
133 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
134 SC->InitializeSema(*this);
136 // Tell the external Sema source about this Sema object.
137 if (ExternalSemaSource *ExternalSema
138 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
139 ExternalSema->InitializeSema(*this);
141 // Initialize predefined 128-bit integer types, if needed.
142 if (PP.getTargetInfo().getPointerWidth(0) >= 64) {
143 // If either of the 128-bit integer types are unavailable to name lookup,
145 DeclarationName Int128 = &Context.Idents.get("__int128_t");
146 if (IdentifierResolver::begin(Int128) == IdentifierResolver::end())
147 PushOnScopeChains(Context.getInt128Decl(), TUScope);
149 DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
150 if (IdentifierResolver::begin(UInt128) == IdentifierResolver::end())
151 PushOnScopeChains(Context.getUInt128Decl(), TUScope);
155 // Initialize predefined Objective-C types:
156 if (PP.getLangOptions().ObjC1) {
157 // If 'SEL' does not yet refer to any declarations, make it refer to the
159 DeclarationName SEL = &Context.Idents.get("SEL");
160 if (IdentifierResolver::begin(SEL) == IdentifierResolver::end())
161 PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
163 // If 'id' does not yet refer to any declarations, make it refer to the
165 DeclarationName Id = &Context.Idents.get("id");
166 if (IdentifierResolver::begin(Id) == IdentifierResolver::end())
167 PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
169 // Create the built-in typedef for 'Class'.
170 DeclarationName Class = &Context.Idents.get("Class");
171 if (IdentifierResolver::begin(Class) == IdentifierResolver::end())
172 PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
177 if (PackContext) FreePackedContext();
178 if (VisContext) FreeVisContext();
179 delete TheTargetAttributesSema;
180 MSStructPragmaOn = false;
181 // Kill all the active scopes.
182 for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
183 delete FunctionScopes[I];
184 if (FunctionScopes.size() == 1)
185 delete FunctionScopes[0];
187 // Tell the SemaConsumer to forget about us; we're going out of scope.
188 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
191 // Detach from the external Sema source.
192 if (ExternalSemaSource *ExternalSema
193 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
194 ExternalSema->ForgetSema();
198 /// makeUnavailableInSystemHeader - There is an error in the current
199 /// context. If we're still in a system header, and we can plausibly
200 /// make the relevant declaration unavailable instead of erroring, do
201 /// so and return true.
202 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
204 // If we're not in a function, it's an error.
205 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
206 if (!fn) return false;
208 // If we're in template instantiation, it's an error.
209 if (!ActiveTemplateInstantiations.empty())
212 // If that function's not in a system header, it's an error.
213 if (!Context.getSourceManager().isInSystemHeader(loc))
216 // If the function is already unavailable, it's not an error.
217 if (fn->hasAttr<UnavailableAttr>()) return true;
219 fn->addAttr(new (Context) UnavailableAttr(loc, Context, msg));
223 ASTMutationListener *Sema::getASTMutationListener() const {
224 return getASTConsumer().GetASTMutationListener();
227 /// \brief Print out statistics about the semantic analysis.
228 void Sema::PrintStats() const {
229 llvm::errs() << "\n*** Semantic Analysis Stats:\n";
230 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
232 BumpAlloc.PrintStats();
233 AnalysisWarnings.PrintStats();
236 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
237 /// If there is already an implicit cast, merge into the existing one.
238 /// The result is of the given category.
239 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
240 CastKind Kind, ExprValueKind VK,
241 const CXXCastPath *BasePath,
242 CheckedConversionKind CCK) {
243 QualType ExprTy = Context.getCanonicalType(E->getType());
244 QualType TypeTy = Context.getCanonicalType(Ty);
246 if (ExprTy == TypeTy)
249 if (getLangOptions().ObjCAutoRefCount)
250 CheckObjCARCConversion(SourceRange(), Ty, E, CCK);
252 // If this is a derived-to-base cast to a through a virtual base, we
254 if (Kind == CK_DerivedToBase &&
255 BasePathInvolvesVirtualBase(*BasePath)) {
256 QualType T = E->getType();
257 if (const PointerType *Pointer = T->getAs<PointerType>())
258 T = Pointer->getPointeeType();
259 if (const RecordType *RecordTy = T->getAs<RecordType>())
260 MarkVTableUsed(E->getLocStart(),
261 cast<CXXRecordDecl>(RecordTy->getDecl()));
264 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
265 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
266 ImpCast->setType(Ty);
267 ImpCast->setValueKind(VK);
272 return Owned(ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK));
275 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
276 /// to the conversion from scalar type ScalarTy to the Boolean type.
277 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
278 switch (ScalarTy->getScalarTypeKind()) {
279 case Type::STK_Bool: return CK_NoOp;
280 case Type::STK_CPointer: return CK_PointerToBoolean;
281 case Type::STK_BlockPointer: return CK_PointerToBoolean;
282 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
283 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
284 case Type::STK_Integral: return CK_IntegralToBoolean;
285 case Type::STK_Floating: return CK_FloatingToBoolean;
286 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
287 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
292 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
293 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
297 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
298 // UnusedFileScopedDecls stores the first declaration.
299 // The declaration may have become definition so check again.
300 const FunctionDecl *DeclToCheck;
301 if (FD->hasBody(DeclToCheck))
302 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
304 // Later redecls may add new information resulting in not having to warn,
306 DeclToCheck = FD->getMostRecentDeclaration();
307 if (DeclToCheck != FD)
308 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
311 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
312 // UnusedFileScopedDecls stores the first declaration.
313 // The declaration may have become definition so check again.
314 const VarDecl *DeclToCheck = VD->getDefinition();
316 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
318 // Later redecls may add new information resulting in not having to warn,
320 DeclToCheck = VD->getMostRecentDeclaration();
321 if (DeclToCheck != VD)
322 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
329 struct UndefinedInternal {
331 FullSourceLoc useLoc;
333 UndefinedInternal(NamedDecl *decl, FullSourceLoc useLoc)
334 : decl(decl), useLoc(useLoc) {}
337 bool operator<(const UndefinedInternal &l, const UndefinedInternal &r) {
338 return l.useLoc.isBeforeInTranslationUnitThan(r.useLoc);
342 /// checkUndefinedInternals - Check for undefined objects with internal linkage.
343 static void checkUndefinedInternals(Sema &S) {
344 if (S.UndefinedInternals.empty()) return;
346 // Collect all the still-undefined entities with internal linkage.
347 SmallVector<UndefinedInternal, 16> undefined;
348 for (llvm::DenseMap<NamedDecl*,SourceLocation>::iterator
349 i = S.UndefinedInternals.begin(), e = S.UndefinedInternals.end();
351 NamedDecl *decl = i->first;
353 // Ignore attributes that have become invalid.
354 if (decl->isInvalidDecl()) continue;
356 // __attribute__((weakref)) is basically a definition.
357 if (decl->hasAttr<WeakRefAttr>()) continue;
359 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
360 if (fn->isPure() || fn->hasBody())
363 if (cast<VarDecl>(decl)->hasDefinition() != VarDecl::DeclarationOnly)
367 // We build a FullSourceLoc so that we can sort with array_pod_sort.
368 FullSourceLoc loc(i->second, S.Context.getSourceManager());
369 undefined.push_back(UndefinedInternal(decl, loc));
372 if (undefined.empty()) return;
374 // Sort (in order of use site) so that we're not (as) dependent on
375 // the iteration order through an llvm::DenseMap.
376 llvm::array_pod_sort(undefined.begin(), undefined.end());
378 for (SmallVectorImpl<UndefinedInternal>::iterator
379 i = undefined.begin(), e = undefined.end(); i != e; ++i) {
380 NamedDecl *decl = i->decl;
381 S.Diag(decl->getLocation(), diag::warn_undefined_internal)
382 << isa<VarDecl>(decl) << decl;
383 S.Diag(i->useLoc, diag::note_used_here);
387 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
391 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
392 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
393 for (unsigned I = 0, N = WeakIDs.size(); I != N; ++I) {
394 llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator Pos
395 = WeakUndeclaredIdentifiers.find(WeakIDs[I].first);
396 if (Pos != WeakUndeclaredIdentifiers.end())
399 WeakUndeclaredIdentifiers.insert(WeakIDs[I]);
403 /// ActOnEndOfTranslationUnit - This is called at the very end of the
404 /// translation unit when EOF is reached and all but the top-level scope is
406 void Sema::ActOnEndOfTranslationUnit() {
407 // Only complete translation units define vtables and perform implicit
409 if (TUKind == TU_Complete) {
410 // If any dynamic classes have their key function defined within
411 // this translation unit, then those vtables are considered "used" and must
413 for (DynamicClassesType::iterator I = DynamicClasses.begin(ExternalSource),
414 E = DynamicClasses.end();
416 assert(!(*I)->isDependentType() &&
417 "Should not see dependent types here!");
418 if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(*I)) {
419 const FunctionDecl *Definition = 0;
420 if (KeyFunction->hasBody(Definition))
421 MarkVTableUsed(Definition->getLocation(), *I, true);
425 // If DefinedUsedVTables ends up marking any virtual member functions it
426 // might lead to more pending template instantiations, which we then need
430 // C++: Perform implicit template instantiations.
432 // FIXME: When we perform these implicit instantiations, we do not
433 // carefully keep track of the point of instantiation (C++ [temp.point]).
434 // This means that name lookup that occurs within the template
435 // instantiation will always happen at the end of the translation unit,
436 // so it will find some names that should not be found. Although this is
437 // common behavior for C++ compilers, it is technically wrong. In the
438 // future, we either need to be able to filter the results of name lookup
439 // or we need to perform template instantiations earlier.
440 PerformPendingInstantiations();
443 // Remove file scoped decls that turned out to be used.
444 UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(0,
446 UnusedFileScopedDecls.end(),
447 std::bind1st(std::ptr_fun(ShouldRemoveFromUnused),
449 UnusedFileScopedDecls.end());
451 if (TUKind == TU_Prefix) {
452 // Translation unit prefixes don't need any of the checking below.
457 // Check for #pragma weak identifiers that were never declared
458 // FIXME: This will cause diagnostics to be emitted in a non-determinstic
459 // order! Iterating over a densemap like this is bad.
460 LoadExternalWeakUndeclaredIdentifiers();
461 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
462 I = WeakUndeclaredIdentifiers.begin(),
463 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
464 if (I->second.getUsed()) continue;
466 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
470 if (TUKind == TU_Module) {
471 // Mark any macros from system headers (in /usr/include) as exported, along
472 // with our own Clang headers.
473 // FIXME: This is a gross hack to deal with the fact that system headers
474 // are #include'd in many places within module headers, but are not
475 // themselves modularized. This doesn't actually work, but it lets us
476 // focus on other issues for the moment.
477 for (Preprocessor::macro_iterator M = PP.macro_begin(false),
478 MEnd = PP.macro_end(false);
481 !M->second->isExported() &&
482 !M->second->isBuiltinMacro()) {
483 SourceLocation Loc = M->second->getDefinitionLoc();
484 if (SourceMgr.isInSystemHeader(Loc)) {
485 const FileEntry *File
486 = SourceMgr.getFileEntryForID(SourceMgr.getFileID(Loc));
488 ((StringRef(File->getName()).find("lib/clang")
489 != StringRef::npos) ||
490 (StringRef(File->getName()).find("usr/include")
491 != StringRef::npos) ||
492 (StringRef(File->getName()).find("usr/local/include")
493 != StringRef::npos)))
494 M->second->setExportLocation(Loc);
499 // Modules don't need any of the checking below.
505 // A declaration of an identifier for an object that has file
506 // scope without an initializer, and without a storage-class
507 // specifier or with the storage-class specifier static,
508 // constitutes a tentative definition. If a translation unit
509 // contains one or more tentative definitions for an identifier,
510 // and the translation unit contains no external definition for
511 // that identifier, then the behavior is exactly as if the
512 // translation unit contains a file scope declaration of that
513 // identifier, with the composite type as of the end of the
514 // translation unit, with an initializer equal to 0.
515 llvm::SmallSet<VarDecl *, 32> Seen;
516 for (TentativeDefinitionsType::iterator
517 T = TentativeDefinitions.begin(ExternalSource),
518 TEnd = TentativeDefinitions.end();
521 VarDecl *VD = (*T)->getActingDefinition();
523 // If the tentative definition was completed, getActingDefinition() returns
524 // null. If we've already seen this variable before, insert()'s second
525 // return value is false.
526 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
529 if (const IncompleteArrayType *ArrayT
530 = Context.getAsIncompleteArrayType(VD->getType())) {
531 if (RequireCompleteType(VD->getLocation(),
532 ArrayT->getElementType(),
533 diag::err_tentative_def_incomplete_type_arr)) {
534 VD->setInvalidDecl();
538 // Set the length of the array to 1 (C99 6.9.2p5).
539 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
540 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
541 QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
542 One, ArrayType::Normal, 0);
544 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
545 diag::err_tentative_def_incomplete_type))
546 VD->setInvalidDecl();
548 // Notify the consumer that we've completed a tentative definition.
549 if (!VD->isInvalidDecl())
550 Consumer.CompleteTentativeDefinition(VD);
554 if (LangOpts.CPlusPlus0x &&
555 Diags.getDiagnosticLevel(diag::warn_delegating_ctor_cycle,
557 != DiagnosticsEngine::Ignored)
558 CheckDelegatingCtorCycles();
560 // If there were errors, disable 'unused' warnings since they will mostly be
562 if (!Diags.hasErrorOccurred()) {
563 // Output warning for unused file scoped decls.
564 for (UnusedFileScopedDeclsType::iterator
565 I = UnusedFileScopedDecls.begin(ExternalSource),
566 E = UnusedFileScopedDecls.end(); I != E; ++I) {
567 if (ShouldRemoveFromUnused(this, *I))
570 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
571 const FunctionDecl *DiagD;
572 if (!FD->hasBody(DiagD))
574 if (DiagD->isDeleted())
575 continue; // Deleted functions are supposed to be unused.
576 if (DiagD->isReferenced()) {
577 if (isa<CXXMethodDecl>(DiagD))
578 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
579 << DiagD->getDeclName();
581 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
582 << /*function*/0 << DiagD->getDeclName();
584 Diag(DiagD->getLocation(),
585 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
586 : diag::warn_unused_function)
587 << DiagD->getDeclName();
590 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
592 DiagD = cast<VarDecl>(*I);
593 if (DiagD->isReferenced()) {
594 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
595 << /*variable*/1 << DiagD->getDeclName();
597 Diag(DiagD->getLocation(), diag::warn_unused_variable)
598 << DiagD->getDeclName();
603 checkUndefinedInternals(*this);
606 // Check we've noticed that we're no longer parsing the initializer for every
607 // variable. If we miss cases, then at best we have a performance issue and
608 // at worst a rejects-valid bug.
609 assert(ParsingInitForAutoVars.empty() &&
610 "Didn't unmark var as having its initializer parsed");
616 //===----------------------------------------------------------------------===//
618 //===----------------------------------------------------------------------===//
620 DeclContext *Sema::getFunctionLevelDeclContext() {
621 DeclContext *DC = CurContext;
623 while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC))
624 DC = DC->getParent();
629 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
630 /// to the function decl for the function being parsed. If we're currently
631 /// in a 'block', this returns the containing context.
632 FunctionDecl *Sema::getCurFunctionDecl() {
633 DeclContext *DC = getFunctionLevelDeclContext();
634 return dyn_cast<FunctionDecl>(DC);
637 ObjCMethodDecl *Sema::getCurMethodDecl() {
638 DeclContext *DC = getFunctionLevelDeclContext();
639 return dyn_cast<ObjCMethodDecl>(DC);
642 NamedDecl *Sema::getCurFunctionOrMethodDecl() {
643 DeclContext *DC = getFunctionLevelDeclContext();
644 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
645 return cast<NamedDecl>(DC);
649 Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
653 if (llvm::Optional<TemplateDeductionInfo*> Info = SemaRef.isSFINAEContext()) {
654 switch (DiagnosticIDs::getDiagnosticSFINAEResponse(getDiagID())) {
655 case DiagnosticIDs::SFINAE_Report:
656 // Fall through; we'll report the diagnostic below.
659 case DiagnosticIDs::SFINAE_AccessControl:
660 // Per C++ Core Issue 1170, access control is part of SFINAE.
661 // Additionally, the AccessCheckingSFINAE flag can be used to temporary
662 // make access control a part of SFINAE for the purposes of checking
664 if (!SemaRef.AccessCheckingSFINAE &&
665 !SemaRef.getLangOptions().CPlusPlus0x)
668 case DiagnosticIDs::SFINAE_SubstitutionFailure:
669 // Count this failure so that we know that template argument deduction
671 ++SemaRef.NumSFINAEErrors;
672 SemaRef.Diags.setLastDiagnosticIgnored();
673 SemaRef.Diags.Clear();
677 case DiagnosticIDs::SFINAE_Suppress:
678 // Make a copy of this suppressed diagnostic and store it with the
679 // template-deduction information;
681 Diagnostic DiagInfo(&SemaRef.Diags);
684 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
685 PartialDiagnostic(DiagInfo,
686 SemaRef.Context.getDiagAllocator()));
688 // Suppress this diagnostic.
689 SemaRef.Diags.setLastDiagnosticIgnored();
690 SemaRef.Diags.Clear();
696 // Set up the context's printing policy based on our current state.
697 SemaRef.Context.setPrintingPolicy(SemaRef.getPrintingPolicy());
699 // Emit the diagnostic.
703 // If this is not a note, and we're in a template instantiation
704 // that is different from the last template instantiation where
705 // we emitted an error, print a template instantiation
707 if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
708 !SemaRef.ActiveTemplateInstantiations.empty() &&
709 SemaRef.ActiveTemplateInstantiations.back()
710 != SemaRef.LastTemplateInstantiationErrorContext) {
711 SemaRef.PrintInstantiationStack();
712 SemaRef.LastTemplateInstantiationErrorContext
713 = SemaRef.ActiveTemplateInstantiations.back();
717 Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
718 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
719 return SemaDiagnosticBuilder(DB, *this, DiagID);
722 Sema::SemaDiagnosticBuilder
723 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
724 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
730 /// \brief Looks through the macro-expansion chain for the given
731 /// location, looking for a macro expansion with the given name.
732 /// If one is found, returns true and sets the location to that
734 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
735 SourceLocation loc = locref;
736 if (!loc.isMacroID()) return false;
738 // There's no good way right now to look at the intermediate
739 // expansions, so just jump to the expansion location.
740 loc = getSourceManager().getExpansionLoc(loc);
742 // If that's written with the name, stop here.
743 SmallVector<char, 16> buffer;
744 if (getPreprocessor().getSpelling(loc, buffer) == name) {
751 /// \brief Determines the active Scope associated with the given declaration
754 /// This routine maps a declaration context to the active Scope object that
755 /// represents that declaration context in the parser. It is typically used
756 /// from "scope-less" code (e.g., template instantiation, lazy creation of
757 /// declarations) that injects a name for name-lookup purposes and, therefore,
758 /// must update the Scope.
760 /// \returns The scope corresponding to the given declaraion context, or NULL
761 /// if no such scope is open.
762 Scope *Sema::getScopeForContext(DeclContext *Ctx) {
767 Ctx = Ctx->getPrimaryContext();
768 for (Scope *S = getCurScope(); S; S = S->getParent()) {
769 // Ignore scopes that cannot have declarations. This is important for
770 // out-of-line definitions of static class members.
771 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
772 if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
773 if (Ctx == Entity->getPrimaryContext())
780 /// \brief Enter a new function scope
781 void Sema::PushFunctionScope() {
782 if (FunctionScopes.size() == 1) {
783 // Use the "top" function scope rather than having to allocate
784 // memory for a new scope.
785 FunctionScopes.back()->Clear();
786 FunctionScopes.push_back(FunctionScopes.back());
790 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
793 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
794 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
798 void Sema::PopFunctionOrBlockScope(const AnalysisBasedWarnings::Policy *WP,
799 const Decl *D, const BlockExpr *blkExpr) {
800 FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
801 assert(!FunctionScopes.empty() && "mismatched push/pop!");
803 // Issue any analysis-based warnings.
805 AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
807 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
808 i = Scope->PossiblyUnreachableDiags.begin(),
809 e = Scope->PossiblyUnreachableDiags.end();
811 const sema::PossiblyUnreachableDiag &D = *i;
816 if (FunctionScopes.back() != Scope) {
821 /// \brief Determine whether any errors occurred within this function/method/
823 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
824 return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
827 BlockScopeInfo *Sema::getCurBlock() {
828 if (FunctionScopes.empty())
831 return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
834 // Pin this vtable to this file.
835 ExternalSemaSource::~ExternalSemaSource() {}
837 std::pair<ObjCMethodList, ObjCMethodList>
838 ExternalSemaSource::ReadMethodPool(Selector Sel) {
839 return std::pair<ObjCMethodList, ObjCMethodList>();
842 void ExternalSemaSource::ReadKnownNamespaces(
843 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
846 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
847 SourceLocation Loc = this->Loc;
848 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
850 Loc.print(OS, S.getSourceManager());
855 if (TheDecl && isa<NamedDecl>(TheDecl)) {
856 std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
858 OS << " '" << Name << '\'';
864 /// \brief Figure out if an expression could be turned into a call.
866 /// Use this when trying to recover from an error where the programmer may have
867 /// written just the name of a function instead of actually calling it.
869 /// \param E - The expression to examine.
870 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
871 /// with no arguments, this parameter is set to the type returned by such a
872 /// call; otherwise, it is set to an empty QualType.
873 /// \param OverloadSet - If the expression is an overloaded function
874 /// name, this parameter is populated with the decls of the various overloads.
875 bool Sema::isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy,
876 UnresolvedSetImpl &OverloadSet) {
877 ZeroArgCallReturnTy = QualType();
880 if (E.getType() == Context.OverloadTy) {
881 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
882 const OverloadExpr *Overloads = FR.Expression;
884 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
885 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
886 OverloadSet.addDecl(*it);
888 // Check whether the function is a non-template which takes no
890 if (const FunctionDecl *OverloadDecl
891 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
892 if (OverloadDecl->getMinRequiredArguments() == 0)
893 ZeroArgCallReturnTy = OverloadDecl->getResultType();
897 // Ignore overloads that are pointer-to-member constants.
898 if (FR.HasFormOfMemberPointer)
904 if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
905 if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
906 if (Fun->getMinRequiredArguments() == 0)
907 ZeroArgCallReturnTy = Fun->getResultType();
912 // We don't have an expression that's convenient to get a FunctionDecl from,
913 // but we can at least check if the type is "function of 0 arguments".
914 QualType ExprTy = E.getType();
915 const FunctionType *FunTy = NULL;
916 QualType PointeeTy = ExprTy->getPointeeType();
917 if (!PointeeTy.isNull())
918 FunTy = PointeeTy->getAs<FunctionType>();
920 FunTy = ExprTy->getAs<FunctionType>();
921 if (!FunTy && ExprTy == Context.BoundMemberTy) {
922 // Look for the bound-member type. If it's still overloaded, give up,
923 // although we probably should have fallen into the OverloadExpr case above
924 // if we actually have an overloaded bound member.
925 QualType BoundMemberTy = Expr::findBoundMemberType(&E);
926 if (!BoundMemberTy.isNull())
927 FunTy = BoundMemberTy->castAs<FunctionType>();
930 if (const FunctionProtoType *FPT =
931 dyn_cast_or_null<FunctionProtoType>(FunTy)) {
932 if (FPT->getNumArgs() == 0)
933 ZeroArgCallReturnTy = FunTy->getResultType();
939 /// \brief Give notes for a set of overloads.
941 /// A companion to isExprCallable. In cases when the name that the programmer
942 /// wrote was an overloaded function, we may be able to make some guesses about
943 /// plausible overloads based on their return types; such guesses can be handed
944 /// off to this method to be emitted as notes.
946 /// \param Overloads - The overloads to note.
947 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
948 /// -fshow-overloads=best, this is the location to attach to the note about too
949 /// many candidates. Typically this will be the location of the original
950 /// ill-formed expression.
951 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
952 const SourceLocation FinalNoteLoc) {
953 int ShownOverloads = 0;
954 int SuppressedOverloads = 0;
955 for (UnresolvedSetImpl::iterator It = Overloads.begin(),
956 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
957 // FIXME: Magic number for max shown overloads stolen from
958 // OverloadCandidateSet::NoteCandidates.
959 if (ShownOverloads >= 4 &&
960 S.Diags.getShowOverloads() == DiagnosticsEngine::Ovl_Best) {
961 ++SuppressedOverloads;
965 NamedDecl *Fn = (*It)->getUnderlyingDecl();
966 S.Diag(Fn->getLocStart(), diag::note_possible_target_of_call);
970 if (SuppressedOverloads)
971 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
972 << SuppressedOverloads;
975 static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
976 const UnresolvedSetImpl &Overloads,
977 bool (*IsPlausibleResult)(QualType)) {
978 if (!IsPlausibleResult)
979 return noteOverloads(S, Overloads, Loc);
981 UnresolvedSet<2> PlausibleOverloads;
982 for (OverloadExpr::decls_iterator It = Overloads.begin(),
983 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
984 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
985 QualType OverloadResultTy = OverloadDecl->getResultType();
986 if (IsPlausibleResult(OverloadResultTy))
987 PlausibleOverloads.addDecl(It.getDecl());
989 noteOverloads(S, PlausibleOverloads, Loc);
992 /// Determine whether the given expression can be called by just
993 /// putting parentheses after it. Notably, expressions with unary
994 /// operators can't be because the unary operator will start parsing
995 /// outside the call.
996 static bool IsCallableWithAppend(Expr *E) {
997 E = E->IgnoreImplicit();
998 return (!isa<CStyleCastExpr>(E) &&
999 !isa<UnaryOperator>(E) &&
1000 !isa<BinaryOperator>(E) &&
1001 !isa<CXXOperatorCallExpr>(E));
1004 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1006 bool (*IsPlausibleResult)(QualType)) {
1007 SourceLocation Loc = E.get()->getExprLoc();
1008 SourceRange Range = E.get()->getSourceRange();
1010 QualType ZeroArgCallTy;
1011 UnresolvedSet<4> Overloads;
1012 if (isExprCallable(*E.get(), ZeroArgCallTy, Overloads) &&
1013 !ZeroArgCallTy.isNull() &&
1014 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
1015 // At this point, we know E is potentially callable with 0
1016 // arguments and that it returns something of a reasonable type,
1017 // so we can emit a fixit and carry on pretending that E was
1018 // actually a CallExpr.
1019 SourceLocation ParenInsertionLoc =
1020 PP.getLocForEndOfToken(Range.getEnd());
1022 << /*zero-arg*/ 1 << Range
1023 << (IsCallableWithAppend(E.get())
1024 ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
1026 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1028 // FIXME: Try this before emitting the fixit, and suppress diagnostics
1030 E = ActOnCallExpr(0, E.take(), ParenInsertionLoc,
1031 MultiExprArg(*this, 0, 0),
1032 ParenInsertionLoc.getLocWithOffset(1));
1036 if (!ForceComplain) return false;
1038 Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
1039 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);