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/AST/ASTContext.h"
17 #include "clang/AST/ASTDiagnostic.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclFriend.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/StmtCXX.h"
24 #include "clang/Basic/DiagnosticOptions.h"
25 #include "clang/Basic/FileManager.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/HeaderSearch.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/CXXFieldCollector.h"
31 #include "clang/Sema/DelayedDiagnostic.h"
32 #include "clang/Sema/ExternalSemaSource.h"
33 #include "clang/Sema/MultiplexExternalSemaSource.h"
34 #include "clang/Sema/ObjCMethodList.h"
35 #include "clang/Sema/PrettyDeclStackTrace.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaConsumer.h"
39 #include "clang/Sema/TemplateDeduction.h"
40 #include "llvm/ADT/APFloat.h"
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/SmallSet.h"
43 using namespace clang;
46 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
47 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
50 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
52 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
53 const Preprocessor &PP) {
54 PrintingPolicy Policy = Context.getPrintingPolicy();
55 // Our printing policy is copied over the ASTContext printing policy whenever
56 // a diagnostic is emitted, so recompute it.
57 Policy.Bool = Context.getLangOpts().Bool;
59 if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
60 Policy.Bool = BoolMacro->isObjectLike() &&
61 BoolMacro->getNumTokens() == 1 &&
62 BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
69 void Sema::ActOnTranslationUnitScope(Scope *S) {
71 PushDeclContext(S, Context.getTranslationUnitDecl());
74 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
75 TranslationUnitKind TUKind,
76 CodeCompleteConsumer *CodeCompleter)
77 : ExternalSource(nullptr),
78 isMultiplexExternalSource(false), FPFeatures(pp.getLangOpts()),
79 LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer),
80 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
81 CollectStats(false), CodeCompleter(CodeCompleter),
82 CurContext(nullptr), OriginalLexicalContext(nullptr),
83 MSStructPragmaOn(false),
84 MSPointerToMemberRepresentationMethod(
85 LangOpts.getMSPointerToMemberRepresentationMethod()),
86 VtorDispStack(MSVtorDispAttr::Mode(LangOpts.VtorDispMode)),
87 PackStack(0), DataSegStack(nullptr), BSSSegStack(nullptr),
88 ConstSegStack(nullptr), CodeSegStack(nullptr), CurInitSeg(nullptr),
90 IsBuildingRecoveryCallExpr(false),
91 Cleanup{}, LateTemplateParser(nullptr),
92 LateTemplateParserCleanup(nullptr),
93 OpaqueParser(nullptr), IdResolver(pp), StdInitializerList(nullptr),
94 CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr),
95 NSNumberDecl(nullptr), NSValueDecl(nullptr),
96 NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
97 ValueWithBytesObjCTypeMethod(nullptr),
98 NSArrayDecl(nullptr), ArrayWithObjectsMethod(nullptr),
99 NSDictionaryDecl(nullptr), DictionaryWithObjectsMethod(nullptr),
100 MSAsmLabelNameCounter(0),
101 GlobalNewDeleteDeclared(false),
104 CachedFakeTopLevelModule(nullptr),
105 AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
106 NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
107 CurrentInstantiationScope(nullptr), DisableTypoCorrection(false),
108 TyposCorrected(0), AnalysisWarnings(*this), ThreadSafetyDeclCache(nullptr),
109 VarDataSharingAttributesStack(nullptr), CurScope(nullptr),
110 Ident_super(nullptr), Ident___float128(nullptr)
114 LoadedExternalKnownNamespaces = false;
115 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
116 NSNumberLiteralMethods[I] = nullptr;
118 if (getLangOpts().ObjC1)
119 NSAPIObj.reset(new NSAPI(Context));
121 if (getLangOpts().CPlusPlus)
122 FieldCollector.reset(new CXXFieldCollector());
124 // Tell diagnostics how to render things from the AST library.
125 Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
127 ExprEvalContexts.emplace_back(PotentiallyEvaluated, 0, CleanupInfo{}, nullptr,
130 FunctionScopes.push_back(new FunctionScopeInfo(Diags));
132 // Initilization of data sharing attributes stack for OpenMP
133 InitDataSharingAttributesStack();
136 void Sema::addImplicitTypedef(StringRef Name, QualType T) {
137 DeclarationName DN = &Context.Idents.get(Name);
138 if (IdResolver.begin(DN) == IdResolver.end())
139 PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
142 void Sema::Initialize() {
143 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
144 SC->InitializeSema(*this);
146 // Tell the external Sema source about this Sema object.
147 if (ExternalSemaSource *ExternalSema
148 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
149 ExternalSema->InitializeSema(*this);
151 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
152 // will not be able to merge any duplicate __va_list_tag decls correctly.
153 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
158 // Initialize predefined 128-bit integer types, if needed.
159 if (Context.getTargetInfo().hasInt128Type()) {
160 // If either of the 128-bit integer types are unavailable to name lookup,
162 DeclarationName Int128 = &Context.Idents.get("__int128_t");
163 if (IdResolver.begin(Int128) == IdResolver.end())
164 PushOnScopeChains(Context.getInt128Decl(), TUScope);
166 DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
167 if (IdResolver.begin(UInt128) == IdResolver.end())
168 PushOnScopeChains(Context.getUInt128Decl(), TUScope);
172 // Initialize predefined Objective-C types:
173 if (getLangOpts().ObjC1) {
174 // If 'SEL' does not yet refer to any declarations, make it refer to the
176 DeclarationName SEL = &Context.Idents.get("SEL");
177 if (IdResolver.begin(SEL) == IdResolver.end())
178 PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
180 // If 'id' does not yet refer to any declarations, make it refer to the
182 DeclarationName Id = &Context.Idents.get("id");
183 if (IdResolver.begin(Id) == IdResolver.end())
184 PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
186 // Create the built-in typedef for 'Class'.
187 DeclarationName Class = &Context.Idents.get("Class");
188 if (IdResolver.begin(Class) == IdResolver.end())
189 PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
191 // Create the built-in forward declaratino for 'Protocol'.
192 DeclarationName Protocol = &Context.Idents.get("Protocol");
193 if (IdResolver.begin(Protocol) == IdResolver.end())
194 PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
197 // Create the internal type for the *StringMakeConstantString builtins.
198 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
199 if (IdResolver.begin(ConstantString) == IdResolver.end())
200 PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
202 // Initialize Microsoft "predefined C++ types".
203 if (getLangOpts().MSVCCompat) {
204 if (getLangOpts().CPlusPlus &&
205 IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
206 PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
209 addImplicitTypedef("size_t", Context.getSizeType());
212 // Initialize predefined OpenCL types and supported optional core features.
213 if (getLangOpts().OpenCL) {
214 #define OPENCLEXT(Ext) \
215 if (Context.getTargetInfo().getSupportedOpenCLOpts().is_##Ext##_supported_core( \
216 getLangOpts().OpenCLVersion)) \
217 getOpenCLOptions().Ext = 1;
218 #include "clang/Basic/OpenCLExtensions.def"
220 addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
221 addImplicitTypedef("event_t", Context.OCLEventTy);
222 if (getLangOpts().OpenCLVersion >= 200) {
223 addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
224 addImplicitTypedef("queue_t", Context.OCLQueueTy);
225 addImplicitTypedef("ndrange_t", Context.OCLNDRangeTy);
226 addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
227 addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
228 addImplicitTypedef("atomic_uint",
229 Context.getAtomicType(Context.UnsignedIntTy));
230 addImplicitTypedef("atomic_long", Context.getAtomicType(Context.LongTy));
231 addImplicitTypedef("atomic_ulong",
232 Context.getAtomicType(Context.UnsignedLongTy));
233 addImplicitTypedef("atomic_float",
234 Context.getAtomicType(Context.FloatTy));
235 addImplicitTypedef("atomic_double",
236 Context.getAtomicType(Context.DoubleTy));
237 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
238 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
239 addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
240 addImplicitTypedef("atomic_intptr_t",
241 Context.getAtomicType(Context.getIntPtrType()));
242 addImplicitTypedef("atomic_uintptr_t",
243 Context.getAtomicType(Context.getUIntPtrType()));
244 addImplicitTypedef("atomic_size_t",
245 Context.getAtomicType(Context.getSizeType()));
246 addImplicitTypedef("atomic_ptrdiff_t",
247 Context.getAtomicType(Context.getPointerDiffType()));
251 if (Context.getTargetInfo().hasBuiltinMSVaList()) {
252 DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
253 if (IdResolver.begin(MSVaList) == IdResolver.end())
254 PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
257 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
258 if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
259 PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
263 llvm::DeleteContainerSeconds(LateParsedTemplateMap);
264 if (VisContext) FreeVisContext();
265 // Kill all the active scopes.
266 for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
267 delete FunctionScopes[I];
268 if (FunctionScopes.size() == 1)
269 delete FunctionScopes[0];
271 // Tell the SemaConsumer to forget about us; we're going out of scope.
272 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
275 // Detach from the external Sema source.
276 if (ExternalSemaSource *ExternalSema
277 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
278 ExternalSema->ForgetSema();
280 // If Sema's ExternalSource is the multiplexer - we own it.
281 if (isMultiplexExternalSource)
282 delete ExternalSource;
284 threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
286 // Destroys data sharing attributes stack for OpenMP
287 DestroyDataSharingAttributesStack();
289 assert(DelayedTypos.empty() && "Uncorrected typos!");
292 /// makeUnavailableInSystemHeader - There is an error in the current
293 /// context. If we're still in a system header, and we can plausibly
294 /// make the relevant declaration unavailable instead of erroring, do
295 /// so and return true.
296 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
297 UnavailableAttr::ImplicitReason reason) {
298 // If we're not in a function, it's an error.
299 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
300 if (!fn) return false;
302 // If we're in template instantiation, it's an error.
303 if (!ActiveTemplateInstantiations.empty())
306 // If that function's not in a system header, it's an error.
307 if (!Context.getSourceManager().isInSystemHeader(loc))
310 // If the function is already unavailable, it's not an error.
311 if (fn->hasAttr<UnavailableAttr>()) return true;
313 fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
317 ASTMutationListener *Sema::getASTMutationListener() const {
318 return getASTConsumer().GetASTMutationListener();
321 ///\brief Registers an external source. If an external source already exists,
322 /// creates a multiplex external source and appends to it.
324 ///\param[in] E - A non-null external sema source.
326 void Sema::addExternalSource(ExternalSemaSource *E) {
327 assert(E && "Cannot use with NULL ptr");
329 if (!ExternalSource) {
334 if (isMultiplexExternalSource)
335 static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
337 ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
338 isMultiplexExternalSource = true;
342 /// \brief Print out statistics about the semantic analysis.
343 void Sema::PrintStats() const {
344 llvm::errs() << "\n*** Semantic Analysis Stats:\n";
345 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
347 BumpAlloc.PrintStats();
348 AnalysisWarnings.PrintStats();
351 void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
353 SourceLocation Loc) {
354 Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
355 if (!ExprNullability || *ExprNullability != NullabilityKind::Nullable)
358 Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
359 if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
362 Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
365 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
366 /// If there is already an implicit cast, merge into the existing one.
367 /// The result is of the given category.
368 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
369 CastKind Kind, ExprValueKind VK,
370 const CXXCastPath *BasePath,
371 CheckedConversionKind CCK) {
373 if (VK == VK_RValue && !E->isRValue()) {
376 llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
378 case CK_LValueToRValue:
379 case CK_ArrayToPointerDecay:
380 case CK_FunctionToPointerDecay:
385 assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
388 diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getLocStart());
390 QualType ExprTy = Context.getCanonicalType(E->getType());
391 QualType TypeTy = Context.getCanonicalType(Ty);
393 if (ExprTy == TypeTy)
396 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
397 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
398 ImpCast->setType(Ty);
399 ImpCast->setValueKind(VK);
404 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
407 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
408 /// to the conversion from scalar type ScalarTy to the Boolean type.
409 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
410 switch (ScalarTy->getScalarTypeKind()) {
411 case Type::STK_Bool: return CK_NoOp;
412 case Type::STK_CPointer: return CK_PointerToBoolean;
413 case Type::STK_BlockPointer: return CK_PointerToBoolean;
414 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
415 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
416 case Type::STK_Integral: return CK_IntegralToBoolean;
417 case Type::STK_Floating: return CK_FloatingToBoolean;
418 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
419 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
424 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
425 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
426 if (D->getMostRecentDecl()->isUsed())
429 if (D->isExternallyVisible())
432 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
433 // UnusedFileScopedDecls stores the first declaration.
434 // The declaration may have become definition so check again.
435 const FunctionDecl *DeclToCheck;
436 if (FD->hasBody(DeclToCheck))
437 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
439 // Later redecls may add new information resulting in not having to warn,
441 DeclToCheck = FD->getMostRecentDecl();
442 if (DeclToCheck != FD)
443 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
446 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
447 // If a variable usable in constant expressions is referenced,
448 // don't warn if it isn't used: if the value of a variable is required
449 // for the computation of a constant expression, it doesn't make sense to
450 // warn even if the variable isn't odr-used. (isReferenced doesn't
451 // precisely reflect that, but it's a decent approximation.)
452 if (VD->isReferenced() &&
453 VD->isUsableInConstantExpressions(SemaRef->Context))
456 // UnusedFileScopedDecls stores the first declaration.
457 // The declaration may have become definition so check again.
458 const VarDecl *DeclToCheck = VD->getDefinition();
460 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
462 // Later redecls may add new information resulting in not having to warn,
464 DeclToCheck = VD->getMostRecentDecl();
465 if (DeclToCheck != VD)
466 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
472 /// Obtains a sorted list of functions and variables that are undefined but
474 void Sema::getUndefinedButUsed(
475 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
476 for (const auto &UndefinedUse : UndefinedButUsed) {
477 NamedDecl *ND = UndefinedUse.first;
479 // Ignore attributes that have become invalid.
480 if (ND->isInvalidDecl()) continue;
482 // __attribute__((weakref)) is basically a definition.
483 if (ND->hasAttr<WeakRefAttr>()) continue;
485 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
488 if (FD->isExternallyVisible() &&
489 !FD->getMostRecentDecl()->isInlined())
492 auto *VD = cast<VarDecl>(ND);
493 if (VD->hasDefinition() != VarDecl::DeclarationOnly)
495 if (VD->isExternallyVisible() && !VD->getMostRecentDecl()->isInline())
499 Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
503 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
504 /// or that are inline.
505 static void checkUndefinedButUsed(Sema &S) {
506 if (S.UndefinedButUsed.empty()) return;
508 // Collect all the still-undefined entities with internal linkage.
509 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
510 S.getUndefinedButUsed(Undefined);
511 if (Undefined.empty()) return;
513 for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
514 I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
515 NamedDecl *ND = I->first;
517 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
518 // An exported function will always be emitted when defined, so even if
519 // the function is inline, it doesn't have to be emitted in this TU. An
520 // imported function implies that it has been exported somewhere else.
524 if (!ND->isExternallyVisible()) {
525 S.Diag(ND->getLocation(), diag::warn_undefined_internal)
526 << isa<VarDecl>(ND) << ND;
527 } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
529 assert(FD->getMostRecentDecl()->isInlined() &&
530 "used object requires definition but isn't inline or internal?");
531 // FIXME: This is ill-formed; we should reject.
532 S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND;
534 assert(cast<VarDecl>(ND)->getMostRecentDecl()->isInline() &&
535 "used var requires definition but isn't inline or internal?");
536 S.Diag(ND->getLocation(), diag::err_undefined_inline_var) << ND;
538 if (I->second.isValid())
539 S.Diag(I->second, diag::note_used_here);
542 S.UndefinedButUsed.clear();
545 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
549 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
550 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
551 for (auto &WeakID : WeakIDs)
552 WeakUndeclaredIdentifiers.insert(WeakID);
556 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
558 /// \brief Returns true, if all methods and nested classes of the given
559 /// CXXRecordDecl are defined in this translation unit.
561 /// Should only be called from ActOnEndOfTranslationUnit so that all
562 /// definitions are actually read.
563 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
564 RecordCompleteMap &MNCComplete) {
565 RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
566 if (Cache != MNCComplete.end())
567 return Cache->second;
568 if (!RD->isCompleteDefinition())
570 bool Complete = true;
571 for (DeclContext::decl_iterator I = RD->decls_begin(),
573 I != E && Complete; ++I) {
574 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
575 Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M));
576 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
577 // If the template function is marked as late template parsed at this
578 // point, it has not been instantiated and therefore we have not
579 // performed semantic analysis on it yet, so we cannot know if the type
580 // can be considered complete.
581 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
582 F->getTemplatedDecl()->isDefined();
583 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
584 if (R->isInjectedClassName())
586 if (R->hasDefinition())
587 Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
593 MNCComplete[RD] = Complete;
597 /// \brief Returns true, if the given CXXRecordDecl is fully defined in this
598 /// translation unit, i.e. all methods are defined or pure virtual and all
599 /// friends, friend functions and nested classes are fully defined in this
600 /// translation unit.
602 /// Should only be called from ActOnEndOfTranslationUnit so that all
603 /// definitions are actually read.
604 static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
605 RecordCompleteMap &RecordsComplete,
606 RecordCompleteMap &MNCComplete) {
607 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
608 if (Cache != RecordsComplete.end())
609 return Cache->second;
610 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
611 for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
612 E = RD->friend_end();
613 I != E && Complete; ++I) {
614 // Check if friend classes and methods are complete.
615 if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
616 // Friend classes are available as the TypeSourceInfo of the FriendDecl.
617 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
618 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
622 // Friend functions are available through the NamedDecl of FriendDecl.
623 if (const FunctionDecl *FD =
624 dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
625 Complete = FD->isDefined();
627 // This is a template friend, give up.
631 RecordsComplete[RD] = Complete;
635 void Sema::emitAndClearUnusedLocalTypedefWarnings() {
637 ExternalSource->ReadUnusedLocalTypedefNameCandidates(
638 UnusedLocalTypedefNameCandidates);
639 for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
640 if (TD->isReferenced())
642 Diag(TD->getLocation(), diag::warn_unused_local_typedef)
643 << isa<TypeAliasDecl>(TD) << TD->getDeclName();
645 UnusedLocalTypedefNameCandidates.clear();
648 /// ActOnEndOfTranslationUnit - This is called at the very end of the
649 /// translation unit when EOF is reached and all but the top-level scope is
651 void Sema::ActOnEndOfTranslationUnit() {
652 assert(DelayedDiagnostics.getCurrentPool() == nullptr
653 && "reached end of translation unit with a pool attached?");
655 // If code completion is enabled, don't perform any end-of-translation-unit
657 if (PP.isCodeCompletionEnabled())
660 // Complete translation units and modules define vtables and perform implicit
661 // instantiations. PCH files do not.
662 if (TUKind != TU_Prefix) {
663 DiagnoseUseOfUnimplementedSelectors();
665 // If DefinedUsedVTables ends up marking any virtual member functions it
666 // might lead to more pending template instantiations, which we then need
670 // C++: Perform implicit template instantiations.
672 // FIXME: When we perform these implicit instantiations, we do not
673 // carefully keep track of the point of instantiation (C++ [temp.point]).
674 // This means that name lookup that occurs within the template
675 // instantiation will always happen at the end of the translation unit,
676 // so it will find some names that are not required to be found. This is
677 // valid, but we could do better by diagnosing if an instantiation uses a
678 // name that was not visible at its first point of instantiation.
679 if (ExternalSource) {
680 // Load pending instantiations from the external source.
681 SmallVector<PendingImplicitInstantiation, 4> Pending;
682 ExternalSource->ReadPendingInstantiations(Pending);
683 PendingInstantiations.insert(PendingInstantiations.begin(),
684 Pending.begin(), Pending.end());
686 PerformPendingInstantiations();
688 if (LateTemplateParserCleanup)
689 LateTemplateParserCleanup(OpaqueParser);
691 CheckDelayedMemberExceptionSpecs();
694 // All delayed member exception specs should be checked or we end up accepting
695 // incompatible declarations.
696 // FIXME: This is wrong for TUKind == TU_Prefix. In that case, we need to
697 // write out the lists to the AST file (if any).
698 assert(DelayedDefaultedMemberExceptionSpecs.empty());
699 assert(DelayedExceptionSpecChecks.empty());
701 // All dllexport classes should have been processed already.
702 assert(DelayedDllExportClasses.empty());
704 // Remove file scoped decls that turned out to be used.
705 UnusedFileScopedDecls.erase(
706 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
707 UnusedFileScopedDecls.end(),
708 std::bind1st(std::ptr_fun(ShouldRemoveFromUnused), this)),
709 UnusedFileScopedDecls.end());
711 if (TUKind == TU_Prefix) {
712 // Translation unit prefixes don't need any of the checking below.
717 // Check for #pragma weak identifiers that were never declared
718 LoadExternalWeakUndeclaredIdentifiers();
719 for (auto WeakID : WeakUndeclaredIdentifiers) {
720 if (WeakID.second.getUsed())
723 Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
725 if (PrevDecl != nullptr &&
726 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
727 Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
728 << "'weak'" << ExpectedVariableOrFunction;
730 Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
734 if (LangOpts.CPlusPlus11 &&
735 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
736 CheckDelegatingCtorCycles();
738 if (!Diags.hasErrorOccurred()) {
740 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
741 checkUndefinedButUsed(*this);
744 if (TUKind == TU_Module) {
745 // If we are building a module, resolve all of the exported declarations
747 if (Module *CurrentModule = PP.getCurrentModule()) {
748 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
750 SmallVector<Module *, 2> Stack;
751 Stack.push_back(CurrentModule);
752 while (!Stack.empty()) {
753 Module *Mod = Stack.pop_back_val();
755 // Resolve the exported declarations and conflicts.
756 // FIXME: Actually complain, once we figure out how to teach the
757 // diagnostic client to deal with complaints in the module map at this
759 ModMap.resolveExports(Mod, /*Complain=*/false);
760 ModMap.resolveUses(Mod, /*Complain=*/false);
761 ModMap.resolveConflicts(Mod, /*Complain=*/false);
763 // Queue the submodules, so their exports will also be resolved.
764 Stack.append(Mod->submodule_begin(), Mod->submodule_end());
768 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
769 // modules when they are built, not every time they are used.
770 emitAndClearUnusedLocalTypedefWarnings();
772 // Modules don't need any of the checking below.
778 // A declaration of an identifier for an object that has file
779 // scope without an initializer, and without a storage-class
780 // specifier or with the storage-class specifier static,
781 // constitutes a tentative definition. If a translation unit
782 // contains one or more tentative definitions for an identifier,
783 // and the translation unit contains no external definition for
784 // that identifier, then the behavior is exactly as if the
785 // translation unit contains a file scope declaration of that
786 // identifier, with the composite type as of the end of the
787 // translation unit, with an initializer equal to 0.
788 llvm::SmallSet<VarDecl *, 32> Seen;
789 for (TentativeDefinitionsType::iterator
790 T = TentativeDefinitions.begin(ExternalSource),
791 TEnd = TentativeDefinitions.end();
794 VarDecl *VD = (*T)->getActingDefinition();
796 // If the tentative definition was completed, getActingDefinition() returns
797 // null. If we've already seen this variable before, insert()'s second
798 // return value is false.
799 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
802 if (const IncompleteArrayType *ArrayT
803 = Context.getAsIncompleteArrayType(VD->getType())) {
804 // Set the length of the array to 1 (C99 6.9.2p5).
805 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
806 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
807 QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
808 One, ArrayType::Normal, 0);
810 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
811 diag::err_tentative_def_incomplete_type))
812 VD->setInvalidDecl();
814 CheckCompleteVariableDeclaration(VD);
816 // Notify the consumer that we've completed a tentative definition.
817 if (!VD->isInvalidDecl())
818 Consumer.CompleteTentativeDefinition(VD);
822 // If there were errors, disable 'unused' warnings since they will mostly be
824 if (!Diags.hasErrorOccurred()) {
825 // Output warning for unused file scoped decls.
826 for (UnusedFileScopedDeclsType::iterator
827 I = UnusedFileScopedDecls.begin(ExternalSource),
828 E = UnusedFileScopedDecls.end(); I != E; ++I) {
829 if (ShouldRemoveFromUnused(this, *I))
832 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
833 const FunctionDecl *DiagD;
834 if (!FD->hasBody(DiagD))
836 if (DiagD->isDeleted())
837 continue; // Deleted functions are supposed to be unused.
838 if (DiagD->isReferenced()) {
839 if (isa<CXXMethodDecl>(DiagD))
840 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
841 << DiagD->getDeclName();
843 if (FD->getStorageClass() == SC_Static &&
844 !FD->isInlineSpecified() &&
845 !SourceMgr.isInMainFile(
846 SourceMgr.getExpansionLoc(FD->getLocation())))
847 Diag(DiagD->getLocation(),
848 diag::warn_unneeded_static_internal_decl)
849 << DiagD->getDeclName();
851 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
852 << /*function*/0 << DiagD->getDeclName();
855 Diag(DiagD->getLocation(),
856 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
857 : diag::warn_unused_function)
858 << DiagD->getDeclName();
861 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
863 DiagD = cast<VarDecl>(*I);
864 if (DiagD->isReferenced()) {
865 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
866 << /*variable*/1 << DiagD->getDeclName();
867 } else if (DiagD->getType().isConstQualified()) {
868 Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
869 << DiagD->getDeclName();
871 Diag(DiagD->getLocation(), diag::warn_unused_variable)
872 << DiagD->getDeclName();
877 emitAndClearUnusedLocalTypedefWarnings();
880 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
881 RecordCompleteMap RecordsComplete;
882 RecordCompleteMap MNCComplete;
883 for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
884 E = UnusedPrivateFields.end(); I != E; ++I) {
885 const NamedDecl *D = *I;
886 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
887 if (RD && !RD->isUnion() &&
888 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
889 Diag(D->getLocation(), diag::warn_unused_private_field)
895 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
897 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
898 for (const auto &DeletedFieldInfo : DeleteExprs) {
899 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
900 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
901 DeleteExprLoc.second);
906 // Check we've noticed that we're no longer parsing the initializer for every
907 // variable. If we miss cases, then at best we have a performance issue and
908 // at worst a rejects-valid bug.
909 assert(ParsingInitForAutoVars.empty() &&
910 "Didn't unmark var as having its initializer parsed");
916 //===----------------------------------------------------------------------===//
918 //===----------------------------------------------------------------------===//
920 DeclContext *Sema::getFunctionLevelDeclContext() {
921 DeclContext *DC = CurContext;
924 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
925 DC = DC->getParent();
926 } else if (isa<CXXMethodDecl>(DC) &&
927 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
928 cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
929 DC = DC->getParent()->getParent();
937 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
938 /// to the function decl for the function being parsed. If we're currently
939 /// in a 'block', this returns the containing context.
940 FunctionDecl *Sema::getCurFunctionDecl() {
941 DeclContext *DC = getFunctionLevelDeclContext();
942 return dyn_cast<FunctionDecl>(DC);
945 ObjCMethodDecl *Sema::getCurMethodDecl() {
946 DeclContext *DC = getFunctionLevelDeclContext();
947 while (isa<RecordDecl>(DC))
948 DC = DC->getParent();
949 return dyn_cast<ObjCMethodDecl>(DC);
952 NamedDecl *Sema::getCurFunctionOrMethodDecl() {
953 DeclContext *DC = getFunctionLevelDeclContext();
954 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
955 return cast<NamedDecl>(DC);
959 void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
960 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
961 // and yet we also use the current diag ID on the DiagnosticsEngine. This has
962 // been made more painfully obvious by the refactor that introduced this
963 // function, but it is possible that the incoming argument can be
964 // eliminnated. If it truly cannot be (for example, there is some reentrancy
965 // issue I am not seeing yet), then there should at least be a clarifying
966 // comment somewhere.
967 if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
968 switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
969 Diags.getCurrentDiagID())) {
970 case DiagnosticIDs::SFINAE_Report:
971 // We'll report the diagnostic below.
974 case DiagnosticIDs::SFINAE_SubstitutionFailure:
975 // Count this failure so that we know that template argument deduction
979 // Make a copy of this suppressed diagnostic and store it with the
980 // template-deduction information.
981 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
982 Diagnostic DiagInfo(&Diags);
983 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
984 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
987 Diags.setLastDiagnosticIgnored();
991 case DiagnosticIDs::SFINAE_AccessControl: {
992 // Per C++ Core Issue 1170, access control is part of SFINAE.
993 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
994 // make access control a part of SFINAE for the purposes of checking
996 if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
999 SourceLocation Loc = Diags.getCurrentDiagLoc();
1001 // Suppress this diagnostic.
1004 // Make a copy of this suppressed diagnostic and store it with the
1005 // template-deduction information.
1006 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1007 Diagnostic DiagInfo(&Diags);
1008 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1009 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1012 Diags.setLastDiagnosticIgnored();
1015 // Now the diagnostic state is clear, produce a C++98 compatibility
1017 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1019 // The last diagnostic which Sema produced was ignored. Suppress any
1020 // notes attached to it.
1021 Diags.setLastDiagnosticIgnored();
1025 case DiagnosticIDs::SFINAE_Suppress:
1026 // Make a copy of this suppressed diagnostic and store it with the
1027 // template-deduction information;
1029 Diagnostic DiagInfo(&Diags);
1030 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1031 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1034 // Suppress this diagnostic.
1035 Diags.setLastDiagnosticIgnored();
1041 // Set up the context's printing policy based on our current state.
1042 Context.setPrintingPolicy(getPrintingPolicy());
1044 // Emit the diagnostic.
1045 if (!Diags.EmitCurrentDiagnostic())
1048 // If this is not a note, and we're in a template instantiation
1049 // that is different from the last template instantiation where
1050 // we emitted an error, print a template instantiation
1052 if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
1053 !ActiveTemplateInstantiations.empty() &&
1054 ActiveTemplateInstantiations.back()
1055 != LastTemplateInstantiationErrorContext) {
1056 PrintInstantiationStack();
1057 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiations.back();
1061 Sema::SemaDiagnosticBuilder
1062 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
1063 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
1069 /// \brief Looks through the macro-expansion chain for the given
1070 /// location, looking for a macro expansion with the given name.
1071 /// If one is found, returns true and sets the location to that
1073 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
1074 SourceLocation loc = locref;
1075 if (!loc.isMacroID()) return false;
1077 // There's no good way right now to look at the intermediate
1078 // expansions, so just jump to the expansion location.
1079 loc = getSourceManager().getExpansionLoc(loc);
1081 // If that's written with the name, stop here.
1082 SmallVector<char, 16> buffer;
1083 if (getPreprocessor().getSpelling(loc, buffer) == name) {
1090 /// \brief Determines the active Scope associated with the given declaration
1093 /// This routine maps a declaration context to the active Scope object that
1094 /// represents that declaration context in the parser. It is typically used
1095 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1096 /// declarations) that injects a name for name-lookup purposes and, therefore,
1097 /// must update the Scope.
1099 /// \returns The scope corresponding to the given declaraion context, or NULL
1100 /// if no such scope is open.
1101 Scope *Sema::getScopeForContext(DeclContext *Ctx) {
1106 Ctx = Ctx->getPrimaryContext();
1107 for (Scope *S = getCurScope(); S; S = S->getParent()) {
1108 // Ignore scopes that cannot have declarations. This is important for
1109 // out-of-line definitions of static class members.
1110 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
1111 if (DeclContext *Entity = S->getEntity())
1112 if (Ctx == Entity->getPrimaryContext())
1119 /// \brief Enter a new function scope
1120 void Sema::PushFunctionScope() {
1121 if (FunctionScopes.size() == 1) {
1122 // Use the "top" function scope rather than having to allocate
1123 // memory for a new scope.
1124 FunctionScopes.back()->Clear();
1125 FunctionScopes.push_back(FunctionScopes.back());
1129 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
1132 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
1133 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
1134 BlockScope, Block));
1137 LambdaScopeInfo *Sema::PushLambdaScope() {
1138 LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
1139 FunctionScopes.push_back(LSI);
1143 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
1144 if (LambdaScopeInfo *const LSI = getCurLambda()) {
1145 LSI->AutoTemplateParameterDepth = Depth;
1149 "Remove assertion if intentionally called in a non-lambda context.");
1152 void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
1153 const Decl *D, const BlockExpr *blkExpr) {
1154 FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
1155 assert(!FunctionScopes.empty() && "mismatched push/pop!");
1157 // Issue any analysis-based warnings.
1159 AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
1161 for (const auto &PUD : Scope->PossiblyUnreachableDiags)
1162 Diag(PUD.Loc, PUD.PD);
1164 if (FunctionScopes.back() != Scope)
1168 void Sema::PushCompoundScope() {
1169 getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo());
1172 void Sema::PopCompoundScope() {
1173 FunctionScopeInfo *CurFunction = getCurFunction();
1174 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
1176 CurFunction->CompoundScopes.pop_back();
1179 /// \brief Determine whether any errors occurred within this function/method/
1181 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
1182 return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
1185 BlockScopeInfo *Sema::getCurBlock() {
1186 if (FunctionScopes.empty())
1189 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
1190 if (CurBSI && CurBSI->TheDecl &&
1191 !CurBSI->TheDecl->Encloses(CurContext)) {
1192 // We have switched contexts due to template instantiation.
1193 assert(!ActiveTemplateInstantiations.empty());
1200 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreCapturedRegions) {
1201 if (FunctionScopes.empty())
1204 auto I = FunctionScopes.rbegin();
1205 if (IgnoreCapturedRegions) {
1206 auto E = FunctionScopes.rend();
1207 while (I != E && isa<CapturedRegionScopeInfo>(*I))
1212 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
1213 if (CurLSI && CurLSI->Lambda &&
1214 !CurLSI->Lambda->Encloses(CurContext)) {
1215 // We have switched contexts due to template instantiation.
1216 assert(!ActiveTemplateInstantiations.empty());
1222 // We have a generic lambda if we parsed auto parameters, or we have
1223 // an associated template parameter list.
1224 LambdaScopeInfo *Sema::getCurGenericLambda() {
1225 if (LambdaScopeInfo *LSI = getCurLambda()) {
1226 return (LSI->AutoTemplateParams.size() ||
1227 LSI->GLTemplateParameterList) ? LSI : nullptr;
1233 void Sema::ActOnComment(SourceRange Comment) {
1234 if (!LangOpts.RetainCommentsFromSystemHeaders &&
1235 SourceMgr.isInSystemHeader(Comment.getBegin()))
1237 RawComment RC(SourceMgr, Comment, false,
1238 LangOpts.CommentOpts.ParseAllComments);
1239 if (RC.isAlmostTrailingComment()) {
1240 SourceRange MagicMarkerRange(Comment.getBegin(),
1241 Comment.getBegin().getLocWithOffset(3));
1242 StringRef MagicMarkerText;
1243 switch (RC.getKind()) {
1244 case RawComment::RCK_OrdinaryBCPL:
1245 MagicMarkerText = "///<";
1247 case RawComment::RCK_OrdinaryC:
1248 MagicMarkerText = "/**<";
1251 llvm_unreachable("if this is an almost Doxygen comment, "
1252 "it should be ordinary");
1254 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
1255 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
1257 Context.addComment(RC);
1260 // Pin this vtable to this file.
1261 ExternalSemaSource::~ExternalSemaSource() {}
1263 void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
1264 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
1266 void ExternalSemaSource::ReadKnownNamespaces(
1267 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
1270 void ExternalSemaSource::ReadUndefinedButUsed(
1271 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
1273 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
1274 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
1276 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
1277 SourceLocation Loc = this->Loc;
1278 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
1279 if (Loc.isValid()) {
1280 Loc.print(OS, S.getSourceManager());
1285 if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
1287 ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(), true);
1294 /// \brief Figure out if an expression could be turned into a call.
1296 /// Use this when trying to recover from an error where the programmer may have
1297 /// written just the name of a function instead of actually calling it.
1299 /// \param E - The expression to examine.
1300 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1301 /// with no arguments, this parameter is set to the type returned by such a
1302 /// call; otherwise, it is set to an empty QualType.
1303 /// \param OverloadSet - If the expression is an overloaded function
1304 /// name, this parameter is populated with the decls of the various overloads.
1305 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1306 UnresolvedSetImpl &OverloadSet) {
1307 ZeroArgCallReturnTy = QualType();
1308 OverloadSet.clear();
1310 const OverloadExpr *Overloads = nullptr;
1311 bool IsMemExpr = false;
1312 if (E.getType() == Context.OverloadTy) {
1313 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
1315 // Ignore overloads that are pointer-to-member constants.
1316 if (FR.HasFormOfMemberPointer)
1319 Overloads = FR.Expression;
1320 } else if (E.getType() == Context.BoundMemberTy) {
1321 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
1325 bool Ambiguous = false;
1328 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
1329 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
1330 OverloadSet.addDecl(*it);
1332 // Check whether the function is a non-template, non-member which takes no
1336 if (const FunctionDecl *OverloadDecl
1337 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
1338 if (OverloadDecl->getMinRequiredArguments() == 0) {
1339 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
1340 ZeroArgCallReturnTy = QualType();
1343 ZeroArgCallReturnTy = OverloadDecl->getReturnType();
1348 // If it's not a member, use better machinery to try to resolve the call
1350 return !ZeroArgCallReturnTy.isNull();
1353 // Attempt to call the member with no arguments - this will correctly handle
1354 // member templates with defaults/deduction of template arguments, overloads
1355 // with default arguments, etc.
1356 if (IsMemExpr && !E.isTypeDependent()) {
1357 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
1358 getDiagnostics().setSuppressAllDiagnostics(true);
1359 ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
1360 None, SourceLocation());
1361 getDiagnostics().setSuppressAllDiagnostics(Suppress);
1363 ZeroArgCallReturnTy = R.get()->getType();
1369 if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
1370 if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
1371 if (Fun->getMinRequiredArguments() == 0)
1372 ZeroArgCallReturnTy = Fun->getReturnType();
1377 // We don't have an expression that's convenient to get a FunctionDecl from,
1378 // but we can at least check if the type is "function of 0 arguments".
1379 QualType ExprTy = E.getType();
1380 const FunctionType *FunTy = nullptr;
1381 QualType PointeeTy = ExprTy->getPointeeType();
1382 if (!PointeeTy.isNull())
1383 FunTy = PointeeTy->getAs<FunctionType>();
1385 FunTy = ExprTy->getAs<FunctionType>();
1387 if (const FunctionProtoType *FPT =
1388 dyn_cast_or_null<FunctionProtoType>(FunTy)) {
1389 if (FPT->getNumParams() == 0)
1390 ZeroArgCallReturnTy = FunTy->getReturnType();
1396 /// \brief Give notes for a set of overloads.
1398 /// A companion to tryExprAsCall. In cases when the name that the programmer
1399 /// wrote was an overloaded function, we may be able to make some guesses about
1400 /// plausible overloads based on their return types; such guesses can be handed
1401 /// off to this method to be emitted as notes.
1403 /// \param Overloads - The overloads to note.
1404 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
1405 /// -fshow-overloads=best, this is the location to attach to the note about too
1406 /// many candidates. Typically this will be the location of the original
1407 /// ill-formed expression.
1408 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
1409 const SourceLocation FinalNoteLoc) {
1410 int ShownOverloads = 0;
1411 int SuppressedOverloads = 0;
1412 for (UnresolvedSetImpl::iterator It = Overloads.begin(),
1413 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1414 // FIXME: Magic number for max shown overloads stolen from
1415 // OverloadCandidateSet::NoteCandidates.
1416 if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
1417 ++SuppressedOverloads;
1421 NamedDecl *Fn = (*It)->getUnderlyingDecl();
1422 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
1426 if (SuppressedOverloads)
1427 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
1428 << SuppressedOverloads;
1431 static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
1432 const UnresolvedSetImpl &Overloads,
1433 bool (*IsPlausibleResult)(QualType)) {
1434 if (!IsPlausibleResult)
1435 return noteOverloads(S, Overloads, Loc);
1437 UnresolvedSet<2> PlausibleOverloads;
1438 for (OverloadExpr::decls_iterator It = Overloads.begin(),
1439 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1440 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1441 QualType OverloadResultTy = OverloadDecl->getReturnType();
1442 if (IsPlausibleResult(OverloadResultTy))
1443 PlausibleOverloads.addDecl(It.getDecl());
1445 noteOverloads(S, PlausibleOverloads, Loc);
1448 /// Determine whether the given expression can be called by just
1449 /// putting parentheses after it. Notably, expressions with unary
1450 /// operators can't be because the unary operator will start parsing
1451 /// outside the call.
1452 static bool IsCallableWithAppend(Expr *E) {
1453 E = E->IgnoreImplicit();
1454 return (!isa<CStyleCastExpr>(E) &&
1455 !isa<UnaryOperator>(E) &&
1456 !isa<BinaryOperator>(E) &&
1457 !isa<CXXOperatorCallExpr>(E));
1460 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1462 bool (*IsPlausibleResult)(QualType)) {
1463 SourceLocation Loc = E.get()->getExprLoc();
1464 SourceRange Range = E.get()->getSourceRange();
1466 QualType ZeroArgCallTy;
1467 UnresolvedSet<4> Overloads;
1468 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
1469 !ZeroArgCallTy.isNull() &&
1470 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
1471 // At this point, we know E is potentially callable with 0
1472 // arguments and that it returns something of a reasonable type,
1473 // so we can emit a fixit and carry on pretending that E was
1474 // actually a CallExpr.
1475 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
1477 << /*zero-arg*/ 1 << Range
1478 << (IsCallableWithAppend(E.get())
1479 ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
1481 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1483 // FIXME: Try this before emitting the fixit, and suppress diagnostics
1485 E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None,
1486 Range.getEnd().getLocWithOffset(1));
1490 if (!ForceComplain) return false;
1492 Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
1493 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1498 IdentifierInfo *Sema::getSuperIdentifier() const {
1500 Ident_super = &Context.Idents.get("super");
1504 IdentifierInfo *Sema::getFloat128Identifier() const {
1505 if (!Ident___float128)
1506 Ident___float128 = &Context.Idents.get("__float128");
1507 return Ident___float128;
1510 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
1511 CapturedRegionKind K) {
1512 CapturingScopeInfo *CSI = new CapturedRegionScopeInfo(
1513 getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
1514 (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0);
1515 CSI->ReturnType = Context.VoidTy;
1516 FunctionScopes.push_back(CSI);
1519 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
1520 if (FunctionScopes.empty())
1523 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
1526 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
1527 Sema::getMismatchingDeleteExpressions() const {