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