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