xref: /llvm-project-15.0.7/clang/lib/Sema/Sema.cpp (revision ef99e4d8)
1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the actions class which performs semantic analysis and
11 // builds an AST out of a parse stream.
12 //
13 //===----------------------------------------------------------------------===//
14 
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 #include "llvm/Support/CrashRecoveryContext.h"
44 using namespace clang;
45 using namespace sema;
46 
47 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
48   return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
49 }
50 
51 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
52 
53 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
54                                        const Preprocessor &PP) {
55   PrintingPolicy Policy = Context.getPrintingPolicy();
56   Policy.Bool = Context.getLangOpts().Bool;
57   if (!Policy.Bool) {
58     if (const MacroInfo *
59           BoolMacro = PP.getMacroInfo(&Context.Idents.get("bool"))) {
60       Policy.Bool = BoolMacro->isObjectLike() &&
61         BoolMacro->getNumTokens() == 1 &&
62         BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
63     }
64   }
65 
66   return Policy;
67 }
68 
69 void Sema::ActOnTranslationUnitScope(Scope *S) {
70   TUScope = S;
71   PushDeclContext(S, Context.getTranslationUnitDecl());
72 }
73 
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     PackContext(nullptr), MSStructPragmaOn(false),
84     MSPointerToMemberRepresentationMethod(
85         LangOpts.getMSPointerToMemberRepresentationMethod()),
86     VtorDispModeStack(1, MSVtorDispAttr::Mode(LangOpts.VtorDispMode)),
87     DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
88     CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr),
89     IsBuildingRecoveryCallExpr(false),
90     ExprNeedsCleanups(false), LateTemplateParser(nullptr),
91     OpaqueParser(nullptr), IdResolver(pp), StdInitializerList(nullptr),
92     CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr),
93     NSNumberDecl(nullptr),
94     NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
95     NSArrayDecl(nullptr), ArrayWithObjectsMethod(nullptr),
96     InitArrayWithObjectsMethod(nullptr),
97     NSDictionaryDecl(nullptr), DictionaryWithObjectsMethod(nullptr),
98     InitDictionaryWithObjectsMethod(nullptr),
99     ArrayAllocObjectsMethod(nullptr),
100     DictAllocObjectsMethod(nullptr),
101     MSAsmLabelNameCounter(0),
102     GlobalNewDeleteDeclared(false),
103     TUKind(TUKind),
104     NumSFINAEErrors(0),
105     AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
106     NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
107     CurrentInstantiationScope(nullptr), DisableTypoCorrection(false),
108     TyposCorrected(0), AnalysisWarnings(*this),
109     VarDataSharingAttributesStack(nullptr), CurScope(nullptr),
110     Ident_super(nullptr), Ident___float128(nullptr)
111 {
112   TUScope = nullptr;
113 
114   LoadedExternalKnownNamespaces = false;
115   for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
116     NSNumberLiteralMethods[I] = nullptr;
117 
118   if (getLangOpts().ObjC1)
119     NSAPIObj.reset(new NSAPI(Context));
120 
121   if (getLangOpts().CPlusPlus)
122     FieldCollector.reset(new CXXFieldCollector());
123 
124   // Tell diagnostics how to render things from the AST library.
125   PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
126                                        &Context);
127 
128   ExprEvalContexts.push_back(
129         ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0,
130                                           false, nullptr, false));
131 
132   FunctionScopes.push_back(new FunctionScopeInfo(Diags));
133 
134   // Initilization of data sharing attributes stack for OpenMP
135   InitDataSharingAttributesStack();
136 }
137 
138 void Sema::addImplicitTypedef(StringRef Name, QualType T) {
139   DeclarationName DN = &Context.Idents.get(Name);
140   if (IdResolver.begin(DN) == IdResolver.end())
141     PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
142 }
143 
144 void Sema::Initialize() {
145   // Tell the AST consumer about this Sema object.
146   Consumer.Initialize(Context);
147 
148   // FIXME: Isn't this redundant with the initialization above?
149   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
150     SC->InitializeSema(*this);
151 
152   // Tell the external Sema source about this Sema object.
153   if (ExternalSemaSource *ExternalSema
154       = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
155     ExternalSema->InitializeSema(*this);
156 
157   // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
158   // will not be able to merge any duplicate __va_list_tag decls correctly.
159   VAListTagName = PP.getIdentifierInfo("__va_list_tag");
160 
161   // Initialize predefined 128-bit integer types, if needed.
162   if (Context.getTargetInfo().hasInt128Type()) {
163     // If either of the 128-bit integer types are unavailable to name lookup,
164     // define them now.
165     DeclarationName Int128 = &Context.Idents.get("__int128_t");
166     if (IdResolver.begin(Int128) == IdResolver.end())
167       PushOnScopeChains(Context.getInt128Decl(), TUScope);
168 
169     DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
170     if (IdResolver.begin(UInt128) == IdResolver.end())
171       PushOnScopeChains(Context.getUInt128Decl(), TUScope);
172   }
173 
174 
175   // Initialize predefined Objective-C types:
176   if (PP.getLangOpts().ObjC1) {
177     // If 'SEL' does not yet refer to any declarations, make it refer to the
178     // predefined 'SEL'.
179     DeclarationName SEL = &Context.Idents.get("SEL");
180     if (IdResolver.begin(SEL) == IdResolver.end())
181       PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
182 
183     // If 'id' does not yet refer to any declarations, make it refer to the
184     // predefined 'id'.
185     DeclarationName Id = &Context.Idents.get("id");
186     if (IdResolver.begin(Id) == IdResolver.end())
187       PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
188 
189     // Create the built-in typedef for 'Class'.
190     DeclarationName Class = &Context.Idents.get("Class");
191     if (IdResolver.begin(Class) == IdResolver.end())
192       PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
193 
194     // Create the built-in forward declaratino for 'Protocol'.
195     DeclarationName Protocol = &Context.Idents.get("Protocol");
196     if (IdResolver.begin(Protocol) == IdResolver.end())
197       PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
198   }
199 
200   // Initialize Microsoft "predefined C++ types".
201   if (PP.getLangOpts().MSVCCompat && PP.getLangOpts().CPlusPlus) {
202     if (IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
203       PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
204                         TUScope);
205 
206     addImplicitTypedef("size_t", Context.getSizeType());
207   }
208 
209   // Initialize predefined OpenCL types.
210   if (PP.getLangOpts().OpenCL) {
211     addImplicitTypedef("image1d_t", Context.OCLImage1dTy);
212     addImplicitTypedef("image1d_array_t", Context.OCLImage1dArrayTy);
213     addImplicitTypedef("image1d_buffer_t", Context.OCLImage1dBufferTy);
214     addImplicitTypedef("image2d_t", Context.OCLImage2dTy);
215     addImplicitTypedef("image2d_array_t", Context.OCLImage2dArrayTy);
216     addImplicitTypedef("image3d_t", Context.OCLImage3dTy);
217     addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
218     addImplicitTypedef("event_t", Context.OCLEventTy);
219   }
220 
221   DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
222   if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
223     PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
224 }
225 
226 Sema::~Sema() {
227   llvm::DeleteContainerSeconds(LateParsedTemplateMap);
228   if (PackContext) FreePackedContext();
229   if (VisContext) FreeVisContext();
230   // Kill all the active scopes.
231   for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
232     delete FunctionScopes[I];
233   if (FunctionScopes.size() == 1)
234     delete FunctionScopes[0];
235 
236   // Tell the SemaConsumer to forget about us; we're going out of scope.
237   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
238     SC->ForgetSema();
239 
240   // Detach from the external Sema source.
241   if (ExternalSemaSource *ExternalSema
242         = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
243     ExternalSema->ForgetSema();
244 
245   // If Sema's ExternalSource is the multiplexer - we own it.
246   if (isMultiplexExternalSource)
247     delete ExternalSource;
248 
249   // Destroys data sharing attributes stack for OpenMP
250   DestroyDataSharingAttributesStack();
251 }
252 
253 /// makeUnavailableInSystemHeader - There is an error in the current
254 /// context.  If we're still in a system header, and we can plausibly
255 /// make the relevant declaration unavailable instead of erroring, do
256 /// so and return true.
257 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
258                                          StringRef msg) {
259   // If we're not in a function, it's an error.
260   FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
261   if (!fn) return false;
262 
263   // If we're in template instantiation, it's an error.
264   if (!ActiveTemplateInstantiations.empty())
265     return false;
266 
267   // If that function's not in a system header, it's an error.
268   if (!Context.getSourceManager().isInSystemHeader(loc))
269     return false;
270 
271   // If the function is already unavailable, it's not an error.
272   if (fn->hasAttr<UnavailableAttr>()) return true;
273 
274   fn->addAttr(UnavailableAttr::CreateImplicit(Context, msg, loc));
275   return true;
276 }
277 
278 ASTMutationListener *Sema::getASTMutationListener() const {
279   return getASTConsumer().GetASTMutationListener();
280 }
281 
282 ///\brief Registers an external source. If an external source already exists,
283 /// creates a multiplex external source and appends to it.
284 ///
285 ///\param[in] E - A non-null external sema source.
286 ///
287 void Sema::addExternalSource(ExternalSemaSource *E) {
288   assert(E && "Cannot use with NULL ptr");
289 
290   if (!ExternalSource) {
291     ExternalSource = E;
292     return;
293   }
294 
295   if (isMultiplexExternalSource)
296     static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
297   else {
298     ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
299     isMultiplexExternalSource = true;
300   }
301 }
302 
303 /// \brief Print out statistics about the semantic analysis.
304 void Sema::PrintStats() const {
305   llvm::errs() << "\n*** Semantic Analysis Stats:\n";
306   llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
307 
308   BumpAlloc.PrintStats();
309   AnalysisWarnings.PrintStats();
310 }
311 
312 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
313 /// If there is already an implicit cast, merge into the existing one.
314 /// The result is of the given category.
315 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
316                                    CastKind Kind, ExprValueKind VK,
317                                    const CXXCastPath *BasePath,
318                                    CheckedConversionKind CCK) {
319 #ifndef NDEBUG
320   if (VK == VK_RValue && !E->isRValue()) {
321     switch (Kind) {
322     default:
323       llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
324                        "kind");
325     case CK_LValueToRValue:
326     case CK_ArrayToPointerDecay:
327     case CK_FunctionToPointerDecay:
328     case CK_ToVoid:
329       break;
330     }
331   }
332   assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
333 #endif
334 
335   QualType ExprTy = Context.getCanonicalType(E->getType());
336   QualType TypeTy = Context.getCanonicalType(Ty);
337 
338   if (ExprTy == TypeTy)
339     return E;
340 
341   // If this is a derived-to-base cast to a through a virtual base, we
342   // need a vtable.
343   if (Kind == CK_DerivedToBase &&
344       BasePathInvolvesVirtualBase(*BasePath)) {
345     QualType T = E->getType();
346     if (const PointerType *Pointer = T->getAs<PointerType>())
347       T = Pointer->getPointeeType();
348     if (const RecordType *RecordTy = T->getAs<RecordType>())
349       MarkVTableUsed(E->getLocStart(),
350                      cast<CXXRecordDecl>(RecordTy->getDecl()));
351   }
352 
353   if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
354     if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
355       ImpCast->setType(Ty);
356       ImpCast->setValueKind(VK);
357       return E;
358     }
359   }
360 
361   return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
362 }
363 
364 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
365 /// to the conversion from scalar type ScalarTy to the Boolean type.
366 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
367   switch (ScalarTy->getScalarTypeKind()) {
368   case Type::STK_Bool: return CK_NoOp;
369   case Type::STK_CPointer: return CK_PointerToBoolean;
370   case Type::STK_BlockPointer: return CK_PointerToBoolean;
371   case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
372   case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
373   case Type::STK_Integral: return CK_IntegralToBoolean;
374   case Type::STK_Floating: return CK_FloatingToBoolean;
375   case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
376   case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
377   }
378   return CK_Invalid;
379 }
380 
381 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
382 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
383   if (D->getMostRecentDecl()->isUsed())
384     return true;
385 
386   if (D->isExternallyVisible())
387     return true;
388 
389   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
390     // UnusedFileScopedDecls stores the first declaration.
391     // The declaration may have become definition so check again.
392     const FunctionDecl *DeclToCheck;
393     if (FD->hasBody(DeclToCheck))
394       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
395 
396     // Later redecls may add new information resulting in not having to warn,
397     // so check again.
398     DeclToCheck = FD->getMostRecentDecl();
399     if (DeclToCheck != FD)
400       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
401   }
402 
403   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
404     // If a variable usable in constant expressions is referenced,
405     // don't warn if it isn't used: if the value of a variable is required
406     // for the computation of a constant expression, it doesn't make sense to
407     // warn even if the variable isn't odr-used.  (isReferenced doesn't
408     // precisely reflect that, but it's a decent approximation.)
409     if (VD->isReferenced() &&
410         VD->isUsableInConstantExpressions(SemaRef->Context))
411       return true;
412 
413     // UnusedFileScopedDecls stores the first declaration.
414     // The declaration may have become definition so check again.
415     const VarDecl *DeclToCheck = VD->getDefinition();
416     if (DeclToCheck)
417       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
418 
419     // Later redecls may add new information resulting in not having to warn,
420     // so check again.
421     DeclToCheck = VD->getMostRecentDecl();
422     if (DeclToCheck != VD)
423       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
424   }
425 
426   return false;
427 }
428 
429 /// Obtains a sorted list of functions that are undefined but ODR-used.
430 void Sema::getUndefinedButUsed(
431     SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
432   for (llvm::DenseMap<NamedDecl *, SourceLocation>::iterator
433          I = UndefinedButUsed.begin(), E = UndefinedButUsed.end();
434        I != E; ++I) {
435     NamedDecl *ND = I->first;
436 
437     // Ignore attributes that have become invalid.
438     if (ND->isInvalidDecl()) continue;
439 
440     // __attribute__((weakref)) is basically a definition.
441     if (ND->hasAttr<WeakRefAttr>()) continue;
442 
443     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
444       if (FD->isDefined())
445         continue;
446       if (FD->isExternallyVisible() &&
447           !FD->getMostRecentDecl()->isInlined())
448         continue;
449     } else {
450       if (cast<VarDecl>(ND)->hasDefinition() != VarDecl::DeclarationOnly)
451         continue;
452       if (ND->isExternallyVisible())
453         continue;
454     }
455 
456     Undefined.push_back(std::make_pair(ND, I->second));
457   }
458 
459   // Sort (in order of use site) so that we're not dependent on the iteration
460   // order through an llvm::DenseMap.
461   SourceManager &SM = Context.getSourceManager();
462   std::sort(Undefined.begin(), Undefined.end(),
463             [&SM](const std::pair<NamedDecl *, SourceLocation> &l,
464                   const std::pair<NamedDecl *, SourceLocation> &r) {
465     if (l.second.isValid() && !r.second.isValid())
466       return true;
467     if (!l.second.isValid() && r.second.isValid())
468       return false;
469     if (l.second != r.second)
470       return SM.isBeforeInTranslationUnit(l.second, r.second);
471     return SM.isBeforeInTranslationUnit(l.first->getLocation(),
472                                         r.first->getLocation());
473   });
474 }
475 
476 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
477 /// or that are inline.
478 static void checkUndefinedButUsed(Sema &S) {
479   if (S.UndefinedButUsed.empty()) return;
480 
481   // Collect all the still-undefined entities with internal linkage.
482   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
483   S.getUndefinedButUsed(Undefined);
484   if (Undefined.empty()) return;
485 
486   for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
487          I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
488     NamedDecl *ND = I->first;
489 
490     if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
491       // An exported function will always be emitted when defined, so even if
492       // the function is inline, it doesn't have to be emitted in this TU. An
493       // imported function implies that it has been exported somewhere else.
494       continue;
495     }
496 
497     if (!ND->isExternallyVisible()) {
498       S.Diag(ND->getLocation(), diag::warn_undefined_internal)
499         << isa<VarDecl>(ND) << ND;
500     } else {
501       assert(cast<FunctionDecl>(ND)->getMostRecentDecl()->isInlined() &&
502              "used object requires definition but isn't inline or internal?");
503       S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND;
504     }
505     if (I->second.isValid())
506       S.Diag(I->second, diag::note_used_here);
507   }
508 }
509 
510 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
511   if (!ExternalSource)
512     return;
513 
514   SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
515   ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
516   for (unsigned I = 0, N = WeakIDs.size(); I != N; ++I) {
517     llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator Pos
518       = WeakUndeclaredIdentifiers.find(WeakIDs[I].first);
519     if (Pos != WeakUndeclaredIdentifiers.end())
520       continue;
521 
522     WeakUndeclaredIdentifiers.insert(WeakIDs[I]);
523   }
524 }
525 
526 
527 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
528 
529 /// \brief Returns true, if all methods and nested classes of the given
530 /// CXXRecordDecl are defined in this translation unit.
531 ///
532 /// Should only be called from ActOnEndOfTranslationUnit so that all
533 /// definitions are actually read.
534 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
535                                             RecordCompleteMap &MNCComplete) {
536   RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
537   if (Cache != MNCComplete.end())
538     return Cache->second;
539   if (!RD->isCompleteDefinition())
540     return false;
541   bool Complete = true;
542   for (DeclContext::decl_iterator I = RD->decls_begin(),
543                                   E = RD->decls_end();
544        I != E && Complete; ++I) {
545     if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
546       Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M));
547     else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
548       Complete = F->getTemplatedDecl()->isDefined();
549     else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
550       if (R->isInjectedClassName())
551         continue;
552       if (R->hasDefinition())
553         Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
554                                                    MNCComplete);
555       else
556         Complete = false;
557     }
558   }
559   MNCComplete[RD] = Complete;
560   return Complete;
561 }
562 
563 /// \brief Returns true, if the given CXXRecordDecl is fully defined in this
564 /// translation unit, i.e. all methods are defined or pure virtual and all
565 /// friends, friend functions and nested classes are fully defined in this
566 /// translation unit.
567 ///
568 /// Should only be called from ActOnEndOfTranslationUnit so that all
569 /// definitions are actually read.
570 static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
571                                  RecordCompleteMap &RecordsComplete,
572                                  RecordCompleteMap &MNCComplete) {
573   RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
574   if (Cache != RecordsComplete.end())
575     return Cache->second;
576   bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
577   for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
578                                       E = RD->friend_end();
579        I != E && Complete; ++I) {
580     // Check if friend classes and methods are complete.
581     if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
582       // Friend classes are available as the TypeSourceInfo of the FriendDecl.
583       if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
584         Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
585       else
586         Complete = false;
587     } else {
588       // Friend functions are available through the NamedDecl of FriendDecl.
589       if (const FunctionDecl *FD =
590           dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
591         Complete = FD->isDefined();
592       else
593         // This is a template friend, give up.
594         Complete = false;
595     }
596   }
597   RecordsComplete[RD] = Complete;
598   return Complete;
599 }
600 
601 void Sema::emitAndClearUnusedLocalTypedefWarnings() {
602   if (ExternalSource)
603     ExternalSource->ReadUnusedLocalTypedefNameCandidates(
604         UnusedLocalTypedefNameCandidates);
605   for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
606     if (TD->isReferenced())
607       continue;
608     Diag(TD->getLocation(), diag::warn_unused_local_typedef)
609         << isa<TypeAliasDecl>(TD) << TD->getDeclName();
610   }
611   UnusedLocalTypedefNameCandidates.clear();
612 }
613 
614 /// ActOnEndOfTranslationUnit - This is called at the very end of the
615 /// translation unit when EOF is reached and all but the top-level scope is
616 /// popped.
617 void Sema::ActOnEndOfTranslationUnit() {
618   assert(DelayedDiagnostics.getCurrentPool() == nullptr
619          && "reached end of translation unit with a pool attached?");
620 
621   // If code completion is enabled, don't perform any end-of-translation-unit
622   // work.
623   if (PP.isCodeCompletionEnabled())
624     return;
625 
626   // Complete translation units and modules define vtables and perform implicit
627   // instantiations. PCH files do not.
628   if (TUKind != TU_Prefix) {
629     DiagnoseUseOfUnimplementedSelectors();
630 
631     // If any dynamic classes have their key function defined within
632     // this translation unit, then those vtables are considered "used" and must
633     // be emitted.
634     for (DynamicClassesType::iterator I = DynamicClasses.begin(ExternalSource),
635                                       E = DynamicClasses.end();
636          I != E; ++I) {
637       assert(!(*I)->isDependentType() &&
638              "Should not see dependent types here!");
639       if (const CXXMethodDecl *KeyFunction =
640               Context.getCurrentKeyFunction(*I)) {
641         const FunctionDecl *Definition = nullptr;
642         if (KeyFunction->hasBody(Definition))
643           MarkVTableUsed(Definition->getLocation(), *I, true);
644       }
645     }
646 
647     // If DefinedUsedVTables ends up marking any virtual member functions it
648     // might lead to more pending template instantiations, which we then need
649     // to instantiate.
650     DefineUsedVTables();
651 
652     // C++: Perform implicit template instantiations.
653     //
654     // FIXME: When we perform these implicit instantiations, we do not
655     // carefully keep track of the point of instantiation (C++ [temp.point]).
656     // This means that name lookup that occurs within the template
657     // instantiation will always happen at the end of the translation unit,
658     // so it will find some names that are not required to be found. This is
659     // valid, but we could do better by diagnosing if an instantiation uses a
660     // name that was not visible at its first point of instantiation.
661     if (ExternalSource) {
662       // Load pending instantiations from the external source.
663       SmallVector<PendingImplicitInstantiation, 4> Pending;
664       ExternalSource->ReadPendingInstantiations(Pending);
665       PendingInstantiations.insert(PendingInstantiations.begin(),
666                                    Pending.begin(), Pending.end());
667     }
668     PerformPendingInstantiations();
669 
670     CheckDelayedMemberExceptionSpecs();
671   }
672 
673   // All delayed member exception specs should be checked or we end up accepting
674   // incompatible declarations.
675   assert(DelayedDefaultedMemberExceptionSpecs.empty());
676   assert(DelayedDestructorExceptionSpecChecks.empty());
677 
678   // Remove file scoped decls that turned out to be used.
679   UnusedFileScopedDecls.erase(
680       std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
681                      UnusedFileScopedDecls.end(),
682                      std::bind1st(std::ptr_fun(ShouldRemoveFromUnused), this)),
683       UnusedFileScopedDecls.end());
684 
685   if (TUKind == TU_Prefix) {
686     // Translation unit prefixes don't need any of the checking below.
687     TUScope = nullptr;
688     return;
689   }
690 
691   // Check for #pragma weak identifiers that were never declared
692   // FIXME: This will cause diagnostics to be emitted in a non-determinstic
693   // order!  Iterating over a densemap like this is bad.
694   LoadExternalWeakUndeclaredIdentifiers();
695   for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
696        I = WeakUndeclaredIdentifiers.begin(),
697        E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
698     if (I->second.getUsed()) continue;
699 
700     Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
701       << I->first;
702   }
703 
704   if (LangOpts.CPlusPlus11 &&
705       !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
706     CheckDelegatingCtorCycles();
707 
708   if (TUKind == TU_Module) {
709     // If we are building a module, resolve all of the exported declarations
710     // now.
711     if (Module *CurrentModule = PP.getCurrentModule()) {
712       ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
713 
714       SmallVector<Module *, 2> Stack;
715       Stack.push_back(CurrentModule);
716       while (!Stack.empty()) {
717         Module *Mod = Stack.pop_back_val();
718 
719         // Resolve the exported declarations and conflicts.
720         // FIXME: Actually complain, once we figure out how to teach the
721         // diagnostic client to deal with complaints in the module map at this
722         // point.
723         ModMap.resolveExports(Mod, /*Complain=*/false);
724         ModMap.resolveUses(Mod, /*Complain=*/false);
725         ModMap.resolveConflicts(Mod, /*Complain=*/false);
726 
727         // Queue the submodules, so their exports will also be resolved.
728         for (Module::submodule_iterator Sub = Mod->submodule_begin(),
729                                      SubEnd = Mod->submodule_end();
730              Sub != SubEnd; ++Sub) {
731           Stack.push_back(*Sub);
732         }
733       }
734     }
735 
736     // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
737     // modules when they are built, not every time they are used.
738     emitAndClearUnusedLocalTypedefWarnings();
739 
740     // Modules don't need any of the checking below.
741     TUScope = nullptr;
742     return;
743   }
744 
745   // C99 6.9.2p2:
746   //   A declaration of an identifier for an object that has file
747   //   scope without an initializer, and without a storage-class
748   //   specifier or with the storage-class specifier static,
749   //   constitutes a tentative definition. If a translation unit
750   //   contains one or more tentative definitions for an identifier,
751   //   and the translation unit contains no external definition for
752   //   that identifier, then the behavior is exactly as if the
753   //   translation unit contains a file scope declaration of that
754   //   identifier, with the composite type as of the end of the
755   //   translation unit, with an initializer equal to 0.
756   llvm::SmallSet<VarDecl *, 32> Seen;
757   for (TentativeDefinitionsType::iterator
758             T = TentativeDefinitions.begin(ExternalSource),
759          TEnd = TentativeDefinitions.end();
760        T != TEnd; ++T)
761   {
762     VarDecl *VD = (*T)->getActingDefinition();
763 
764     // If the tentative definition was completed, getActingDefinition() returns
765     // null. If we've already seen this variable before, insert()'s second
766     // return value is false.
767     if (!VD || VD->isInvalidDecl() || !Seen.insert(VD))
768       continue;
769 
770     if (const IncompleteArrayType *ArrayT
771         = Context.getAsIncompleteArrayType(VD->getType())) {
772       // Set the length of the array to 1 (C99 6.9.2p5).
773       Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
774       llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
775       QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
776                                                 One, ArrayType::Normal, 0);
777       VD->setType(T);
778     } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
779                                    diag::err_tentative_def_incomplete_type))
780       VD->setInvalidDecl();
781 
782     CheckCompleteVariableDeclaration(VD);
783 
784     // Notify the consumer that we've completed a tentative definition.
785     if (!VD->isInvalidDecl())
786       Consumer.CompleteTentativeDefinition(VD);
787 
788   }
789 
790   // If there were errors, disable 'unused' warnings since they will mostly be
791   // noise.
792   if (!Diags.hasErrorOccurred()) {
793     // Output warning for unused file scoped decls.
794     for (UnusedFileScopedDeclsType::iterator
795            I = UnusedFileScopedDecls.begin(ExternalSource),
796            E = UnusedFileScopedDecls.end(); I != E; ++I) {
797       if (ShouldRemoveFromUnused(this, *I))
798         continue;
799 
800       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
801         const FunctionDecl *DiagD;
802         if (!FD->hasBody(DiagD))
803           DiagD = FD;
804         if (DiagD->isDeleted())
805           continue; // Deleted functions are supposed to be unused.
806         if (DiagD->isReferenced()) {
807           if (isa<CXXMethodDecl>(DiagD))
808             Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
809                   << DiagD->getDeclName();
810           else {
811             if (FD->getStorageClass() == SC_Static &&
812                 !FD->isInlineSpecified() &&
813                 !SourceMgr.isInMainFile(
814                    SourceMgr.getExpansionLoc(FD->getLocation())))
815               Diag(DiagD->getLocation(),
816                    diag::warn_unneeded_static_internal_decl)
817                   << DiagD->getDeclName();
818             else
819               Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
820                    << /*function*/0 << DiagD->getDeclName();
821           }
822         } else {
823           Diag(DiagD->getLocation(),
824                isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
825                                          : diag::warn_unused_function)
826                 << DiagD->getDeclName();
827         }
828       } else {
829         const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
830         if (!DiagD)
831           DiagD = cast<VarDecl>(*I);
832         if (DiagD->isReferenced()) {
833           Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
834                 << /*variable*/1 << DiagD->getDeclName();
835         } else if (DiagD->getType().isConstQualified()) {
836           Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
837               << DiagD->getDeclName();
838         } else {
839           Diag(DiagD->getLocation(), diag::warn_unused_variable)
840               << DiagD->getDeclName();
841         }
842       }
843     }
844 
845     if (ExternalSource)
846       ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
847     checkUndefinedButUsed(*this);
848 
849     emitAndClearUnusedLocalTypedefWarnings();
850   }
851 
852   if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
853     RecordCompleteMap RecordsComplete;
854     RecordCompleteMap MNCComplete;
855     for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
856          E = UnusedPrivateFields.end(); I != E; ++I) {
857       const NamedDecl *D = *I;
858       const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
859       if (RD && !RD->isUnion() &&
860           IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
861         Diag(D->getLocation(), diag::warn_unused_private_field)
862               << D->getDeclName();
863       }
864     }
865   }
866 
867   // Check we've noticed that we're no longer parsing the initializer for every
868   // variable. If we miss cases, then at best we have a performance issue and
869   // at worst a rejects-valid bug.
870   assert(ParsingInitForAutoVars.empty() &&
871          "Didn't unmark var as having its initializer parsed");
872 
873   TUScope = nullptr;
874 }
875 
876 
877 //===----------------------------------------------------------------------===//
878 // Helper functions.
879 //===----------------------------------------------------------------------===//
880 
881 DeclContext *Sema::getFunctionLevelDeclContext() {
882   DeclContext *DC = CurContext;
883 
884   while (true) {
885     if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
886       DC = DC->getParent();
887     } else if (isa<CXXMethodDecl>(DC) &&
888                cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
889                cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
890       DC = DC->getParent()->getParent();
891     }
892     else break;
893   }
894 
895   return DC;
896 }
897 
898 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
899 /// to the function decl for the function being parsed.  If we're currently
900 /// in a 'block', this returns the containing context.
901 FunctionDecl *Sema::getCurFunctionDecl() {
902   DeclContext *DC = getFunctionLevelDeclContext();
903   return dyn_cast<FunctionDecl>(DC);
904 }
905 
906 ObjCMethodDecl *Sema::getCurMethodDecl() {
907   DeclContext *DC = getFunctionLevelDeclContext();
908   while (isa<RecordDecl>(DC))
909     DC = DC->getParent();
910   return dyn_cast<ObjCMethodDecl>(DC);
911 }
912 
913 NamedDecl *Sema::getCurFunctionOrMethodDecl() {
914   DeclContext *DC = getFunctionLevelDeclContext();
915   if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
916     return cast<NamedDecl>(DC);
917   return nullptr;
918 }
919 
920 void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
921   // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
922   // and yet we also use the current diag ID on the DiagnosticsEngine. This has
923   // been made more painfully obvious by the refactor that introduced this
924   // function, but it is possible that the incoming argument can be
925   // eliminnated. If it truly cannot be (for example, there is some reentrancy
926   // issue I am not seeing yet), then there should at least be a clarifying
927   // comment somewhere.
928   if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
929     switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
930               Diags.getCurrentDiagID())) {
931     case DiagnosticIDs::SFINAE_Report:
932       // We'll report the diagnostic below.
933       break;
934 
935     case DiagnosticIDs::SFINAE_SubstitutionFailure:
936       // Count this failure so that we know that template argument deduction
937       // has failed.
938       ++NumSFINAEErrors;
939 
940       // Make a copy of this suppressed diagnostic and store it with the
941       // template-deduction information.
942       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
943         Diagnostic DiagInfo(&Diags);
944         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
945                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
946       }
947 
948       Diags.setLastDiagnosticIgnored();
949       Diags.Clear();
950       return;
951 
952     case DiagnosticIDs::SFINAE_AccessControl: {
953       // Per C++ Core Issue 1170, access control is part of SFINAE.
954       // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
955       // make access control a part of SFINAE for the purposes of checking
956       // type traits.
957       if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
958         break;
959 
960       SourceLocation Loc = Diags.getCurrentDiagLoc();
961 
962       // Suppress this diagnostic.
963       ++NumSFINAEErrors;
964 
965       // Make a copy of this suppressed diagnostic and store it with the
966       // template-deduction information.
967       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
968         Diagnostic DiagInfo(&Diags);
969         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
970                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
971       }
972 
973       Diags.setLastDiagnosticIgnored();
974       Diags.Clear();
975 
976       // Now the diagnostic state is clear, produce a C++98 compatibility
977       // warning.
978       Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
979 
980       // The last diagnostic which Sema produced was ignored. Suppress any
981       // notes attached to it.
982       Diags.setLastDiagnosticIgnored();
983       return;
984     }
985 
986     case DiagnosticIDs::SFINAE_Suppress:
987       // Make a copy of this suppressed diagnostic and store it with the
988       // template-deduction information;
989       if (*Info) {
990         Diagnostic DiagInfo(&Diags);
991         (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
992                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
993       }
994 
995       // Suppress this diagnostic.
996       Diags.setLastDiagnosticIgnored();
997       Diags.Clear();
998       return;
999     }
1000   }
1001 
1002   // Set up the context's printing policy based on our current state.
1003   Context.setPrintingPolicy(getPrintingPolicy());
1004 
1005   // Emit the diagnostic.
1006   if (!Diags.EmitCurrentDiagnostic())
1007     return;
1008 
1009   // If this is not a note, and we're in a template instantiation
1010   // that is different from the last template instantiation where
1011   // we emitted an error, print a template instantiation
1012   // backtrace.
1013   if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
1014       !ActiveTemplateInstantiations.empty() &&
1015       ActiveTemplateInstantiations.back()
1016         != LastTemplateInstantiationErrorContext) {
1017     PrintInstantiationStack();
1018     LastTemplateInstantiationErrorContext = ActiveTemplateInstantiations.back();
1019   }
1020 }
1021 
1022 Sema::SemaDiagnosticBuilder
1023 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
1024   SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
1025   PD.Emit(Builder);
1026 
1027   return Builder;
1028 }
1029 
1030 /// \brief Looks through the macro-expansion chain for the given
1031 /// location, looking for a macro expansion with the given name.
1032 /// If one is found, returns true and sets the location to that
1033 /// expansion loc.
1034 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
1035   SourceLocation loc = locref;
1036   if (!loc.isMacroID()) return false;
1037 
1038   // There's no good way right now to look at the intermediate
1039   // expansions, so just jump to the expansion location.
1040   loc = getSourceManager().getExpansionLoc(loc);
1041 
1042   // If that's written with the name, stop here.
1043   SmallVector<char, 16> buffer;
1044   if (getPreprocessor().getSpelling(loc, buffer) == name) {
1045     locref = loc;
1046     return true;
1047   }
1048   return false;
1049 }
1050 
1051 /// \brief Determines the active Scope associated with the given declaration
1052 /// context.
1053 ///
1054 /// This routine maps a declaration context to the active Scope object that
1055 /// represents that declaration context in the parser. It is typically used
1056 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1057 /// declarations) that injects a name for name-lookup purposes and, therefore,
1058 /// must update the Scope.
1059 ///
1060 /// \returns The scope corresponding to the given declaraion context, or NULL
1061 /// if no such scope is open.
1062 Scope *Sema::getScopeForContext(DeclContext *Ctx) {
1063 
1064   if (!Ctx)
1065     return nullptr;
1066 
1067   Ctx = Ctx->getPrimaryContext();
1068   for (Scope *S = getCurScope(); S; S = S->getParent()) {
1069     // Ignore scopes that cannot have declarations. This is important for
1070     // out-of-line definitions of static class members.
1071     if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
1072       if (DeclContext *Entity = S->getEntity())
1073         if (Ctx == Entity->getPrimaryContext())
1074           return S;
1075   }
1076 
1077   return nullptr;
1078 }
1079 
1080 /// \brief Enter a new function scope
1081 void Sema::PushFunctionScope() {
1082   if (FunctionScopes.size() == 1) {
1083     // Use the "top" function scope rather than having to allocate
1084     // memory for a new scope.
1085     FunctionScopes.back()->Clear();
1086     FunctionScopes.push_back(FunctionScopes.back());
1087     return;
1088   }
1089 
1090   FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
1091 }
1092 
1093 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
1094   FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
1095                                               BlockScope, Block));
1096 }
1097 
1098 LambdaScopeInfo *Sema::PushLambdaScope() {
1099   LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
1100   FunctionScopes.push_back(LSI);
1101   return LSI;
1102 }
1103 
1104 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
1105   if (LambdaScopeInfo *const LSI = getCurLambda()) {
1106     LSI->AutoTemplateParameterDepth = Depth;
1107     return;
1108   }
1109   llvm_unreachable(
1110       "Remove assertion if intentionally called in a non-lambda context.");
1111 }
1112 
1113 void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
1114                                 const Decl *D, const BlockExpr *blkExpr) {
1115   FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
1116   assert(!FunctionScopes.empty() && "mismatched push/pop!");
1117 
1118   // Issue any analysis-based warnings.
1119   if (WP && D)
1120     AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
1121   else
1122     for (const auto &PUD : Scope->PossiblyUnreachableDiags)
1123       Diag(PUD.Loc, PUD.PD);
1124 
1125   if (FunctionScopes.back() != Scope)
1126     delete Scope;
1127 }
1128 
1129 void Sema::PushCompoundScope() {
1130   getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo());
1131 }
1132 
1133 void Sema::PopCompoundScope() {
1134   FunctionScopeInfo *CurFunction = getCurFunction();
1135   assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
1136 
1137   CurFunction->CompoundScopes.pop_back();
1138 }
1139 
1140 /// \brief Determine whether any errors occurred within this function/method/
1141 /// block.
1142 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
1143   return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
1144 }
1145 
1146 BlockScopeInfo *Sema::getCurBlock() {
1147   if (FunctionScopes.empty())
1148     return nullptr;
1149 
1150   auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
1151   if (CurBSI && CurBSI->TheDecl &&
1152       !CurBSI->TheDecl->Encloses(CurContext)) {
1153     // We have switched contexts due to template instantiation.
1154     assert(!ActiveTemplateInstantiations.empty());
1155     return nullptr;
1156   }
1157 
1158   return CurBSI;
1159 }
1160 
1161 LambdaScopeInfo *Sema::getCurLambda() {
1162   if (FunctionScopes.empty())
1163     return nullptr;
1164 
1165   auto CurLSI = dyn_cast<LambdaScopeInfo>(FunctionScopes.back());
1166   if (CurLSI && CurLSI->Lambda &&
1167       !CurLSI->Lambda->Encloses(CurContext)) {
1168     // We have switched contexts due to template instantiation.
1169     assert(!ActiveTemplateInstantiations.empty());
1170     return nullptr;
1171   }
1172 
1173   return CurLSI;
1174 }
1175 // We have a generic lambda if we parsed auto parameters, or we have
1176 // an associated template parameter list.
1177 LambdaScopeInfo *Sema::getCurGenericLambda() {
1178   if (LambdaScopeInfo *LSI =  getCurLambda()) {
1179     return (LSI->AutoTemplateParams.size() ||
1180                     LSI->GLTemplateParameterList) ? LSI : nullptr;
1181   }
1182   return nullptr;
1183 }
1184 
1185 
1186 void Sema::ActOnComment(SourceRange Comment) {
1187   if (!LangOpts.RetainCommentsFromSystemHeaders &&
1188       SourceMgr.isInSystemHeader(Comment.getBegin()))
1189     return;
1190   RawComment RC(SourceMgr, Comment, false,
1191                 LangOpts.CommentOpts.ParseAllComments);
1192   if (RC.isAlmostTrailingComment()) {
1193     SourceRange MagicMarkerRange(Comment.getBegin(),
1194                                  Comment.getBegin().getLocWithOffset(3));
1195     StringRef MagicMarkerText;
1196     switch (RC.getKind()) {
1197     case RawComment::RCK_OrdinaryBCPL:
1198       MagicMarkerText = "///<";
1199       break;
1200     case RawComment::RCK_OrdinaryC:
1201       MagicMarkerText = "/**<";
1202       break;
1203     default:
1204       llvm_unreachable("if this is an almost Doxygen comment, "
1205                        "it should be ordinary");
1206     }
1207     Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
1208       FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
1209   }
1210   Context.addComment(RC);
1211 }
1212 
1213 // Pin this vtable to this file.
1214 ExternalSemaSource::~ExternalSemaSource() {}
1215 
1216 void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
1217 
1218 void ExternalSemaSource::ReadKnownNamespaces(
1219                            SmallVectorImpl<NamespaceDecl *> &Namespaces) {
1220 }
1221 
1222 void ExternalSemaSource::ReadUndefinedButUsed(
1223                        llvm::DenseMap<NamedDecl *, SourceLocation> &Undefined) {
1224 }
1225 
1226 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
1227   SourceLocation Loc = this->Loc;
1228   if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
1229   if (Loc.isValid()) {
1230     Loc.print(OS, S.getSourceManager());
1231     OS << ": ";
1232   }
1233   OS << Message;
1234 
1235   if (TheDecl && isa<NamedDecl>(TheDecl)) {
1236     std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
1237     if (!Name.empty())
1238       OS << " '" << Name << '\'';
1239   }
1240 
1241   OS << '\n';
1242 }
1243 
1244 /// \brief Figure out if an expression could be turned into a call.
1245 ///
1246 /// Use this when trying to recover from an error where the programmer may have
1247 /// written just the name of a function instead of actually calling it.
1248 ///
1249 /// \param E - The expression to examine.
1250 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1251 ///  with no arguments, this parameter is set to the type returned by such a
1252 ///  call; otherwise, it is set to an empty QualType.
1253 /// \param OverloadSet - If the expression is an overloaded function
1254 ///  name, this parameter is populated with the decls of the various overloads.
1255 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1256                          UnresolvedSetImpl &OverloadSet) {
1257   ZeroArgCallReturnTy = QualType();
1258   OverloadSet.clear();
1259 
1260   const OverloadExpr *Overloads = nullptr;
1261   bool IsMemExpr = false;
1262   if (E.getType() == Context.OverloadTy) {
1263     OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
1264 
1265     // Ignore overloads that are pointer-to-member constants.
1266     if (FR.HasFormOfMemberPointer)
1267       return false;
1268 
1269     Overloads = FR.Expression;
1270   } else if (E.getType() == Context.BoundMemberTy) {
1271     Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
1272     IsMemExpr = true;
1273   }
1274 
1275   bool Ambiguous = false;
1276 
1277   if (Overloads) {
1278     for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
1279          DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
1280       OverloadSet.addDecl(*it);
1281 
1282       // Check whether the function is a non-template, non-member which takes no
1283       // arguments.
1284       if (IsMemExpr)
1285         continue;
1286       if (const FunctionDecl *OverloadDecl
1287             = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
1288         if (OverloadDecl->getMinRequiredArguments() == 0) {
1289           if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
1290             ZeroArgCallReturnTy = QualType();
1291             Ambiguous = true;
1292           } else
1293             ZeroArgCallReturnTy = OverloadDecl->getReturnType();
1294         }
1295       }
1296     }
1297 
1298     // If it's not a member, use better machinery to try to resolve the call
1299     if (!IsMemExpr)
1300       return !ZeroArgCallReturnTy.isNull();
1301   }
1302 
1303   // Attempt to call the member with no arguments - this will correctly handle
1304   // member templates with defaults/deduction of template arguments, overloads
1305   // with default arguments, etc.
1306   if (IsMemExpr && !E.isTypeDependent()) {
1307     bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
1308     getDiagnostics().setSuppressAllDiagnostics(true);
1309     ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
1310                                              None, SourceLocation());
1311     getDiagnostics().setSuppressAllDiagnostics(Suppress);
1312     if (R.isUsable()) {
1313       ZeroArgCallReturnTy = R.get()->getType();
1314       return true;
1315     }
1316     return false;
1317   }
1318 
1319   if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
1320     if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
1321       if (Fun->getMinRequiredArguments() == 0)
1322         ZeroArgCallReturnTy = Fun->getReturnType();
1323       return true;
1324     }
1325   }
1326 
1327   // We don't have an expression that's convenient to get a FunctionDecl from,
1328   // but we can at least check if the type is "function of 0 arguments".
1329   QualType ExprTy = E.getType();
1330   const FunctionType *FunTy = nullptr;
1331   QualType PointeeTy = ExprTy->getPointeeType();
1332   if (!PointeeTy.isNull())
1333     FunTy = PointeeTy->getAs<FunctionType>();
1334   if (!FunTy)
1335     FunTy = ExprTy->getAs<FunctionType>();
1336 
1337   if (const FunctionProtoType *FPT =
1338       dyn_cast_or_null<FunctionProtoType>(FunTy)) {
1339     if (FPT->getNumParams() == 0)
1340       ZeroArgCallReturnTy = FunTy->getReturnType();
1341     return true;
1342   }
1343   return false;
1344 }
1345 
1346 /// \brief Give notes for a set of overloads.
1347 ///
1348 /// A companion to tryExprAsCall. In cases when the name that the programmer
1349 /// wrote was an overloaded function, we may be able to make some guesses about
1350 /// plausible overloads based on their return types; such guesses can be handed
1351 /// off to this method to be emitted as notes.
1352 ///
1353 /// \param Overloads - The overloads to note.
1354 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
1355 ///  -fshow-overloads=best, this is the location to attach to the note about too
1356 ///  many candidates. Typically this will be the location of the original
1357 ///  ill-formed expression.
1358 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
1359                           const SourceLocation FinalNoteLoc) {
1360   int ShownOverloads = 0;
1361   int SuppressedOverloads = 0;
1362   for (UnresolvedSetImpl::iterator It = Overloads.begin(),
1363        DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1364     // FIXME: Magic number for max shown overloads stolen from
1365     // OverloadCandidateSet::NoteCandidates.
1366     if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
1367       ++SuppressedOverloads;
1368       continue;
1369     }
1370 
1371     NamedDecl *Fn = (*It)->getUnderlyingDecl();
1372     S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
1373     ++ShownOverloads;
1374   }
1375 
1376   if (SuppressedOverloads)
1377     S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
1378       << SuppressedOverloads;
1379 }
1380 
1381 static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
1382                                    const UnresolvedSetImpl &Overloads,
1383                                    bool (*IsPlausibleResult)(QualType)) {
1384   if (!IsPlausibleResult)
1385     return noteOverloads(S, Overloads, Loc);
1386 
1387   UnresolvedSet<2> PlausibleOverloads;
1388   for (OverloadExpr::decls_iterator It = Overloads.begin(),
1389          DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1390     const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1391     QualType OverloadResultTy = OverloadDecl->getReturnType();
1392     if (IsPlausibleResult(OverloadResultTy))
1393       PlausibleOverloads.addDecl(It.getDecl());
1394   }
1395   noteOverloads(S, PlausibleOverloads, Loc);
1396 }
1397 
1398 /// Determine whether the given expression can be called by just
1399 /// putting parentheses after it.  Notably, expressions with unary
1400 /// operators can't be because the unary operator will start parsing
1401 /// outside the call.
1402 static bool IsCallableWithAppend(Expr *E) {
1403   E = E->IgnoreImplicit();
1404   return (!isa<CStyleCastExpr>(E) &&
1405           !isa<UnaryOperator>(E) &&
1406           !isa<BinaryOperator>(E) &&
1407           !isa<CXXOperatorCallExpr>(E));
1408 }
1409 
1410 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1411                                 bool ForceComplain,
1412                                 bool (*IsPlausibleResult)(QualType)) {
1413   SourceLocation Loc = E.get()->getExprLoc();
1414   SourceRange Range = E.get()->getSourceRange();
1415 
1416   QualType ZeroArgCallTy;
1417   UnresolvedSet<4> Overloads;
1418   if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
1419       !ZeroArgCallTy.isNull() &&
1420       (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
1421     // At this point, we know E is potentially callable with 0
1422     // arguments and that it returns something of a reasonable type,
1423     // so we can emit a fixit and carry on pretending that E was
1424     // actually a CallExpr.
1425     SourceLocation ParenInsertionLoc = PP.getLocForEndOfToken(Range.getEnd());
1426     Diag(Loc, PD)
1427       << /*zero-arg*/ 1 << Range
1428       << (IsCallableWithAppend(E.get())
1429           ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
1430           : FixItHint());
1431     notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1432 
1433     // FIXME: Try this before emitting the fixit, and suppress diagnostics
1434     // while doing so.
1435     E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None,
1436                       Range.getEnd().getLocWithOffset(1));
1437     return true;
1438   }
1439 
1440   if (!ForceComplain) return false;
1441 
1442   Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
1443   notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1444   E = ExprError();
1445   return true;
1446 }
1447 
1448 IdentifierInfo *Sema::getSuperIdentifier() const {
1449   if (!Ident_super)
1450     Ident_super = &Context.Idents.get("super");
1451   return Ident_super;
1452 }
1453 
1454 IdentifierInfo *Sema::getFloat128Identifier() const {
1455   if (!Ident___float128)
1456     Ident___float128 = &Context.Idents.get("__float128");
1457   return Ident___float128;
1458 }
1459 
1460 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
1461                                    CapturedRegionKind K) {
1462   CapturingScopeInfo *CSI = new CapturedRegionScopeInfo(
1463       getDiagnostics(), S, CD, RD, CD->getContextParam(), K);
1464   CSI->ReturnType = Context.VoidTy;
1465   FunctionScopes.push_back(CSI);
1466 }
1467 
1468 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
1469   if (FunctionScopes.empty())
1470     return nullptr;
1471 
1472   return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
1473 }
1474