1//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the actions class which performs semantic analysis and
10// builds an AST out of a parse stream.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SemaAPINotesInternal.h"
15#include "UsedDeclVisitor.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTDiagnostic.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclFriend.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/PrettyDeclStackTrace.h"
25#include "clang/AST/StmtCXX.h"
26#include "clang/AST/TypeOrdering.h"
27#include "clang/Basic/DarwinSDKInfo.h"
28#include "clang/Basic/DiagnosticOptions.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Lex/HeaderSearch.h"
33#include "clang/Lex/HeaderSearchOptions.h"
34#include "clang/Lex/Preprocessor.h"
35#include "clang/Sema/CXXFieldCollector.h"
36#include "clang/Sema/EnterExpressionEvaluationContext.h"
37#include "clang/Sema/ExternalSemaSource.h"
38#include "clang/Sema/Initialization.h"
39#include "clang/Sema/MultiplexExternalSemaSource.h"
40#include "clang/Sema/ObjCMethodList.h"
41#include "clang/Sema/RISCVIntrinsicManager.h"
42#include "clang/Sema/Scope.h"
43#include "clang/Sema/ScopeInfo.h"
44#include "clang/Sema/SemaAMDGPU.h"
45#include "clang/Sema/SemaARM.h"
46#include "clang/Sema/SemaAVR.h"
47#include "clang/Sema/SemaBPF.h"
48#include "clang/Sema/SemaCUDA.h"
49#include "clang/Sema/SemaCodeCompletion.h"
50#include "clang/Sema/SemaConsumer.h"
51#include "clang/Sema/SemaDirectX.h"
52#include "clang/Sema/SemaHLSL.h"
53#include "clang/Sema/SemaHexagon.h"
54#include "clang/Sema/SemaLoongArch.h"
55#include "clang/Sema/SemaM68k.h"
56#include "clang/Sema/SemaMIPS.h"
57#include "clang/Sema/SemaMSP430.h"
58#include "clang/Sema/SemaNVPTX.h"
59#include "clang/Sema/SemaObjC.h"
60#include "clang/Sema/SemaOpenACC.h"
61#include "clang/Sema/SemaOpenCL.h"
62#include "clang/Sema/SemaOpenMP.h"
63#include "clang/Sema/SemaPPC.h"
64#include "clang/Sema/SemaPseudoObject.h"
65#include "clang/Sema/SemaRISCV.h"
66#include "clang/Sema/SemaSPIRV.h"
67#include "clang/Sema/SemaSYCL.h"
68#include "clang/Sema/SemaSwift.h"
69#include "clang/Sema/SemaSystemZ.h"
70#include "clang/Sema/SemaWasm.h"
71#include "clang/Sema/SemaX86.h"
72#include "clang/Sema/TemplateDeduction.h"
73#include "clang/Sema/TypoCorrection.h"
74#include "llvm/ADT/DenseMap.h"
75#include "llvm/ADT/STLExtras.h"
76#include "llvm/ADT/SetVector.h"
77#include "llvm/ADT/SmallPtrSet.h"
78#include "llvm/Support/TimeProfiler.h"
79#include <optional>
80
81using namespace clang;
82using namespace sema;
83
84SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
85 return Lexer::getLocForEndOfToken(Loc, Offset, SM: SourceMgr, LangOpts);
86}
87
88SourceRange
89Sema::getRangeForNextToken(SourceLocation Loc, bool IncludeMacros,
90 bool IncludeComments,
91 std::optional<tok::TokenKind> ExpectedToken) {
92 if (!Loc.isValid())
93 return SourceRange();
94 std::optional<Token> NextToken =
95 Lexer::findNextToken(Loc, SM: SourceMgr, LangOpts, IncludeComments);
96 if (!NextToken)
97 return SourceRange();
98 if (ExpectedToken && NextToken->getKind() != *ExpectedToken)
99 return SourceRange();
100 SourceLocation TokenStart = NextToken->getLocation();
101 SourceLocation TokenEnd = NextToken->getLastLoc();
102 if (!TokenStart.isValid() || !TokenEnd.isValid())
103 return SourceRange();
104 if (!IncludeMacros && (TokenStart.isMacroID() || TokenEnd.isMacroID()))
105 return SourceRange();
106
107 return SourceRange(TokenStart, TokenEnd);
108}
109
110ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
111
112DarwinSDKInfo *
113Sema::getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
114 StringRef Platform) {
115 auto *SDKInfo = getDarwinSDKInfoForAvailabilityChecking();
116 if (!SDKInfo && !WarnedDarwinSDKInfoMissing) {
117 Diag(Loc, DiagID: diag::warn_missing_sdksettings_for_availability_checking)
118 << Platform;
119 WarnedDarwinSDKInfoMissing = true;
120 }
121 return SDKInfo;
122}
123
124DarwinSDKInfo *Sema::getDarwinSDKInfoForAvailabilityChecking() {
125 if (CachedDarwinSDKInfo)
126 return CachedDarwinSDKInfo->get();
127 auto SDKInfo = parseDarwinSDKInfo(
128 VFS&: PP.getFileManager().getVirtualFileSystem(),
129 SDKRootPath: PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot);
130 if (SDKInfo && *SDKInfo) {
131 CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(args: std::move(**SDKInfo));
132 return CachedDarwinSDKInfo->get();
133 }
134 if (!SDKInfo)
135 llvm::consumeError(Err: SDKInfo.takeError());
136 CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>();
137 return nullptr;
138}
139
140IdentifierInfo *Sema::InventAbbreviatedTemplateParameterTypeName(
141 const IdentifierInfo *ParamName, unsigned int Index) {
142 std::string InventedName;
143 llvm::raw_string_ostream OS(InventedName);
144
145 if (!ParamName)
146 OS << "auto:" << Index + 1;
147 else
148 OS << ParamName->getName() << ":auto";
149
150 return &Context.Idents.get(Name: OS.str());
151}
152
153PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
154 const Preprocessor &PP) {
155 PrintingPolicy Policy = Context.getPrintingPolicy();
156 // In diagnostics, we print _Bool as bool if the latter is defined as the
157 // former.
158 Policy.Bool = Context.getLangOpts().Bool;
159 if (!Policy.Bool) {
160 if (const MacroInfo *BoolMacro = PP.getMacroInfo(II: Context.getBoolName())) {
161 Policy.Bool = BoolMacro->isObjectLike() &&
162 BoolMacro->getNumTokens() == 1 &&
163 BoolMacro->getReplacementToken(Tok: 0).is(K: tok::kw__Bool);
164 }
165 }
166
167 // Shorten the data output if needed
168 Policy.EntireContentsOfLargeArray = false;
169
170 return Policy;
171}
172
173void Sema::ActOnTranslationUnitScope(Scope *S) {
174 TUScope = S;
175 PushDeclContext(S, DC: Context.getTranslationUnitDecl());
176}
177
178namespace clang {
179namespace sema {
180
181class SemaPPCallbacks : public PPCallbacks {
182 Sema *S = nullptr;
183 llvm::SmallVector<SourceLocation, 8> IncludeStack;
184 llvm::SmallVector<llvm::TimeTraceProfilerEntry *, 8> ProfilerStack;
185
186public:
187 void set(Sema &S) { this->S = &S; }
188
189 void reset() { S = nullptr; }
190
191 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
192 SrcMgr::CharacteristicKind FileType,
193 FileID PrevFID) override {
194 if (!S)
195 return;
196 switch (Reason) {
197 case EnterFile: {
198 SourceManager &SM = S->getSourceManager();
199 SourceLocation IncludeLoc = SM.getIncludeLoc(FID: SM.getFileID(SpellingLoc: Loc));
200 if (IncludeLoc.isValid()) {
201 if (llvm::timeTraceProfilerEnabled()) {
202 OptionalFileEntryRef FE = SM.getFileEntryRefForID(FID: SM.getFileID(SpellingLoc: Loc));
203 ProfilerStack.push_back(Elt: llvm::timeTraceAsyncProfilerBegin(
204 Name: "Source", Detail: FE ? FE->getName() : StringRef("<unknown>")));
205 }
206
207 IncludeStack.push_back(Elt: IncludeLoc);
208 S->DiagnoseNonDefaultPragmaAlignPack(
209 Kind: Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude,
210 IncludeLoc);
211 }
212 break;
213 }
214 case ExitFile:
215 if (!IncludeStack.empty()) {
216 if (llvm::timeTraceProfilerEnabled())
217 llvm::timeTraceProfilerEnd(E: ProfilerStack.pop_back_val());
218
219 S->DiagnoseNonDefaultPragmaAlignPack(
220 Kind: Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit,
221 IncludeLoc: IncludeStack.pop_back_val());
222 }
223 break;
224 default:
225 break;
226 }
227 }
228 void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
229 diag::Severity Mapping, StringRef Str) override {
230 // The pragma changed diagnostic severities; drop any cached analysis
231 // warning policies derived from the previous state.
232 S->AnalysisWarnings.clearPolicyCache();
233
234 // If one of the analysis-based diagnostics was enabled while processing
235 // a function, we want to note it in the analysis-based warnings so they
236 // can be run at the end of the function body even if the analysis warnings
237 // are disabled at that point.
238 SmallVector<diag::kind, 256> GroupDiags;
239 diag::Flavor Flavor =
240 Str[1] == 'W' ? diag::Flavor::WarningOrError : diag::Flavor::Remark;
241 StringRef Group = Str.substr(Start: 2);
242
243 if (S->PP.getDiagnostics().getDiagnosticIDs()->getDiagnosticsInGroup(
244 Flavor, Group, Diags&: GroupDiags))
245 return;
246
247 for (diag::kind K : GroupDiags) {
248 // Note: the cases in this switch should be kept in sync with the
249 // diagnostics in AnalysisBasedWarnings::getPolicyInEffectAt().
250 AnalysisBasedWarnings::Policy &Override =
251 S->AnalysisWarnings.getPolicyOverrides();
252 switch (K) {
253 default: break;
254 case diag::warn_unreachable:
255 case diag::warn_unreachable_break:
256 case diag::warn_unreachable_return:
257 case diag::warn_unreachable_loop_increment:
258 Override.enableCheckUnreachable = true;
259 break;
260 case diag::warn_double_lock:
261 Override.enableThreadSafetyAnalysis = true;
262 break;
263 case diag::warn_use_in_invalid_state:
264 Override.enableConsumedAnalysis = true;
265 break;
266 }
267 }
268 }
269};
270
271} // end namespace sema
272} // end namespace clang
273
274const unsigned Sema::MaxAlignmentExponent;
275const uint64_t Sema::MaximumAlignment;
276
277Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
278 TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
279 : SemaBase(*this), CollectStats(false), TUKind(TUKind),
280 CurFPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
281 Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
282 SourceMgr(PP.getSourceManager()), APINotes(SourceMgr, LangOpts),
283 AnalysisWarnings(*this), ThreadSafetyDeclCache(nullptr),
284 LateTemplateParser(nullptr), OpaqueParser(nullptr), CurContext(nullptr),
285 ExternalSource(nullptr), StackHandler(Diags), CurScope(nullptr),
286 Ident_super(nullptr), AMDGPUPtr(std::make_unique<SemaAMDGPU>(args&: *this)),
287 ARMPtr(std::make_unique<SemaARM>(args&: *this)),
288 AVRPtr(std::make_unique<SemaAVR>(args&: *this)),
289 BPFPtr(std::make_unique<SemaBPF>(args&: *this)),
290 CodeCompletionPtr(
291 std::make_unique<SemaCodeCompletion>(args&: *this, args&: CodeCompleter)),
292 CUDAPtr(std::make_unique<SemaCUDA>(args&: *this)),
293 DirectXPtr(std::make_unique<SemaDirectX>(args&: *this)),
294 HLSLPtr(std::make_unique<SemaHLSL>(args&: *this)),
295 HexagonPtr(std::make_unique<SemaHexagon>(args&: *this)),
296 LoongArchPtr(std::make_unique<SemaLoongArch>(args&: *this)),
297 M68kPtr(std::make_unique<SemaM68k>(args&: *this)),
298 MIPSPtr(std::make_unique<SemaMIPS>(args&: *this)),
299 MSP430Ptr(std::make_unique<SemaMSP430>(args&: *this)),
300 NVPTXPtr(std::make_unique<SemaNVPTX>(args&: *this)),
301 ObjCPtr(std::make_unique<SemaObjC>(args&: *this)),
302 OpenACCPtr(std::make_unique<SemaOpenACC>(args&: *this)),
303 OpenCLPtr(std::make_unique<SemaOpenCL>(args&: *this)),
304 OpenMPPtr(std::make_unique<SemaOpenMP>(args&: *this)),
305 PPCPtr(std::make_unique<SemaPPC>(args&: *this)),
306 PseudoObjectPtr(std::make_unique<SemaPseudoObject>(args&: *this)),
307 RISCVPtr(std::make_unique<SemaRISCV>(args&: *this)),
308 SPIRVPtr(std::make_unique<SemaSPIRV>(args&: *this)),
309 SYCLPtr(std::make_unique<SemaSYCL>(args&: *this)),
310 SwiftPtr(std::make_unique<SemaSwift>(args&: *this)),
311 SystemZPtr(std::make_unique<SemaSystemZ>(args&: *this)),
312 WasmPtr(std::make_unique<SemaWasm>(args&: *this)),
313 X86Ptr(std::make_unique<SemaX86>(args&: *this)),
314 MSPointerToMemberRepresentationMethod(
315 LangOpts.getMSPointerToMemberRepresentationMethod()),
316 MSStructPragmaOn(false), VtorDispStack(LangOpts.getVtorDispMode()),
317 AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)),
318 DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
319 CodeSegStack(nullptr), StrictGuardStackCheckStack(false),
320 FpPragmaStack(FPOptionsOverride()), CurInitSeg(nullptr),
321 VisContext(nullptr), PragmaAttributeCurrentTargetDecl(nullptr),
322 StdCoroutineTraitsCache(nullptr), IdResolver(pp),
323 OriginalLexicalContext(nullptr), StdInitializerList(nullptr),
324 StdTypeIdentity(nullptr),
325 FullyCheckedComparisonCategories(
326 static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
327 StdSourceLocationImplDecl(nullptr), CXXTypeInfoDecl(nullptr),
328 GlobalNewDeleteDeclared(false), DisableTypoCorrection(false),
329 TyposCorrected(0), IsBuildingRecoveryCallExpr(false),
330 CurrentInstantiationScope(nullptr), NonInstantiationEntries(0),
331 ArgPackSubstIndex(std::nullopt), SatisfactionCache(Context) {
332 assert(pp.TUKind == TUKind);
333 TUScope = nullptr;
334
335 LoadedExternalKnownNamespaces = false;
336 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
337 ObjC().NSNumberLiteralMethods[I] = nullptr;
338
339 if (getLangOpts().ObjC)
340 ObjC().NSAPIObj.reset(p: new NSAPI(Context));
341
342 if (getLangOpts().CPlusPlus)
343 FieldCollector.reset(p: new CXXFieldCollector());
344
345 // Tell diagnostics how to render things from the AST library.
346 Diags.SetArgToStringFn(Fn: &FormatASTNodeDiagnosticArgument, Cookie: &Context);
347
348 // This evaluation context exists to ensure that there's always at least one
349 // valid evaluation context available. It is never removed from the
350 // evaluation stack.
351 ExprEvalContexts.emplace_back(
352 Args: ExpressionEvaluationContext::PotentiallyEvaluated, Args: 0, Args: CleanupInfo{},
353 Args: nullptr, Args: ExpressionEvaluationContextRecord::EK_Other);
354
355 // Initialization of data sharing attributes stack for OpenMP
356 OpenMP().InitDataSharingAttributesStack();
357
358 std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
359 std::make_unique<sema::SemaPPCallbacks>();
360 SemaPPCallbackHandler = Callbacks.get();
361 PP.addPPCallbacks(C: std::move(Callbacks));
362 SemaPPCallbackHandler->set(*this);
363
364 CurFPFeatures.setFPEvalMethod(PP.getCurrentFPEvalMethod());
365}
366
367// Anchor Sema's type info to this TU.
368void Sema::anchor() {}
369
370void Sema::addImplicitTypedef(StringRef Name, QualType T) {
371 DeclarationName DN = &Context.Idents.get(Name);
372 if (IdResolver.begin(Name: DN) == IdResolver.end())
373 PushOnScopeChains(D: Context.buildImplicitTypedef(T, Name), S: TUScope);
374}
375
376void Sema::Initialize() {
377 // Create BuiltinVaListDecl *before* ExternalSemaSource::InitializeSema(this)
378 // because during initialization ASTReader can emit globals that require
379 // name mangling. And the name mangling uses BuiltinVaListDecl.
380 if (Context.getTargetInfo().hasBuiltinMSVaList())
381 (void)Context.getBuiltinMSVaListDecl();
382 if (Context.getTargetInfo().hasBuiltinZOSVaList())
383 (void)Context.getBuiltinZOSVaListDecl();
384 (void)Context.getBuiltinVaListDecl();
385
386 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(Val: &Consumer))
387 SC->InitializeSema(S&: *this);
388
389 // Tell the external Sema source about this Sema object.
390 if (ExternalSemaSource *ExternalSema
391 = dyn_cast_or_null<ExternalSemaSource>(Val: Context.getExternalSource()))
392 ExternalSema->InitializeSema(S&: *this);
393
394 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
395 // will not be able to merge any duplicate __va_list_tag decls correctly.
396 VAListTagName = PP.getIdentifierInfo(Name: "__va_list_tag");
397
398 if (!TUScope)
399 return;
400
401 // Initialize predefined 128-bit integer types, if needed.
402 if (Context.getTargetInfo().hasInt128Type() ||
403 (Context.getAuxTargetInfo() &&
404 Context.getAuxTargetInfo()->hasInt128Type())) {
405 // If either of the 128-bit integer types are unavailable to name lookup,
406 // define them now.
407 DeclarationName Int128 = &Context.Idents.get(Name: "__int128_t");
408 if (IdResolver.begin(Name: Int128) == IdResolver.end())
409 PushOnScopeChains(D: Context.getInt128Decl(), S: TUScope);
410
411 DeclarationName UInt128 = &Context.Idents.get(Name: "__uint128_t");
412 if (IdResolver.begin(Name: UInt128) == IdResolver.end())
413 PushOnScopeChains(D: Context.getUInt128Decl(), S: TUScope);
414 }
415
416
417 // Initialize predefined Objective-C types:
418 if (getLangOpts().ObjC) {
419 // If 'SEL' does not yet refer to any declarations, make it refer to the
420 // predefined 'SEL'.
421 DeclarationName SEL = &Context.Idents.get(Name: "SEL");
422 if (IdResolver.begin(Name: SEL) == IdResolver.end())
423 PushOnScopeChains(D: Context.getObjCSelDecl(), S: TUScope);
424
425 // If 'id' does not yet refer to any declarations, make it refer to the
426 // predefined 'id'.
427 DeclarationName Id = &Context.Idents.get(Name: "id");
428 if (IdResolver.begin(Name: Id) == IdResolver.end())
429 PushOnScopeChains(D: Context.getObjCIdDecl(), S: TUScope);
430
431 // Create the built-in typedef for 'Class'.
432 DeclarationName Class = &Context.Idents.get(Name: "Class");
433 if (IdResolver.begin(Name: Class) == IdResolver.end())
434 PushOnScopeChains(D: Context.getObjCClassDecl(), S: TUScope);
435
436 // Create the built-in forward declaratino for 'Protocol'.
437 DeclarationName Protocol = &Context.Idents.get(Name: "Protocol");
438 if (IdResolver.begin(Name: Protocol) == IdResolver.end())
439 PushOnScopeChains(D: Context.getObjCProtocolDecl(), S: TUScope);
440 }
441
442 // Create the internal type for the *StringMakeConstantString builtins.
443 DeclarationName ConstantString = &Context.Idents.get(Name: "__NSConstantString");
444 if (IdResolver.begin(Name: ConstantString) == IdResolver.end())
445 PushOnScopeChains(D: Context.getCFConstantStringDecl(), S: TUScope);
446
447 // Initialize Microsoft "predefined C++ types".
448 if (getLangOpts().MSVCCompat) {
449 if (getLangOpts().CPlusPlus &&
450 IdResolver.begin(Name: &Context.Idents.get(Name: "type_info")) == IdResolver.end())
451 PushOnScopeChains(D: Context.getMSTypeInfoTagDecl(), S: TUScope);
452
453 addImplicitTypedef(Name: "size_t", T: Context.getSizeType());
454 }
455
456 // Initialize predefined OpenCL types and supported extensions and (optional)
457 // core features.
458 if (getLangOpts().OpenCL) {
459 getOpenCLOptions().addSupport(
460 FeaturesMap: Context.getTargetInfo().getSupportedOpenCLOpts(), Opts: getLangOpts());
461 addImplicitTypedef(Name: "sampler_t", T: Context.OCLSamplerTy);
462 addImplicitTypedef(Name: "event_t", T: Context.OCLEventTy);
463 auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion();
464 if (OCLCompatibleVersion >= 200) {
465 if (getLangOpts().OpenCLCPlusPlus || getLangOpts().Blocks) {
466 addImplicitTypedef(Name: "clk_event_t", T: Context.OCLClkEventTy);
467 addImplicitTypedef(Name: "queue_t", T: Context.OCLQueueTy);
468 }
469 if (getLangOpts().OpenCLPipes)
470 addImplicitTypedef(Name: "reserve_id_t", T: Context.OCLReserveIDTy);
471 addImplicitTypedef(Name: "atomic_int", T: Context.getAtomicType(T: Context.IntTy));
472 addImplicitTypedef(Name: "atomic_uint",
473 T: Context.getAtomicType(T: Context.UnsignedIntTy));
474 addImplicitTypedef(Name: "atomic_float",
475 T: Context.getAtomicType(T: Context.FloatTy));
476 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
477 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
478 addImplicitTypedef(Name: "atomic_flag", T: Context.getAtomicType(T: Context.IntTy));
479
480
481 // OpenCL v2.0 s6.13.11.6:
482 // - The atomic_long and atomic_ulong types are supported if the
483 // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
484 // extensions are supported.
485 // - The atomic_double type is only supported if double precision
486 // is supported and the cl_khr_int64_base_atomics and
487 // cl_khr_int64_extended_atomics extensions are supported.
488 // - If the device address space is 64-bits, the data types
489 // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
490 // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
491 // cl_khr_int64_extended_atomics extensions are supported.
492
493 auto AddPointerSizeDependentTypes = [&]() {
494 auto AtomicSizeT = Context.getAtomicType(T: Context.getSizeType());
495 auto AtomicIntPtrT = Context.getAtomicType(T: Context.getIntPtrType());
496 auto AtomicUIntPtrT = Context.getAtomicType(T: Context.getUIntPtrType());
497 auto AtomicPtrDiffT =
498 Context.getAtomicType(T: Context.getPointerDiffType());
499 addImplicitTypedef(Name: "atomic_size_t", T: AtomicSizeT);
500 addImplicitTypedef(Name: "atomic_intptr_t", T: AtomicIntPtrT);
501 addImplicitTypedef(Name: "atomic_uintptr_t", T: AtomicUIntPtrT);
502 addImplicitTypedef(Name: "atomic_ptrdiff_t", T: AtomicPtrDiffT);
503 };
504
505 if (Context.getTypeSize(T: Context.getSizeType()) == 32) {
506 AddPointerSizeDependentTypes();
507 }
508
509 if (getOpenCLOptions().isSupported(Ext: "cl_khr_fp16", LO: getLangOpts())) {
510 auto AtomicHalfT = Context.getAtomicType(T: Context.HalfTy);
511 addImplicitTypedef(Name: "atomic_half", T: AtomicHalfT);
512 }
513
514 std::vector<QualType> Atomic64BitTypes;
515 if (getOpenCLOptions().isSupported(Ext: "cl_khr_int64_base_atomics",
516 LO: getLangOpts()) &&
517 getOpenCLOptions().isSupported(Ext: "cl_khr_int64_extended_atomics",
518 LO: getLangOpts())) {
519 if (getOpenCLOptions().isSupported(Ext: "cl_khr_fp64", LO: getLangOpts())) {
520 auto AtomicDoubleT = Context.getAtomicType(T: Context.DoubleTy);
521 addImplicitTypedef(Name: "atomic_double", T: AtomicDoubleT);
522 Atomic64BitTypes.push_back(x: AtomicDoubleT);
523 }
524 auto AtomicLongT = Context.getAtomicType(T: Context.LongTy);
525 auto AtomicULongT = Context.getAtomicType(T: Context.UnsignedLongTy);
526 addImplicitTypedef(Name: "atomic_long", T: AtomicLongT);
527 addImplicitTypedef(Name: "atomic_ulong", T: AtomicULongT);
528
529
530 if (Context.getTypeSize(T: Context.getSizeType()) == 64) {
531 AddPointerSizeDependentTypes();
532 }
533 }
534 }
535
536#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
537 if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) { \
538 addImplicitTypedef(#ExtType, Context.Id##Ty); \
539 }
540#include "clang/Basic/OpenCLExtensionTypes.def"
541 }
542
543 if (Context.getTargetInfo().hasAArch64ACLETypes() ||
544 (Context.getAuxTargetInfo() &&
545 Context.getAuxTargetInfo()->hasAArch64ACLETypes())) {
546#define SVE_TYPE(Name, Id, SingletonId) \
547 addImplicitTypedef(#Name, Context.SingletonId);
548#define NEON_VECTOR_TYPE(Name, BaseType, ElBits, NumEls, VectorKind) \
549 addImplicitTypedef( \
550 #Name, Context.getVectorType(Context.BaseType, NumEls, VectorKind));
551#include "clang/Basic/AArch64ACLETypes.def"
552 }
553
554 if (Context.getTargetInfo().getTriple().isPPC64()) {
555#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
556 addImplicitTypedef(#Name, Context.Id##Ty);
557#include "clang/Basic/PPCTypes.def"
558#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
559 addImplicitTypedef(#Name, Context.Id##Ty);
560#include "clang/Basic/PPCTypes.def"
561 }
562
563 if (Context.getTargetInfo().hasRISCVVTypes()) {
564#define RVV_TYPE(Name, Id, SingletonId) \
565 addImplicitTypedef(Name, Context.SingletonId);
566#include "clang/Basic/RISCVVTypes.def"
567 }
568
569 if (Context.getTargetInfo().getTriple().isWasm() &&
570 Context.getTargetInfo().hasFeature(Feature: "reference-types")) {
571#define WASM_TYPE(Name, Id, SingletonId) \
572 addImplicitTypedef(Name, Context.SingletonId);
573#include "clang/Basic/WebAssemblyReferenceTypes.def"
574 }
575
576 if (Context.getTargetInfo().hasAMDGPUTypes() ||
577 (Context.getAuxTargetInfo() &&
578 (Context.getAuxTargetInfo()->hasAMDGPUTypes()))) {
579#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
580 addImplicitTypedef(Name, Context.SingletonId);
581#include "clang/Basic/AMDGPUTypes.def"
582 }
583
584 if (Context.getTargetInfo().getTriple().isSPIRV() ||
585 (Context.getAuxTargetInfo() &&
586 Context.getAuxTargetInfo()->getTriple().isSPIRV())) {
587#define SPIRV_TYPE(Name, Id, SingletonId) \
588 addImplicitTypedef(Name, Context.SingletonId);
589#include "clang/Basic/SPIRVTypes.def"
590 }
591
592 if (Context.getTargetInfo().hasBuiltinMSVaList()) {
593 DeclarationName MSVaList = &Context.Idents.get(Name: "__builtin_ms_va_list");
594 if (IdResolver.begin(Name: MSVaList) == IdResolver.end())
595 PushOnScopeChains(D: Context.getBuiltinMSVaListDecl(), S: TUScope);
596 }
597
598 if (Context.getTargetInfo().hasBuiltinZOSVaList()) {
599 DeclarationName ZOSVaList = &Context.Idents.get(Name: "__builtin_zos_va_list");
600 if (IdResolver.begin(Name: ZOSVaList) == IdResolver.end())
601 PushOnScopeChains(D: Context.getBuiltinZOSVaListDecl(), S: TUScope);
602 }
603
604 DeclarationName BuiltinVaList = &Context.Idents.get(Name: "__builtin_va_list");
605 if (IdResolver.begin(Name: BuiltinVaList) == IdResolver.end())
606 PushOnScopeChains(D: Context.getBuiltinVaListDecl(), S: TUScope);
607}
608
609Sema::~Sema() {
610 assert(InstantiatingSpecializations.empty() &&
611 "failed to clean up an InstantiatingTemplate?");
612
613 if (VisContext) FreeVisContext();
614
615 // Kill all the active scopes.
616 for (sema::FunctionScopeInfo *FSI : FunctionScopes)
617 delete FSI;
618
619 // Tell the SemaConsumer to forget about us; we're going out of scope.
620 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(Val: &Consumer))
621 SC->ForgetSema();
622
623 // Detach from the external Sema source.
624 if (ExternalSemaSource *ExternalSema
625 = dyn_cast_or_null<ExternalSemaSource>(Val: Context.getExternalSource()))
626 ExternalSema->ForgetSema();
627
628 // Delete cached satisfactions.
629 std::vector<ConstraintSatisfaction *> Satisfactions;
630 Satisfactions.reserve(n: SatisfactionCache.size());
631 for (auto &Node : SatisfactionCache)
632 Satisfactions.push_back(x: &Node);
633 for (auto *Node : Satisfactions)
634 delete Node;
635
636 threadSafety::threadSafetyCleanup(Cache: ThreadSafetyDeclCache);
637
638 // Destroys data sharing attributes stack for OpenMP
639 OpenMP().DestroyDataSharingAttributesStack();
640
641 // Detach from the PP callback handler which outlives Sema since it's owned
642 // by the preprocessor.
643 SemaPPCallbackHandler->reset();
644}
645
646void Sema::runWithSufficientStackSpace(SourceLocation Loc,
647 llvm::function_ref<void()> Fn) {
648 StackHandler.runWithSufficientStackSpace(Loc, Fn);
649}
650
651bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
652 UnavailableAttr::ImplicitReason reason) {
653 // If we're not in a function, it's an error.
654 FunctionDecl *fn = dyn_cast<FunctionDecl>(Val: CurContext);
655 if (!fn) return false;
656
657 // If we're in template instantiation, it's an error.
658 if (inTemplateInstantiation())
659 return false;
660
661 // If that function's not in a system header, it's an error.
662 if (!Context.getSourceManager().isInSystemHeader(Loc: loc))
663 return false;
664
665 // If the function is already unavailable, it's not an error.
666 if (fn->hasAttr<UnavailableAttr>()) return true;
667
668 fn->addAttr(A: UnavailableAttr::CreateImplicit(Ctx&: Context, Message: "", ImplicitReason: reason, Range: loc));
669 return true;
670}
671
672ASTMutationListener *Sema::getASTMutationListener() const {
673 return getASTConsumer().GetASTMutationListener();
674}
675
676void Sema::addExternalSource(IntrusiveRefCntPtr<ExternalSemaSource> E) {
677 assert(E && "Cannot use with NULL ptr");
678
679 if (!ExternalSource) {
680 ExternalSource = std::move(E);
681 return;
682 }
683
684 if (auto *Ex = dyn_cast<MultiplexExternalSemaSource>(Val: ExternalSource.get()))
685 Ex->AddSource(Source: std::move(E));
686 else
687 ExternalSource = llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>(
688 A&: ExternalSource, A: std::move(E));
689}
690
691void Sema::PrintStats() const {
692 llvm::errs() << "\n*** Semantic Analysis Stats:\n";
693 if (SFINAETrap *Trap = getSFINAEContext())
694 llvm::errs() << int(Trap->hasErrorOccurred())
695 << " SFINAE diagnostics trapped.\n";
696
697 BumpAlloc.PrintStats();
698 AnalysisWarnings.PrintStats();
699}
700
701void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
702 QualType SrcType,
703 SourceLocation Loc) {
704 NullabilityKindOrNone ExprNullability = SrcType->getNullability();
705 if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable &&
706 *ExprNullability != NullabilityKind::NullableResult))
707 return;
708
709 NullabilityKindOrNone TypeNullability = DstType->getNullability();
710 if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
711 return;
712
713 Diag(Loc, DiagID: diag::warn_nullability_lost) << SrcType << DstType;
714}
715
716// Generate diagnostics when adding or removing effects in a type conversion.
717void Sema::diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType,
718 SourceLocation Loc) {
719 const auto SrcFX = FunctionEffectsRef::get(QT: SrcType);
720 const auto DstFX = FunctionEffectsRef::get(QT: DstType);
721 if (SrcFX != DstFX) {
722 for (const auto &Diff : FunctionEffectDiffVector(SrcFX, DstFX)) {
723 if (Diff.shouldDiagnoseConversion(SrcType, SrcFX, DstType, DstFX))
724 Diag(Loc, DiagID: diag::warn_invalid_add_func_effects) << Diff.effectName();
725 }
726 }
727}
728
729void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E) {
730 // nullptr only exists from C++11 on, so don't warn on its absence earlier.
731 if (!getLangOpts().CPlusPlus11)
732 return;
733
734 if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
735 return;
736
737 const Expr *EStripped = E->IgnoreParenImpCasts();
738 if (EStripped->getType()->isNullPtrType())
739 return;
740 if (isa<GNUNullExpr>(Val: EStripped))
741 return;
742
743 if (Diags.isIgnored(DiagID: diag::warn_zero_as_null_pointer_constant,
744 Loc: E->getBeginLoc()))
745 return;
746
747 // Don't diagnose the conversion from a 0 literal to a null pointer argument
748 // in a synthesized call to operator<=>.
749 if (!CodeSynthesisContexts.empty() &&
750 CodeSynthesisContexts.back().Kind ==
751 CodeSynthesisContext::RewritingOperatorAsSpaceship)
752 return;
753
754 // Ignore null pointers in defaulted comparison operators.
755 FunctionDecl *FD = getCurFunctionDecl();
756 if (FD && FD->isDefaulted()) {
757 return;
758 }
759
760 // If it is a macro from system header, and if the macro name is not "NULL",
761 // do not warn.
762 // Note that uses of "NULL" will be ignored above on systems that define it
763 // as __null.
764 SourceLocation MaybeMacroLoc = E->getBeginLoc();
765 if (Diags.getSuppressSystemWarnings() &&
766 SourceMgr.isInSystemMacro(loc: MaybeMacroLoc) &&
767 !findMacroSpelling(loc&: MaybeMacroLoc, name: "NULL"))
768 return;
769
770 Diag(Loc: E->getBeginLoc(), DiagID: diag::warn_zero_as_null_pointer_constant)
771 << FixItHint::CreateReplacement(RemoveRange: E->getSourceRange(), Code: "nullptr");
772}
773
774/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
775/// If there is already an implicit cast, merge into the existing one.
776/// The result is of the given category.
777ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
778 CastKind Kind, ExprValueKind VK,
779 const CXXCastPath *BasePath,
780 CheckedConversionKind CCK) {
781#ifndef NDEBUG
782 if (VK == VK_PRValue && !E->isPRValue()) {
783 switch (Kind) {
784 default:
785 llvm_unreachable(
786 ("can't implicitly cast glvalue to prvalue with this cast "
787 "kind: " +
788 std::string(CastExpr::getCastKindName(Kind)))
789 .c_str());
790 case CK_Dependent:
791 case CK_LValueToRValue:
792 case CK_ArrayToPointerDecay:
793 case CK_FunctionToPointerDecay:
794 case CK_ToVoid:
795 case CK_NonAtomicToAtomic:
796 case CK_HLSLArrayRValue:
797 case CK_HLSLAggregateSplatCast:
798 break;
799 }
800 }
801 assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) &&
802 "can't cast prvalue to glvalue");
803#endif
804
805 diagnoseNullableToNonnullConversion(DstType: Ty, SrcType: E->getType(), Loc: E->getBeginLoc());
806 diagnoseZeroToNullptrConversion(Kind, E);
807 if (Context.hasAnyFunctionEffects() && !isCast(CCK) &&
808 Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
809 diagnoseFunctionEffectConversion(DstType: Ty, SrcType: E->getType(), Loc: E->getBeginLoc());
810
811 QualType ExprTy = Context.getCanonicalType(T: E->getType());
812 QualType TypeTy = Context.getCanonicalType(T: Ty);
813
814 // This cast is used in place of a regular LValue to RValue cast for
815 // HLSL Array Parameter Types. It needs to be emitted even if
816 // ExprTy == TypeTy, except if E is an HLSLOutArgExpr
817 // Emitting a cast in that case will prevent HLSLOutArgExpr from
818 // being handled properly in EmitCallArg
819 if (Kind == CK_HLSLArrayRValue && !isa<HLSLOutArgExpr>(Val: E))
820 return ImplicitCastExpr::Create(Context, T: Ty, Kind, Operand: E, BasePath, Cat: VK,
821 FPO: CurFPFeatureOverrides());
822
823 if (ExprTy == TypeTy)
824 return E;
825
826 if (Kind == CK_ArrayToPointerDecay) {
827 // C++1z [conv.array]: The temporary materialization conversion is applied.
828 // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
829 if (getLangOpts().CPlusPlus && E->isPRValue()) {
830 // The temporary is an lvalue in C++98 and an xvalue otherwise.
831 ExprResult Materialized = CreateMaterializeTemporaryExpr(
832 T: E->getType(), Temporary: E, BoundToLvalueReference: !getLangOpts().CPlusPlus11);
833 if (Materialized.isInvalid())
834 return ExprError();
835 E = Materialized.get();
836 }
837 // C17 6.7.1p6 footnote 124: The implementation can treat any register
838 // declaration simply as an auto declaration. However, whether or not
839 // addressable storage is actually used, the address of any part of an
840 // object declared with storage-class specifier register cannot be
841 // computed, either explicitly(by use of the unary & operator as discussed
842 // in 6.5.3.2) or implicitly(by converting an array name to a pointer as
843 // discussed in 6.3.2.1).Thus, the only operator that can be applied to an
844 // array declared with storage-class specifier register is sizeof.
845 if (VK == VK_PRValue && !getLangOpts().CPlusPlus && !E->isPRValue()) {
846 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
847 if (const auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl())) {
848 if (VD->getStorageClass() == SC_Register) {
849 Diag(Loc: E->getExprLoc(), DiagID: diag::err_typecheck_address_of)
850 << /*register variable*/ 3 << E->getSourceRange();
851 return ExprError();
852 }
853 }
854 }
855 }
856 }
857
858 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Val: E)) {
859 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
860 ImpCast->setType(Ty);
861 ImpCast->setValueKind(VK);
862 return E;
863 }
864 }
865
866 bool IsExplicitCast = isa<CStyleCastExpr>(Val: E) || isa<CXXStaticCastExpr>(Val: E) ||
867 isa<CXXFunctionalCastExpr>(Val: E);
868
869 if ((Kind == CK_IntegralCast || Kind == CK_IntegralToBoolean ||
870 (Kind == CK_NoOp && E->getType()->isIntegerType() &&
871 Ty->isIntegerType())) &&
872 IsExplicitCast) {
873 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
874 if (Ty->isIntegerType() && !Ty->isOverflowBehaviorType()) {
875 Ty = Context.getOverflowBehaviorType(Kind: SourceOBT->getBehaviorKind(), Wrapped: Ty);
876 }
877 }
878 }
879
880 return ImplicitCastExpr::Create(Context, T: Ty, Kind, Operand: E, BasePath, Cat: VK,
881 FPO: CurFPFeatureOverrides());
882}
883
884CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
885 switch (ScalarTy->getScalarTypeKind()) {
886 case Type::STK_Bool: return CK_NoOp;
887 case Type::STK_CPointer: return CK_PointerToBoolean;
888 case Type::STK_BlockPointer: return CK_PointerToBoolean;
889 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
890 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
891 case Type::STK_Integral: return CK_IntegralToBoolean;
892 case Type::STK_Floating: return CK_FloatingToBoolean;
893 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
894 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
895 case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
896 }
897 llvm_unreachable("unknown scalar type kind");
898}
899
900/// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
901static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
902 if (D->getMostRecentDecl()->isUsed())
903 return true;
904
905 if (D->isExternallyVisible())
906 return true;
907
908 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
909 // If this is a function template and none of its specializations is used,
910 // we should warn.
911 if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
912 for (const auto *Spec : Template->specializations())
913 if (ShouldRemoveFromUnused(SemaRef, D: Spec))
914 return true;
915
916 // UnusedFileScopedDecls stores the first declaration.
917 // The declaration may have become definition so check again.
918 const FunctionDecl *DeclToCheck;
919 if (FD->hasBody(Definition&: DeclToCheck))
920 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(D: DeclToCheck);
921
922 // Later redecls may add new information resulting in not having to warn,
923 // so check again.
924 DeclToCheck = FD->getMostRecentDecl();
925 if (DeclToCheck != FD)
926 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(D: DeclToCheck);
927 }
928
929 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
930 // If a variable usable in constant expressions is referenced,
931 // don't warn if it isn't used: if the value of a variable is required
932 // for the computation of a constant expression, it doesn't make sense to
933 // warn even if the variable isn't odr-used. (isReferenced doesn't
934 // precisely reflect that, but it's a decent approximation.)
935 if (VD->isReferenced() &&
936 VD->mightBeUsableInConstantExpressions(C: SemaRef->Context))
937 return true;
938
939 if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
940 // If this is a variable template and none of its specializations is used,
941 // we should warn.
942 for (const auto *Spec : Template->specializations())
943 if (ShouldRemoveFromUnused(SemaRef, D: Spec))
944 return true;
945
946 // UnusedFileScopedDecls stores the first declaration.
947 // The declaration may have become definition so check again.
948 const VarDecl *DeclToCheck = VD->getDefinition();
949 if (DeclToCheck)
950 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(D: DeclToCheck);
951
952 // Later redecls may add new information resulting in not having to warn,
953 // so check again.
954 DeclToCheck = VD->getMostRecentDecl();
955 if (DeclToCheck != VD)
956 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(D: DeclToCheck);
957 }
958
959 return false;
960}
961
962static bool isFunctionOrVarDeclExternC(const NamedDecl *ND) {
963 if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND))
964 return FD->isExternC();
965 return cast<VarDecl>(Val: ND)->isExternC();
966}
967
968/// Determine whether ND is an external-linkage function or variable whose
969/// type has no linkage.
970bool Sema::isExternalWithNoLinkageType(const ValueDecl *VD) const {
971 // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
972 // because we also want to catch the case where its type has VisibleNoLinkage,
973 // which does not affect the linkage of VD.
974 return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
975 !isExternalFormalLinkage(L: VD->getType()->getLinkage()) &&
976 !isFunctionOrVarDeclExternC(ND: VD);
977}
978
979bool Sema::isMainFileLoc(SourceLocation Loc) const {
980 if (TUKind != TU_Complete || getLangOpts().IsHeaderFile)
981 return false;
982 return SourceMgr.isInMainFile(Loc);
983}
984
985/// Obtains a sorted list of functions and variables that are undefined but
986/// ODR-used.
987void Sema::getUndefinedButUsed(
988 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
989 for (const auto &UndefinedUse : UndefinedButUsed) {
990 NamedDecl *ND = UndefinedUse.first;
991
992 // Ignore attributes that have become invalid.
993 if (ND->isInvalidDecl()) continue;
994
995 // __attribute__((weakref)) is basically a definition.
996 if (ND->hasAttr<WeakRefAttr>()) continue;
997
998 if (isa<CXXDeductionGuideDecl>(Val: ND))
999 continue;
1000
1001 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
1002 // An exported function will always be emitted when defined, so even if
1003 // the function is inline, it doesn't have to be emitted in this TU. An
1004 // imported function implies that it has been exported somewhere else.
1005 continue;
1006 }
1007
1008 if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) {
1009 if (FD->isDefined())
1010 continue;
1011 if (FD->isExternallyVisible() &&
1012 !isExternalWithNoLinkageType(VD: FD) &&
1013 !FD->getMostRecentDecl()->isInlined() &&
1014 !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
1015 continue;
1016 if (FD->getBuiltinID())
1017 continue;
1018 } else {
1019 const auto *VD = cast<VarDecl>(Val: ND);
1020 if (VD->hasDefinition() != VarDecl::DeclarationOnly)
1021 continue;
1022 if (VD->isExternallyVisible() &&
1023 !isExternalWithNoLinkageType(VD) &&
1024 !VD->getMostRecentDecl()->isInline() &&
1025 !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
1026 continue;
1027
1028 // Skip VarDecls that lack formal definitions but which we know are in
1029 // fact defined somewhere.
1030 if (VD->isKnownToBeDefined())
1031 continue;
1032 }
1033
1034 Undefined.push_back(Elt: std::make_pair(x&: ND, y: UndefinedUse.second));
1035 }
1036}
1037
1038/// checkUndefinedButUsed - Check for undefined objects with internal linkage
1039/// or that are inline.
1040static void checkUndefinedButUsed(Sema &S) {
1041 if (S.UndefinedButUsed.empty()) return;
1042
1043 // Collect all the still-undefined entities with internal linkage.
1044 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
1045 S.getUndefinedButUsed(Undefined);
1046 S.UndefinedButUsed.clear();
1047 if (Undefined.empty()) return;
1048
1049 for (const auto &Undef : Undefined) {
1050 ValueDecl *VD = cast<ValueDecl>(Val: Undef.first);
1051 SourceLocation UseLoc = Undef.second;
1052
1053 if (S.isExternalWithNoLinkageType(VD)) {
1054 // C++ [basic.link]p8:
1055 // A type without linkage shall not be used as the type of a variable
1056 // or function with external linkage unless
1057 // -- the entity has C language linkage
1058 // -- the entity is not odr-used or is defined in the same TU
1059 //
1060 // As an extension, accept this in cases where the type is externally
1061 // visible, since the function or variable actually can be defined in
1062 // another translation unit in that case.
1063 S.Diag(Loc: VD->getLocation(), DiagID: isExternallyVisible(L: VD->getType()->getLinkage())
1064 ? diag::ext_undefined_internal_type
1065 : diag::err_undefined_internal_type)
1066 << isa<VarDecl>(Val: VD) << VD;
1067 } else if (!VD->isExternallyVisible()) {
1068 // FIXME: We can promote this to an error. The function or variable can't
1069 // be defined anywhere else, so the program must necessarily violate the
1070 // one definition rule.
1071 bool IsImplicitBase = false;
1072 if (const auto *BaseD = dyn_cast<FunctionDecl>(Val: VD)) {
1073 auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();
1074 if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
1075 TP: llvm::omp::TraitProperty::
1076 implementation_extension_disable_implicit_base)) {
1077 const auto *Func = cast<FunctionDecl>(
1078 Val: cast<DeclRefExpr>(Val: DVAttr->getVariantFuncRef())->getDecl());
1079 IsImplicitBase = BaseD->isImplicit() &&
1080 Func->getIdentifier()->isMangledOpenMPVariantName();
1081 }
1082 }
1083 if (!S.getLangOpts().OpenMP || !IsImplicitBase)
1084 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_undefined_internal)
1085 << isa<VarDecl>(Val: VD) << VD;
1086 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: VD)) {
1087 (void)FD;
1088 assert(FD->getMostRecentDecl()->isInlined() &&
1089 "used object requires definition but isn't inline or internal?");
1090 // FIXME: This is ill-formed; we should reject.
1091 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_undefined_inline) << VD;
1092 } else {
1093 assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
1094 "used var requires definition but isn't inline or internal?");
1095 S.Diag(Loc: VD->getLocation(), DiagID: diag::err_undefined_inline_var) << VD;
1096 }
1097 if (UseLoc.isValid())
1098 S.Diag(Loc: UseLoc, DiagID: diag::note_used_here);
1099 }
1100}
1101
1102void Sema::LoadExternalWeakUndeclaredIdentifiers() {
1103 if (!ExternalSource)
1104 return;
1105
1106 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
1107 ExternalSource->ReadWeakUndeclaredIdentifiers(WI&: WeakIDs);
1108 for (auto &WeakID : WeakIDs)
1109 (void)WeakUndeclaredIdentifiers[WeakID.first].insert(X: WeakID.second);
1110}
1111
1112void Sema::LoadExternalExtnameUndeclaredIdentifiers() {
1113 if (!ExternalSource)
1114 return;
1115
1116 SmallVector<std::pair<IdentifierInfo *, AsmLabelAttr *>, 4> ExtnameIDs;
1117 ExternalSource->ReadExtnameUndeclaredIdentifiers(EI&: ExtnameIDs);
1118 for (auto &ExtnameID : ExtnameIDs)
1119 ExtnameUndeclaredIdentifiers[ExtnameID.first] = ExtnameID.second;
1120}
1121
1122typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
1123
1124/// Returns true, if all methods and nested classes of the given
1125/// CXXRecordDecl are defined in this translation unit.
1126///
1127/// Should only be called from ActOnEndOfTranslationUnit so that all
1128/// definitions are actually read.
1129static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
1130 RecordCompleteMap &MNCComplete) {
1131 RecordCompleteMap::iterator Cache = MNCComplete.find(Val: RD);
1132 if (Cache != MNCComplete.end())
1133 return Cache->second;
1134 if (!RD->isCompleteDefinition())
1135 return false;
1136 bool Complete = true;
1137 for (DeclContext::decl_iterator I = RD->decls_begin(),
1138 E = RD->decls_end();
1139 I != E && Complete; ++I) {
1140 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Val: *I))
1141 Complete = M->isDefined() || M->isDefaulted() ||
1142 (M->isPureVirtual() && !isa<CXXDestructorDecl>(Val: M));
1143 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(Val: *I))
1144 // If the template function is marked as late template parsed at this
1145 // point, it has not been instantiated and therefore we have not
1146 // performed semantic analysis on it yet, so we cannot know if the type
1147 // can be considered complete.
1148 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
1149 F->getTemplatedDecl()->isDefined();
1150 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(Val: *I)) {
1151 if (R->isInjectedClassName())
1152 continue;
1153 if (R->hasDefinition())
1154 Complete = MethodsAndNestedClassesComplete(RD: R->getDefinition(),
1155 MNCComplete);
1156 else
1157 Complete = false;
1158 }
1159 }
1160 MNCComplete[RD] = Complete;
1161 return Complete;
1162}
1163
1164/// Returns true, if the given CXXRecordDecl is fully defined in this
1165/// translation unit, i.e. all methods are defined or pure virtual and all
1166/// friends, friend functions and nested classes are fully defined in this
1167/// translation unit.
1168///
1169/// Should only be called from ActOnEndOfTranslationUnit so that all
1170/// definitions are actually read.
1171static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
1172 RecordCompleteMap &RecordsComplete,
1173 RecordCompleteMap &MNCComplete) {
1174 RecordCompleteMap::iterator Cache = RecordsComplete.find(Val: RD);
1175 if (Cache != RecordsComplete.end())
1176 return Cache->second;
1177 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
1178 for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
1179 E = RD->friend_end();
1180 I != E && Complete; ++I) {
1181 FriendDecl *Friend = *I;
1182 // Check if friend classes and methods are complete.
1183 if (TypeSourceInfo *TSI = Friend->getFriendType()) {
1184 // Friend classes are available as the TypeSourceInfo of the FriendDecl.
1185 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
1186 Complete = MethodsAndNestedClassesComplete(RD: FriendD, MNCComplete);
1187 else
1188 Complete = false;
1189 } else {
1190 // Friend functions are available through the NamedDecl of FriendDecl.
1191 if (const FunctionDecl *FD =
1192 dyn_cast<FunctionDecl>(Val: Friend->getFriendDecl()))
1193 Complete = FD->isDefined();
1194 else
1195 // This is a template friend, give up.
1196 Complete = false;
1197 }
1198 }
1199 RecordsComplete[RD] = Complete;
1200 return Complete;
1201}
1202
1203void Sema::getSortedUnusedLocalTypedefNameCandidates(
1204 SmallVectorImpl<const TypedefNameDecl *> &Sorted) const {
1205 // The candidates are collected while iterating a Scope's SmallPtrSet, so sort
1206 // by source location for a deterministic order.
1207 Sorted.assign(in_start: UnusedLocalTypedefNameCandidates.begin(),
1208 in_end: UnusedLocalTypedefNameCandidates.end());
1209 llvm::sort(C&: Sorted,
1210 Comp: [](const TypedefNameDecl *LHS, const TypedefNameDecl *RHS) {
1211 return LHS->getLocation().getRawEncoding() <
1212 RHS->getLocation().getRawEncoding();
1213 });
1214}
1215
1216void Sema::emitAndClearUnusedLocalTypedefWarnings() {
1217 if (ExternalSource)
1218 ExternalSource->ReadUnusedLocalTypedefNameCandidates(
1219 Decls&: UnusedLocalTypedefNameCandidates);
1220 SmallVector<const TypedefNameDecl *, 4> Sorted;
1221 getSortedUnusedLocalTypedefNameCandidates(Sorted);
1222 for (const TypedefNameDecl *TD : Sorted) {
1223 if (TD->isReferenced())
1224 continue;
1225 Diag(Loc: TD->getLocation(), DiagID: diag::warn_unused_local_typedef)
1226 << isa<TypeAliasDecl>(Val: TD) << TD->getDeclName();
1227 }
1228 UnusedLocalTypedefNameCandidates.clear();
1229}
1230
1231void Sema::ActOnStartOfTranslationUnit() {
1232 if (getLangOpts().CPlusPlusModules &&
1233 getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit)
1234 HandleStartOfHeaderUnit();
1235}
1236
1237void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {
1238 if (Kind == TUFragmentKind::Global) {
1239 // Perform Pending Instantiations at the end of global module fragment so
1240 // that the module ownership of TU-level decls won't get messed.
1241 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1242 PerformPendingInstantiations();
1243 return;
1244 }
1245
1246 // Transfer late parsed template instantiations over to the pending template
1247 // instantiation list. During normal compilation, the late template parser
1248 // will be installed and instantiating these templates will succeed.
1249 //
1250 // If we are building a TU prefix for serialization, it is also safe to
1251 // transfer these over, even though they are not parsed. The end of the TU
1252 // should be outside of any eager template instantiation scope, so when this
1253 // AST is deserialized, these templates will not be parsed until the end of
1254 // the combined TU.
1255 PendingInstantiations.insert(position: PendingInstantiations.end(),
1256 first: LateParsedInstantiations.begin(),
1257 last: LateParsedInstantiations.end());
1258 LateParsedInstantiations.clear();
1259
1260 // If DefinedUsedVTables ends up marking any virtual member functions it
1261 // might lead to more pending template instantiations, which we then need
1262 // to instantiate.
1263 DefineUsedVTables();
1264
1265 // C++: Perform implicit template instantiations.
1266 //
1267 // FIXME: When we perform these implicit instantiations, we do not
1268 // carefully keep track of the point of instantiation (C++ [temp.point]).
1269 // This means that name lookup that occurs within the template
1270 // instantiation will always happen at the end of the translation unit,
1271 // so it will find some names that are not required to be found. This is
1272 // valid, but we could do better by diagnosing if an instantiation uses a
1273 // name that was not visible at its first point of instantiation.
1274 if (ExternalSource) {
1275 // Load pending instantiations from the external source.
1276 SmallVector<PendingImplicitInstantiation, 4> Pending;
1277 ExternalSource->ReadPendingInstantiations(Pending);
1278 for (auto PII : Pending)
1279 if (auto Func = dyn_cast<FunctionDecl>(Val: PII.first))
1280 Func->setInstantiationIsPending(true);
1281 PendingInstantiations.insert(position: PendingInstantiations.begin(),
1282 first: Pending.begin(), last: Pending.end());
1283 }
1284
1285 {
1286 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1287 PerformPendingInstantiations();
1288 }
1289
1290 emitDeferredDiags();
1291
1292 assert(LateParsedInstantiations.empty() &&
1293 "end of TU template instantiation should not create more "
1294 "late-parsed templates");
1295}
1296
1297void Sema::ActOnEndOfTranslationUnit() {
1298 assert(DelayedDiagnostics.getCurrentPool() == nullptr
1299 && "reached end of translation unit with a pool attached?");
1300
1301 // If code completion is enabled, don't perform any end-of-translation-unit
1302 // work.
1303 if (PP.isCodeCompletionEnabled())
1304 return;
1305
1306 // Complete translation units and modules define vtables and perform implicit
1307 // instantiations. PCH files do not.
1308 if (TUKind != TU_Prefix) {
1309 ObjC().DiagnoseUseOfUnimplementedSelectors();
1310
1311 ActOnEndOfTranslationUnitFragment(
1312 Kind: !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1313 Module::PrivateModuleFragment
1314 ? TUFragmentKind::Private
1315 : TUFragmentKind::Normal);
1316
1317 CheckDelayedMemberExceptionSpecs();
1318 } else {
1319 // If we are building a TU prefix for serialization, it is safe to transfer
1320 // these over, even though they are not parsed. The end of the TU should be
1321 // outside of any eager template instantiation scope, so when this AST is
1322 // deserialized, these templates will not be parsed until the end of the
1323 // combined TU.
1324 PendingInstantiations.insert(position: PendingInstantiations.end(),
1325 first: LateParsedInstantiations.begin(),
1326 last: LateParsedInstantiations.end());
1327 LateParsedInstantiations.clear();
1328
1329 if (LangOpts.PCHInstantiateTemplates) {
1330 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1331 PerformPendingInstantiations();
1332 }
1333 }
1334
1335 DiagnoseUnterminatedPragmaAlignPack();
1336 DiagnoseUnterminatedPragmaAttribute();
1337 OpenMP().DiagnoseUnterminatedOpenMPDeclareTarget();
1338 DiagnosePrecisionLossInComplexDivision();
1339 DiagnoseUnusedAPINotesSelectors();
1340
1341 // All delayed member exception specs should be checked or we end up accepting
1342 // incompatible declarations.
1343 assert(DelayedOverridingExceptionSpecChecks.empty());
1344 assert(DelayedEquivalentExceptionSpecChecks.empty());
1345
1346 // All dllexport classes should have been processed already.
1347 assert(DelayedDllExportClasses.empty());
1348 assert(DelayedDllExportMemberFunctions.empty());
1349
1350 // Remove file scoped decls that turned out to be used.
1351 UnusedFileScopedDecls.erase(
1352 From: std::remove_if(first: UnusedFileScopedDecls.begin(source: nullptr, LocalOnly: true),
1353 last: UnusedFileScopedDecls.end(),
1354 pred: [this](const DeclaratorDecl *DD) {
1355 return ShouldRemoveFromUnused(SemaRef: this, D: DD);
1356 }),
1357 To: UnusedFileScopedDecls.end());
1358
1359 if (TUKind == TU_Prefix) {
1360 // Translation unit prefixes don't need any of the checking below.
1361 if (!PP.isIncrementalProcessingEnabled())
1362 TUScope = nullptr;
1363 return;
1364 }
1365
1366 // Check for #pragma weak identifiers that were never declared
1367 LoadExternalWeakUndeclaredIdentifiers();
1368 for (const auto &WeakIDs : WeakUndeclaredIdentifiers) {
1369 if (WeakIDs.second.empty())
1370 continue;
1371
1372 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: WeakIDs.first, Loc: SourceLocation(),
1373 NameKind: LookupOrdinaryName);
1374 if (PrevDecl != nullptr &&
1375 !(isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl)))
1376 for (const auto &WI : WeakIDs.second)
1377 Diag(Loc: WI.getLocation(), DiagID: diag::warn_attribute_wrong_decl_type)
1378 << "'weak'" << /*isRegularKeyword=*/0 << ExpectedVariableOrFunction;
1379 else
1380 for (const auto &WI : WeakIDs.second)
1381 Diag(Loc: WI.getLocation(), DiagID: diag::warn_weak_identifier_undeclared)
1382 << WeakIDs.first;
1383 }
1384
1385 if (LangOpts.CPlusPlus11 &&
1386 !Diags.isIgnored(DiagID: diag::warn_delegating_ctor_cycle, Loc: SourceLocation()))
1387 CheckDelegatingCtorCycles();
1388
1389 if (!Diags.hasErrorOccurred()) {
1390 if (ExternalSource)
1391 ExternalSource->ReadUndefinedButUsed(Undefined&: UndefinedButUsed);
1392 checkUndefinedButUsed(S&: *this);
1393 }
1394
1395 // A global-module-fragment is only permitted within a module unit.
1396 if (!ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1397 Module::ExplicitGlobalModuleFragment) {
1398 Diag(Loc: ModuleScopes.back().BeginLoc,
1399 DiagID: diag::err_module_declaration_missing_after_global_module_introducer);
1400 } else if (getLangOpts().getCompilingModule() ==
1401 LangOptions::CMK_ModuleInterface &&
1402 // We can't use ModuleScopes here since ModuleScopes is always
1403 // empty if we're compiling the BMI.
1404 !getASTContext().getCurrentNamedModule()) {
1405 // If we are building a module interface unit, we should have seen the
1406 // module declaration.
1407 //
1408 // FIXME: Make a better guess as to where to put the module declaration.
1409 Diag(Loc: getSourceManager().getLocForStartOfFile(
1410 FID: getSourceManager().getMainFileID()),
1411 DiagID: diag::err_module_declaration_missing);
1412 }
1413
1414 // Now we can decide whether the modules we're building need an initializer.
1415 if (Module *CurrentModule = getCurrentModule();
1416 CurrentModule && CurrentModule->isInterfaceOrPartition()) {
1417 auto DoesModNeedInit = [this](Module *M) {
1418 for (Decl *D : getASTContext().getModuleInitializers(M)) {
1419 auto *VD = dyn_cast<VarDecl>(Val: D);
1420 // TLS initialization is not handled by the TU's global initializer.
1421 if (!VD || VD->getTLSKind() != VarDecl::TLS_None)
1422 continue;
1423
1424 if (const VarDecl *InitDecl = VD->getInitializingDeclaration();
1425 (InitDecl && !InitDecl->hasConstantInitialization()) ||
1426 VD->needsDestruction(Ctx: getASTContext()) ==
1427 QualType::DK_cxx_destructor)
1428 return true;
1429 }
1430 for (auto [Exported, _] : M->Exports)
1431 if (Exported->isNamedModuleInterfaceHasInit())
1432 return true;
1433 for (Module *I : M->Imports)
1434 if (I->isNamedModuleInterfaceHasInit())
1435 return true;
1436
1437 return false;
1438 };
1439
1440 CurrentModule->NamedModuleHasInit =
1441 DoesModNeedInit(CurrentModule) ||
1442 llvm::any_of(Range: CurrentModule->submodules(), P: DoesModNeedInit);
1443 }
1444
1445 if (TUKind == TU_ClangModule) {
1446 // If we are building a module, resolve all of the exported declarations
1447 // now.
1448 if (Module *CurrentModule = PP.getCurrentModule()) {
1449 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
1450
1451 SmallVector<Module *, 2> Stack;
1452 Stack.push_back(Elt: CurrentModule);
1453 while (!Stack.empty()) {
1454 Module *Mod = Stack.pop_back_val();
1455
1456 // Resolve the exported declarations and conflicts.
1457 // FIXME: Actually complain, once we figure out how to teach the
1458 // diagnostic client to deal with complaints in the module map at this
1459 // point.
1460 ModMap.resolveExports(Mod, /*Complain=*/false);
1461 ModMap.resolveUses(Mod, /*Complain=*/false);
1462 ModMap.resolveConflicts(Mod, /*Complain=*/false);
1463
1464 // Queue the submodules, so their exports will also be resolved.
1465 auto SubmodulesRange = Mod->submodules();
1466 Stack.append(in_start: SubmodulesRange.begin(), in_end: SubmodulesRange.end());
1467 }
1468 }
1469
1470 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1471 // modules when they are built, not every time they are used.
1472 emitAndClearUnusedLocalTypedefWarnings();
1473 }
1474
1475 // C++ standard modules. Diagnose cases where a function is declared inline
1476 // in the module purview but has no definition before the end of the TU or
1477 // the start of a Private Module Fragment (if one is present).
1478 if (!PendingInlineFuncDecls.empty()) {
1479 for (auto *FD : PendingInlineFuncDecls) {
1480 bool DefInPMF = false;
1481 if (auto *FDD = FD->getDefinition()) {
1482 DefInPMF = FDD->getOwningModule()->isPrivateModule();
1483 if (!DefInPMF)
1484 continue;
1485 }
1486 Diag(Loc: FD->getLocation(), DiagID: diag::err_export_inline_not_defined) << DefInPMF;
1487 // If we have a PMF it should be at the end of the ModuleScopes.
1488 if (DefInPMF &&
1489 ModuleScopes.back().Module->Kind == Module::PrivateModuleFragment) {
1490 Diag(Loc: ModuleScopes.back().BeginLoc, DiagID: diag::note_private_module_fragment);
1491 }
1492 }
1493 PendingInlineFuncDecls.clear();
1494 }
1495
1496 // C99 6.9.2p2:
1497 // A declaration of an identifier for an object that has file
1498 // scope without an initializer, and without a storage-class
1499 // specifier or with the storage-class specifier static,
1500 // constitutes a tentative definition. If a translation unit
1501 // contains one or more tentative definitions for an identifier,
1502 // and the translation unit contains no external definition for
1503 // that identifier, then the behavior is exactly as if the
1504 // translation unit contains a file scope declaration of that
1505 // identifier, with the composite type as of the end of the
1506 // translation unit, with an initializer equal to 0.
1507 llvm::SmallPtrSet<VarDecl *, 32> Seen;
1508 for (TentativeDefinitionsType::iterator
1509 T = TentativeDefinitions.begin(source: ExternalSource.get()),
1510 TEnd = TentativeDefinitions.end();
1511 T != TEnd; ++T) {
1512 VarDecl *VD = (*T)->getActingDefinition();
1513
1514 // If the tentative definition was completed, getActingDefinition() returns
1515 // null. If we've already seen this variable before, insert()'s second
1516 // return value is false.
1517 if (!VD || VD->isInvalidDecl() || !Seen.insert(Ptr: VD).second)
1518 continue;
1519
1520 if (const IncompleteArrayType *ArrayT
1521 = Context.getAsIncompleteArrayType(T: VD->getType())) {
1522 // Set the length of the array to 1 (C99 6.9.2p5).
1523 Diag(Loc: VD->getLocation(), DiagID: diag::warn_tentative_incomplete_array);
1524 llvm::APInt One(Context.getTypeSize(T: Context.getSizeType()), true);
1525 QualType T = Context.getConstantArrayType(
1526 EltTy: ArrayT->getElementType(), ArySize: One, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
1527 VD->setType(T);
1528 } else if (RequireCompleteType(Loc: VD->getLocation(), T: VD->getType(),
1529 DiagID: diag::err_tentative_def_incomplete_type))
1530 VD->setInvalidDecl();
1531
1532 // No initialization is performed for a tentative definition.
1533 CheckCompleteVariableDeclaration(VD);
1534
1535 // In C, if the definition is const-qualified and has no initializer, it
1536 // is left uninitialized unless it has static or thread storage duration.
1537 QualType Type = VD->getType();
1538 if (!VD->isInvalidDecl() && !getLangOpts().CPlusPlus &&
1539 Type.isConstQualified() && !VD->getAnyInitializer()) {
1540 unsigned DiagID = diag::warn_default_init_const_unsafe;
1541 if (VD->getStorageDuration() == SD_Static ||
1542 VD->getStorageDuration() == SD_Thread)
1543 DiagID = diag::warn_default_init_const;
1544
1545 bool EmitCppCompat = !Diags.isIgnored(
1546 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
1547 Loc: VD->getLocation());
1548
1549 Diag(Loc: VD->getLocation(), DiagID) << Type << EmitCppCompat;
1550 }
1551
1552 // Notify the consumer that we've completed a tentative definition.
1553 if (!VD->isInvalidDecl())
1554 Consumer.CompleteTentativeDefinition(D: VD);
1555 }
1556
1557 // In incremental mode, tentative definitions belong to the current
1558 // partial translation unit (PTU). Once they have been completed and
1559 // emitted to codegen, drop them to prevent re-emission in future PTUs.
1560 if (PP.isIncrementalProcessingEnabled())
1561 TentativeDefinitions.erase(From: TentativeDefinitions.begin(source: ExternalSource.get()),
1562 To: TentativeDefinitions.end());
1563
1564 for (auto *D : ExternalDeclarations) {
1565 if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())
1566 continue;
1567
1568 Consumer.CompleteExternalDeclaration(D);
1569 }
1570
1571 // Visit all pending #pragma export.
1572 for (const PendingPragmaInfo &Exported : PendingExportedNames.values()) {
1573 if (!Exported.Used)
1574 Diag(Loc: Exported.NameLoc, DiagID: diag::warn_failed_to_resolve_pragma) << "export";
1575 }
1576
1577 if (LangOpts.HLSL)
1578 HLSL().ActOnEndOfTranslationUnit(TU: getASTContext().getTranslationUnitDecl());
1579 if (LangOpts.OpenACC)
1580 OpenACC().ActOnEndOfTranslationUnit(
1581 TU: getASTContext().getTranslationUnitDecl());
1582
1583 // If there were errors, disable 'unused' warnings since they will mostly be
1584 // noise. Don't warn for a use from a module: either we should warn on all
1585 // file-scope declarations in modules or not at all, but whether the
1586 // declaration is used is immaterial.
1587 if (!Diags.hasErrorOccurred() && TUKind != TU_ClangModule) {
1588 // Output warning for unused file scoped decls.
1589 for (UnusedFileScopedDeclsType::iterator
1590 I = UnusedFileScopedDecls.begin(source: ExternalSource.get()),
1591 E = UnusedFileScopedDecls.end();
1592 I != E; ++I) {
1593 if (ShouldRemoveFromUnused(SemaRef: this, D: *I))
1594 continue;
1595
1596 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) {
1597 const FunctionDecl *DiagD;
1598 if (!FD->hasBody(Definition&: DiagD))
1599 DiagD = FD;
1600 if (DiagD->isDeleted())
1601 continue; // Deleted functions are supposed to be unused.
1602 SourceRange DiagRange = DiagD->getLocation();
1603 if (const ASTTemplateArgumentListInfo *ASTTAL =
1604 DiagD->getTemplateSpecializationArgsAsWritten())
1605 DiagRange.setEnd(ASTTAL->RAngleLoc);
1606 if (DiagD->isReferenced()) {
1607 if (isa<CXXMethodDecl>(Val: DiagD))
1608 Diag(Loc: DiagD->getLocation(), DiagID: diag::warn_unneeded_member_function)
1609 << DiagD << DiagRange;
1610 else {
1611 if (FD->getStorageClass() == SC_Static &&
1612 !FD->isInlineSpecified() &&
1613 !SourceMgr.isInMainFile(
1614 Loc: SourceMgr.getExpansionLoc(Loc: FD->getLocation())))
1615 Diag(Loc: DiagD->getLocation(),
1616 DiagID: diag::warn_unneeded_static_internal_decl)
1617 << DiagD << DiagRange;
1618 else
1619 Diag(Loc: DiagD->getLocation(), DiagID: diag::warn_unneeded_internal_decl)
1620 << /*function=*/0 << DiagD << DiagRange;
1621 }
1622 } else if (!FD->isTargetMultiVersion() ||
1623 FD->isTargetMultiVersionDefault()) {
1624 if (FD->getDescribedFunctionTemplate())
1625 Diag(Loc: DiagD->getLocation(), DiagID: diag::warn_unused_template)
1626 << /*function=*/0 << DiagD << DiagRange;
1627 else
1628 Diag(Loc: DiagD->getLocation(), DiagID: isa<CXXMethodDecl>(Val: DiagD)
1629 ? diag::warn_unused_member_function
1630 : diag::warn_unused_function)
1631 << DiagD << DiagRange;
1632 }
1633 } else {
1634 const VarDecl *DiagD = cast<VarDecl>(Val: *I)->getDefinition();
1635 if (!DiagD)
1636 DiagD = cast<VarDecl>(Val: *I);
1637 SourceRange DiagRange = DiagD->getLocation();
1638 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: DiagD)) {
1639 if (const ASTTemplateArgumentListInfo *ASTTAL =
1640 VTSD->getTemplateArgsAsWritten())
1641 DiagRange.setEnd(ASTTAL->RAngleLoc);
1642 }
1643 if (DiagD->isReferenced()) {
1644 Diag(Loc: DiagD->getLocation(), DiagID: diag::warn_unneeded_internal_decl)
1645 << /*variable=*/1 << DiagD << DiagRange;
1646 } else if (DiagD->getDescribedVarTemplate()) {
1647 Diag(Loc: DiagD->getLocation(), DiagID: diag::warn_unused_template)
1648 << /*variable=*/1 << DiagD << DiagRange;
1649 } else if (DiagD->getType().isConstQualified()) {
1650 const SourceManager &SM = SourceMgr;
1651 if (SM.getMainFileID() != SM.getFileID(SpellingLoc: DiagD->getLocation()) ||
1652 !PP.getLangOpts().IsHeaderFile)
1653 Diag(Loc: DiagD->getLocation(), DiagID: diag::warn_unused_const_variable)
1654 << DiagD << DiagRange;
1655 } else {
1656 Diag(Loc: DiagD->getLocation(), DiagID: diag::warn_unused_variable)
1657 << DiagD << DiagRange;
1658 }
1659 }
1660 }
1661
1662 emitAndClearUnusedLocalTypedefWarnings();
1663 }
1664
1665 if (!Diags.isIgnored(DiagID: diag::warn_unused_but_set_global, Loc: SourceLocation())) {
1666 // Diagnose unused-but-set static globals in a deterministic order.
1667 // Not tracking shadowing info for static globals; there's nothing to
1668 // shadow.
1669 struct LocAndDiag {
1670 SourceLocation Loc;
1671 PartialDiagnostic PD;
1672 };
1673 SmallVector<LocAndDiag, 16> DeclDiags;
1674 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
1675 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PD: std::move(PD)});
1676 };
1677
1678 // For -Wunused-but-set-variable we only care about variables that were
1679 // referenced by the TU end.
1680 for (const auto &Ref : RefsMinusAssignments) {
1681 const VarDecl *VD = Ref.first;
1682 // Only diagnose internal linkage file vars defined in the main file to
1683 // match -Wunused-variable behavior and avoid false positives from
1684 // headers.
1685 if (VD->isInternalLinkageFileVar() && isMainFileLoc(Loc: VD->getLocation()))
1686 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
1687 }
1688
1689 llvm::sort(C&: DeclDiags,
1690 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
1691 // Sorting purely for determinism; matches behavior in
1692 // Sema::ActOnPopScope.
1693 return LHS.Loc < RHS.Loc;
1694 });
1695 for (const LocAndDiag &D : DeclDiags)
1696 Diag(Loc: D.Loc, PD: D.PD);
1697 }
1698
1699 if (!Diags.isIgnored(DiagID: diag::warn_unused_private_field, Loc: SourceLocation())) {
1700 // FIXME: Load additional unused private field candidates from the external
1701 // source.
1702 RecordCompleteMap RecordsComplete;
1703 RecordCompleteMap MNCComplete;
1704 for (const NamedDecl *D : UnusedPrivateFields) {
1705 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext());
1706 if (RD && !RD->isUnion() && !D->hasAttr<UnusedAttr>() &&
1707 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
1708 Diag(Loc: D->getLocation(), DiagID: diag::warn_unused_private_field)
1709 << D->getDeclName();
1710 }
1711 }
1712 }
1713
1714 if (!Diags.isIgnored(DiagID: diag::warn_mismatched_delete_new, Loc: SourceLocation())) {
1715 if (ExternalSource)
1716 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1717 for (const auto &DeletedFieldInfo : DeleteExprs) {
1718 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1719 AnalyzeDeleteExprMismatch(Field: DeletedFieldInfo.first, DeleteLoc: DeleteExprLoc.first,
1720 DeleteWasArrayForm: DeleteExprLoc.second);
1721 }
1722 }
1723 }
1724
1725 AnalysisWarnings.IssueWarnings(D: Context.getTranslationUnitDecl());
1726
1727 if (Context.hasAnyFunctionEffects())
1728 performFunctionEffectAnalysis(TU: Context.getTranslationUnitDecl());
1729
1730 // Check we've noticed that we're no longer parsing the initializer for every
1731 // variable. If we miss cases, then at best we have a performance issue and
1732 // at worst a rejects-valid bug.
1733 assert(ParsingInitForAutoVars.empty() &&
1734 "Didn't unmark var as having its initializer parsed");
1735
1736 if (!PP.isIncrementalProcessingEnabled())
1737 TUScope = nullptr;
1738
1739 checkExposure(TU: Context.getTranslationUnitDecl());
1740}
1741
1742
1743//===----------------------------------------------------------------------===//
1744// Helper functions.
1745//===----------------------------------------------------------------------===//
1746
1747DeclContext *Sema::getFunctionLevelDeclContext(bool AllowLambda) const {
1748 DeclContext *DC = CurContext;
1749
1750 while (true) {
1751 if (isa<BlockDecl, EnumDecl, CapturedDecl, RequiresExprBodyDecl,
1752 CXXExpansionStmtDecl>(Val: DC)) {
1753 DC = DC->getParent();
1754 } else if (!AllowLambda && isa<CXXMethodDecl>(Val: DC) &&
1755 cast<CXXMethodDecl>(Val: DC)->getOverloadedOperator() == OO_Call &&
1756 cast<CXXRecordDecl>(Val: DC->getParent())->isLambda()) {
1757 DC = DC->getParent()->getParent();
1758 } else
1759 break;
1760 }
1761
1762 return DC;
1763}
1764
1765/// getCurFunctionDecl - If inside of a function body, this returns a pointer
1766/// to the function decl for the function being parsed. If we're currently
1767/// in a 'block', this returns the containing context.
1768FunctionDecl *Sema::getCurFunctionDecl(bool AllowLambda) const {
1769 DeclContext *DC = getFunctionLevelDeclContext(AllowLambda);
1770 return dyn_cast<FunctionDecl>(Val: DC);
1771}
1772
1773ObjCMethodDecl *Sema::getCurMethodDecl() {
1774 DeclContext *DC = getFunctionLevelDeclContext();
1775 while (isa<RecordDecl>(Val: DC))
1776 DC = DC->getParent();
1777 return dyn_cast<ObjCMethodDecl>(Val: DC);
1778}
1779
1780NamedDecl *Sema::getCurFunctionOrMethodDecl() const {
1781 DeclContext *DC = getFunctionLevelDeclContext();
1782 if (isa<ObjCMethodDecl>(Val: DC) || isa<FunctionDecl>(Val: DC))
1783 return cast<NamedDecl>(Val: DC);
1784 return nullptr;
1785}
1786
1787LangAS Sema::getDefaultCXXMethodAddrSpace() const {
1788 if (getLangOpts().OpenCL)
1789 return getASTContext().getDefaultOpenCLPointeeAddrSpace();
1790 return LangAS::Default;
1791}
1792
1793void Sema::EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB) {
1794 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1795 // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1796 // been made more painfully obvious by the refactor that introduced this
1797 // function, but it is possible that the incoming argument can be
1798 // eliminated. If it truly cannot be (for example, there is some reentrancy
1799 // issue I am not seeing yet), then there should at least be a clarifying
1800 // comment somewhere.
1801 Diagnostic DiagInfo(&Diags, DB);
1802 if (SFINAETrap *Trap = getSFINAEContext()) {
1803 sema::TemplateDeductionInfo *Info = Trap->getDeductionInfo();
1804 switch (DiagnosticIDs::getDiagnosticSFINAEResponse(DiagID: DiagInfo.getID())) {
1805 case DiagnosticIDs::SFINAE_Report:
1806 // We'll report the diagnostic below.
1807 break;
1808
1809 case DiagnosticIDs::SFINAE_SubstitutionFailure:
1810 // Count this failure so that we know that template argument deduction
1811 // has failed.
1812 Trap->setErrorOccurred();
1813
1814 // Make a copy of this suppressed diagnostic and store it with the
1815 // template-deduction information.
1816 if (Info && !Info->hasSFINAEDiagnostic())
1817 Info->addSFINAEDiagnostic(
1818 Loc: DiagInfo.getLocation(),
1819 PD: PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1820
1821 Diags.setLastDiagnosticIgnored(true);
1822 return;
1823
1824 case DiagnosticIDs::SFINAE_AccessControl: {
1825 // Per C++ Core Issue 1170, access control is part of SFINAE.
1826 // Additionally, the WithAccessChecking flag can be used to temporarily
1827 // make access control a part of SFINAE for the purposes of checking
1828 // type traits.
1829 if (!Trap->withAccessChecking() && !getLangOpts().CPlusPlus11)
1830 break;
1831
1832 SourceLocation Loc = DiagInfo.getLocation();
1833
1834 // Suppress this diagnostic.
1835 Trap->setErrorOccurred();
1836
1837 // Make a copy of this suppressed diagnostic and store it with the
1838 // template-deduction information.
1839 if (Info && !Info->hasSFINAEDiagnostic())
1840 Info->addSFINAEDiagnostic(
1841 Loc: DiagInfo.getLocation(),
1842 PD: PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1843
1844 Diags.setLastDiagnosticIgnored(true);
1845
1846 // Now produce a C++98 compatibility warning.
1847 Diag(Loc, DiagID: diag::warn_cxx98_compat_sfinae_access_control);
1848
1849 // The last diagnostic which Sema produced was ignored. Suppress any
1850 // notes attached to it.
1851 Diags.setLastDiagnosticIgnored(true);
1852 return;
1853 }
1854
1855 case DiagnosticIDs::SFINAE_Suppress:
1856 if (DiagnosticsEngine::Level Level = getDiagnostics().getDiagnosticLevel(
1857 DiagID: DiagInfo.getID(), Loc: DiagInfo.getLocation());
1858 Level == DiagnosticsEngine::Ignored)
1859 return;
1860 // Make a copy of this suppressed diagnostic and store it with the
1861 // template-deduction information;
1862 if (Info) {
1863 Info->addSuppressedDiagnostic(
1864 Loc: DiagInfo.getLocation(),
1865 PD: PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1866 if (!Diags.getDiagnosticIDs()->isNote(DiagID))
1867 PrintContextStack(DiagFunc: [Info](SourceLocation Loc, PartialDiagnostic PD) {
1868 Info->addSuppressedDiagnostic(Loc, PD: std::move(PD));
1869 });
1870 }
1871
1872 // Suppress this diagnostic.
1873 Diags.setLastDiagnosticIgnored(true);
1874 return;
1875 }
1876 }
1877
1878 // Copy the diagnostic printing policy over the ASTContext printing policy.
1879 // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292
1880 Context.setPrintingPolicy(getPrintingPolicy());
1881
1882 // Emit the diagnostic.
1883 if (!Diags.EmitDiagnostic(DB))
1884 return;
1885
1886 // If this is not a note, and we're in a template instantiation
1887 // that is different from the last template instantiation where
1888 // we emitted an error, print a template instantiation
1889 // backtrace.
1890 if (!Diags.getDiagnosticIDs()->isNote(DiagID))
1891 PrintContextStack();
1892}
1893
1894bool Sema::hasUncompilableErrorOccurred() const {
1895 if (getDiagnostics().hasUncompilableErrorOccurred())
1896 return true;
1897 auto *FD = dyn_cast<FunctionDecl>(Val: CurContext);
1898 if (!FD)
1899 return false;
1900 auto Loc = DeviceDeferredDiags.find(Val: FD);
1901 if (Loc == DeviceDeferredDiags.end())
1902 return false;
1903 for (auto PDAt : Loc->second) {
1904 if (Diags.getDiagnosticIDs()->isDefaultMappingAsError(
1905 DiagID: PDAt.second.getDiagID()))
1906 return true;
1907 }
1908 return false;
1909}
1910
1911// Print notes showing how we can reach FD starting from an a priori
1912// known-callable function. When a function has multiple callers, emit
1913// each call chain separately. The first note in each chain uses
1914// "called by" and subsequent notes use "which is called by".
1915static void emitCallStackNotes(Sema &S, const FunctionDecl *FD) {
1916 auto FnIt = S.CUDA().DeviceKnownEmittedFns.find(Val: FD);
1917 if (FnIt == S.CUDA().DeviceKnownEmittedFns.end())
1918 return;
1919
1920 for (const auto &CallerInfo : FnIt->second) {
1921 if (S.Diags.hasFatalErrorOccurred())
1922 return;
1923 S.Diags.Report(Loc: CallerInfo.Loc, DiagID: diag::note_called_by) << CallerInfo.FD;
1924 // Walk up the rest of the chain using "which is called by".
1925 auto NextIt = S.CUDA().DeviceKnownEmittedFns.find(Val: CallerInfo.FD);
1926 while (NextIt != S.CUDA().DeviceKnownEmittedFns.end()) {
1927 if (S.Diags.hasFatalErrorOccurred())
1928 return;
1929 const auto &Next = NextIt->second.front();
1930 S.Diags.Report(Loc: Next.Loc, DiagID: diag::note_which_is_called_by) << Next.FD;
1931 NextIt = S.CUDA().DeviceKnownEmittedFns.find(Val: Next.FD);
1932 }
1933 }
1934}
1935
1936namespace {
1937
1938/// Helper class that emits deferred diagnostic messages if an entity directly
1939/// or indirectly using the function that causes the deferred diagnostic
1940/// messages is known to be emitted.
1941///
1942/// During parsing of AST, certain diagnostic messages are recorded as deferred
1943/// diagnostics since it is unknown whether the functions containing such
1944/// diagnostics will be emitted. A list of potentially emitted functions and
1945/// variables that may potentially trigger emission of functions are also
1946/// recorded. DeferredDiagnosticsEmitter recursively visits used functions
1947/// by each function to emit deferred diagnostics.
1948///
1949/// During the visit, certain OpenMP directives or initializer of variables
1950/// with certain OpenMP attributes will cause subsequent visiting of any
1951/// functions enter a state which is called OpenMP device context in this
1952/// implementation. The state is exited when the directive or initializer is
1953/// exited. This state can change the emission states of subsequent uses
1954/// of functions.
1955///
1956/// Conceptually the functions or variables to be visited form a use graph
1957/// where the parent node uses the child node. At any point of the visit,
1958/// the tree nodes traversed from the tree root to the current node form a use
1959/// stack. The emission state of the current node depends on two factors:
1960/// 1. the emission state of the root node
1961/// 2. whether the current node is in OpenMP device context
1962/// If the function is decided to be emitted, its contained deferred diagnostics
1963/// are emitted, together with the information about the use stack.
1964///
1965class DeferredDiagnosticsEmitter
1966 : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
1967public:
1968 typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited;
1969
1970 // Whether the function is already in the current use-path.
1971 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath;
1972
1973 // The current use-path.
1974 llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath;
1975
1976 // Whether the visiting of the function has been done. Done[0] is for the
1977 // case not in OpenMP device context. Done[1] is for the case in OpenMP
1978 // device context. We need two sets because diagnostics emission may be
1979 // different depending on whether it is in OpenMP device context.
1980 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2];
1981
1982 // Functions that need their deferred diagnostics emitted. Collected
1983 // during the graph walk and emitted afterwards so that all callers
1984 // are known when producing call chain notes.
1985 llvm::SetVector<CanonicalDeclPtr<const FunctionDecl>> FnsToEmit;
1986
1987 // Emission state of the root node of the current use graph.
1988 bool ShouldEmitRootNode;
1989
1990 // Current OpenMP device context level. It is initialized to 0 and each
1991 // entering of device context increases it by 1 and each exit decreases
1992 // it by 1. Non-zero value indicates it is currently in device context.
1993 unsigned InOMPDeviceContext;
1994
1995 DeferredDiagnosticsEmitter(Sema &S)
1996 : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
1997
1998 bool shouldVisitDiscardedStmt() const { return false; }
1999
2000 void VisitOMPTargetDirective(OMPTargetDirective *Node) {
2001 ++InOMPDeviceContext;
2002 Inherited::VisitOMPTargetDirective(S: Node);
2003 --InOMPDeviceContext;
2004 }
2005
2006 void visitUsedDecl(SourceLocation Loc, Decl *D) {
2007 if (isa<VarDecl>(Val: D))
2008 return;
2009 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
2010 checkFunc(Loc, FD);
2011 else
2012 Inherited::visitUsedDecl(Loc, D);
2013 }
2014
2015 // Visitor member and parent dtors called by this dtor.
2016 void VisitCalledDestructors(CXXDestructorDecl *DD) {
2017 const CXXRecordDecl *RD = DD->getParent();
2018
2019 // Visit the dtors of all members
2020 for (const FieldDecl *FD : RD->fields()) {
2021 QualType FT = FD->getType();
2022 if (const auto *ClassDecl = FT->getAsCXXRecordDecl();
2023 ClassDecl &&
2024 (ClassDecl->isBeingDefined() || ClassDecl->isCompleteDefinition()))
2025 if (CXXDestructorDecl *MemberDtor = ClassDecl->getDestructor())
2026 asImpl().visitUsedDecl(Loc: MemberDtor->getLocation(), D: MemberDtor);
2027 }
2028
2029 // Also visit base class dtors
2030 for (const auto &Base : RD->bases()) {
2031 QualType BaseType = Base.getType();
2032 if (const auto *BaseDecl = BaseType->getAsCXXRecordDecl();
2033 BaseDecl &&
2034 (BaseDecl->isBeingDefined() || BaseDecl->isCompleteDefinition()))
2035 if (CXXDestructorDecl *BaseDtor = BaseDecl->getDestructor())
2036 asImpl().visitUsedDecl(Loc: BaseDtor->getLocation(), D: BaseDtor);
2037 }
2038 }
2039
2040 void VisitDeclStmt(DeclStmt *DS) {
2041 // Visit dtors called by variables that need destruction
2042 for (auto *D : DS->decls())
2043 if (auto *VD = dyn_cast<VarDecl>(Val: D))
2044 if (VD->isThisDeclarationADefinition() &&
2045 VD->needsDestruction(Ctx: S.Context)) {
2046 QualType VT = VD->getType();
2047 if (const auto *ClassDecl = VT->getAsCXXRecordDecl();
2048 ClassDecl && (ClassDecl->isBeingDefined() ||
2049 ClassDecl->isCompleteDefinition()))
2050 if (CXXDestructorDecl *Dtor = ClassDecl->getDestructor())
2051 asImpl().visitUsedDecl(Loc: Dtor->getLocation(), D: Dtor);
2052 }
2053
2054 Inherited::VisitDeclStmt(S: DS);
2055 }
2056 void checkVar(VarDecl *VD) {
2057 assert(VD->isFileVarDecl() &&
2058 "Should only check file-scope variables");
2059 if (auto *Init = VD->getInit()) {
2060 auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
2061 bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
2062 *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
2063 if (IsDev)
2064 ++InOMPDeviceContext;
2065 this->Visit(S: Init);
2066 if (IsDev)
2067 --InOMPDeviceContext;
2068 }
2069 }
2070
2071 void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
2072 auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];
2073 FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back();
2074 if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||
2075 S.shouldIgnoreInHostDeviceCheck(Callee: FD) || InUsePath.count(Ptr: FD))
2076 return;
2077 // Finalize analysis of OpenMP-specific constructs.
2078 if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 &&
2079 (ShouldEmitRootNode || InOMPDeviceContext))
2080 S.OpenMP().finalizeOpenMPDelayedAnalysis(Caller, Callee: FD, Loc);
2081 if (Caller) {
2082 auto &Callers = S.CUDA().DeviceKnownEmittedFns[FD];
2083 CanonicalDeclPtr<const FunctionDecl> CanonCaller(Caller);
2084 if (llvm::none_of(Range&: Callers, P: [CanonCaller](const auto &C) {
2085 return C.FD == CanonCaller;
2086 }))
2087 Callers.push_back(Elt: {.FD: Caller, .Loc: Loc});
2088 }
2089 if (ShouldEmitRootNode || InOMPDeviceContext)
2090 FnsToEmit.insert(X: FD);
2091 // Do not revisit a function if the function body has been completely
2092 // visited before.
2093 if (!Done.insert(Ptr: FD).second)
2094 return;
2095 InUsePath.insert(Ptr: FD);
2096 UsePath.push_back(Elt: FD);
2097 if (auto *S = FD->getBody()) {
2098 this->Visit(S);
2099 }
2100 if (CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(Val: FD))
2101 asImpl().VisitCalledDestructors(DD: Dtor);
2102 UsePath.pop_back();
2103 InUsePath.erase(Ptr: FD);
2104 }
2105
2106 void checkRecordedDecl(Decl *D) {
2107 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
2108 ShouldEmitRootNode = S.getEmissionStatus(Decl: FD, /*Final=*/true) ==
2109 Sema::FunctionEmissionStatus::Emitted;
2110 checkFunc(Loc: SourceLocation(), FD);
2111 } else
2112 checkVar(VD: cast<VarDecl>(Val: D));
2113 }
2114
2115 void emitDeferredDiags(const FunctionDecl *FD) {
2116 auto It = S.DeviceDeferredDiags.find(Val: FD);
2117 if (It == S.DeviceDeferredDiags.end())
2118 return;
2119 bool HasWarningOrError = false;
2120 for (PartialDiagnosticAt &PDAt : It->second) {
2121 if (S.Diags.hasFatalErrorOccurred())
2122 return;
2123 const SourceLocation &Loc = PDAt.first;
2124 const PartialDiagnostic &PD = PDAt.second;
2125 HasWarningOrError |=
2126 S.getDiagnostics().getDiagnosticLevel(DiagID: PD.getDiagID(), Loc) >=
2127 DiagnosticsEngine::Warning;
2128 {
2129 DiagnosticBuilder Builder(S.Diags.Report(Loc, DiagID: PD.getDiagID()));
2130 PD.Emit(DB: Builder);
2131 }
2132 }
2133 if (HasWarningOrError)
2134 emitCallStackNotes(S, FD);
2135 }
2136
2137 void emitCollectedDiags() {
2138 for (const auto &FD : FnsToEmit)
2139 emitDeferredDiags(FD);
2140 }
2141};
2142} // namespace
2143
2144void Sema::emitDeferredDiags() {
2145 if (ExternalSource)
2146 ExternalSource->ReadDeclsToCheckForDeferredDiags(
2147 Decls&: DeclsToCheckForDeferredDiags);
2148
2149 // For each implicit-H+D-explicit-inst function with deferred errors but no
2150 // organic device caller, drop the diagnostics and mark for a trap body.
2151 auto ClassifyImplicitHDExplicitInst = [&]() {
2152 if (!LangOpts.CUDAIsDevice)
2153 return;
2154 for (auto &Pair : DeviceDeferredDiags) {
2155 const FunctionDecl *FD = Pair.first;
2156 if (!SemaCUDA::isImplicitHDExplicitInstantiation(FD))
2157 continue;
2158 if (CUDA().DeviceKnownEmittedFns.count(Val: FD))
2159 continue;
2160 bool HasError =
2161 llvm::any_of(Range&: Pair.second, P: [&](const PartialDiagnosticAt &PDAt) {
2162 return getDiagnostics().getDiagnosticLevel(DiagID: PDAt.second.getDiagID(),
2163 Loc: PDAt.first) >=
2164 DiagnosticsEngine::Error;
2165 });
2166 if (!HasError)
2167 continue;
2168 Pair.second.clear();
2169 Context.CUDADeviceInvalidFuncs.insert(Ptr: FD->getCanonicalDecl());
2170 }
2171 };
2172
2173 if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||
2174 DeclsToCheckForDeferredDiags.empty()) {
2175 ClassifyImplicitHDExplicitInst();
2176 return;
2177 }
2178
2179 DeferredDiagnosticsEmitter DDE(*this);
2180 for (auto *D : DeclsToCheckForDeferredDiags)
2181 DDE.checkRecordedDecl(D);
2182 ClassifyImplicitHDExplicitInst();
2183 DDE.emitCollectedDiags();
2184}
2185
2186// In CUDA, there are some constructs which may appear in semantically-valid
2187// code, but trigger errors if we ever generate code for the function in which
2188// they appear. Essentially every construct you're not allowed to use on the
2189// device falls into this category, because you are allowed to use these
2190// constructs in a __host__ __device__ function, but only if that function is
2191// never codegen'ed on the device.
2192//
2193// To handle semantic checking for these constructs, we keep track of the set of
2194// functions we know will be emitted, either because we could tell a priori that
2195// they would be emitted, or because they were transitively called by a
2196// known-emitted function.
2197//
2198// We also keep a partial call graph of which not-known-emitted functions call
2199// which other not-known-emitted functions.
2200//
2201// When we see something which is illegal if the current function is emitted
2202// (usually by way of DiagIfDeviceCode, DiagIfHostCode, or
2203// CheckCall), we first check if the current function is known-emitted. If
2204// so, we immediately output the diagnostic.
2205//
2206// Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags
2207// until we discover that the function is known-emitted, at which point we take
2208// it out of this map and emit the diagnostic.
2209
2210Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc,
2211 unsigned DiagID,
2212 const FunctionDecl *Fn,
2213 Sema &S)
2214 : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
2215 ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
2216 switch (K) {
2217 case K_Nop:
2218 break;
2219 case K_Immediate:
2220 case K_ImmediateWithCallStack:
2221 ImmediateDiag.emplace(
2222 args: ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));
2223 break;
2224 case K_Deferred:
2225 assert(Fn && "Must have a function to attach the deferred diag to.");
2226 auto &Diags = S.DeviceDeferredDiags[Fn];
2227 PartialDiagId.emplace(args: Diags.size());
2228 Diags.emplace_back(args&: Loc, args: S.PDiag(DiagID));
2229 break;
2230 }
2231}
2232
2233Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D)
2234 : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
2235 ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
2236 PartialDiagId(D.PartialDiagId) {
2237 // Clean the previous diagnostics.
2238 D.ShowCallStack = false;
2239 D.ImmediateDiag.reset();
2240 D.PartialDiagId.reset();
2241}
2242
2243Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
2244 if (ImmediateDiag) {
2245 // Emit our diagnostic and, if it was a warning or error, output a callstack
2246 // if Fn isn't a priori known-emitted.
2247 ImmediateDiag.reset(); // Emit the immediate diag.
2248
2249 if (ShowCallStack) {
2250 bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
2251 DiagID, Loc) >= DiagnosticsEngine::Warning;
2252 if (IsWarningOrError)
2253 emitCallStackNotes(S, FD: Fn);
2254 }
2255 } else {
2256 assert((!PartialDiagId || ShowCallStack) &&
2257 "Must always show call stack for deferred diags.");
2258 }
2259}
2260
2261Sema::SemaDiagnosticBuilder
2262Sema::targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD) {
2263 FD = FD ? FD : getCurFunctionDecl();
2264 if (LangOpts.OpenMP)
2265 return LangOpts.OpenMPIsTargetDevice
2266 ? OpenMP().diagIfOpenMPDeviceCode(Loc, DiagID, FD)
2267 : OpenMP().diagIfOpenMPHostCode(Loc, DiagID, FD);
2268 if (getLangOpts().CUDA)
2269 return getLangOpts().CUDAIsDevice ? CUDA().DiagIfDeviceCode(Loc, DiagID)
2270 : CUDA().DiagIfHostCode(Loc, DiagID);
2271
2272 if (getLangOpts().SYCLIsDevice)
2273 return SYCL().DiagIfDeviceCode(Loc, DiagID);
2274
2275 return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, DiagID,
2276 FD, *this);
2277}
2278
2279void Sema::checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D) {
2280 if (isUnevaluatedContext() || Ty.isNull())
2281 return;
2282
2283 // The original idea behind checkTypeSupport function is that unused
2284 // declarations can be replaced with an array of bytes of the same size during
2285 // codegen, such replacement doesn't seem to be possible for types without
2286 // constant byte size like zero length arrays. So, do a deep check for SYCL.
2287 if (D && LangOpts.SYCLIsDevice) {
2288 llvm::DenseSet<QualType> Visited;
2289 SYCL().deepTypeCheckForDevice(UsedAt: Loc, Visited, DeclToCheck: D);
2290 }
2291
2292 Decl *C = cast<Decl>(Val: getCurLexicalContext());
2293
2294 // Memcpy operations for structs containing a member with unsupported type
2295 // are ok, though.
2296 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: C)) {
2297 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
2298 MD->isTrivial())
2299 return;
2300
2301 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: MD))
2302 if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())
2303 return;
2304 }
2305
2306 // Try to associate errors with the lexical context, if that is a function, or
2307 // the value declaration otherwise.
2308 const FunctionDecl *FD = isa<FunctionDecl>(Val: C)
2309 ? cast<FunctionDecl>(Val: C)
2310 : dyn_cast_or_null<FunctionDecl>(Val: D);
2311
2312 auto CheckDeviceType = [&](QualType Ty) {
2313 if (Ty->isDependentType())
2314 return;
2315
2316 if (Ty->isBitIntType()) {
2317 if (!Context.getTargetInfo().hasBitIntType()) {
2318 PartialDiagnostic PD = PDiag(DiagID: diag::err_target_unsupported_type);
2319 if (D)
2320 PD << D;
2321 else
2322 PD << "expression";
2323 targetDiag(Loc, PD, FD)
2324 << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/
2325 << Ty << Context.getTargetInfo().getTriple().str();
2326 }
2327 return;
2328 }
2329
2330 // Check if we are dealing with two 'long double' but with different
2331 // semantics.
2332 bool LongDoubleMismatched = false;
2333 if (Ty->isRealFloatingType() && Context.getTypeSize(T: Ty) == 128) {
2334 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(T: Ty);
2335 if ((&Sem != &llvm::APFloat::PPCDoubleDouble() &&
2336 !Context.getTargetInfo().hasFloat128Type()) ||
2337 (&Sem == &llvm::APFloat::PPCDoubleDouble() &&
2338 !Context.getTargetInfo().hasIbm128Type()))
2339 LongDoubleMismatched = true;
2340 }
2341
2342 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
2343 (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
2344 (Ty->isIbm128Type() && !Context.getTargetInfo().hasIbm128Type()) ||
2345 (Ty->isIntegerType() && Context.getTypeSize(T: Ty) == 128 &&
2346 !Context.getTargetInfo().hasInt128Type()) ||
2347 (Ty->isBFloat16Type() && !Context.getTargetInfo().hasBFloat16Type() &&
2348 !LangOpts.CUDAIsDevice) ||
2349 LongDoubleMismatched) {
2350 PartialDiagnostic PD = PDiag(DiagID: diag::err_target_unsupported_type);
2351 if (D)
2352 PD << D;
2353 else
2354 PD << "expression";
2355
2356 if (targetDiag(Loc, PD, FD)
2357 << true /*show bit size*/
2358 << static_cast<unsigned>(Context.getTypeSize(T: Ty)) << Ty
2359 << false /*return*/ << Context.getTargetInfo().getTriple().str()) {
2360 if (D)
2361 D->setInvalidDecl();
2362 }
2363 if (D)
2364 targetDiag(Loc: D->getLocation(), DiagID: diag::note_defined_here, FD) << D;
2365 }
2366 };
2367
2368 auto CheckType = [&](QualType Ty, bool IsRetTy = false) {
2369 if (LangOpts.SYCLIsDevice ||
2370 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice) ||
2371 LangOpts.CUDAIsDevice)
2372 CheckDeviceType(Ty);
2373
2374 QualType UnqualTy = Ty.getCanonicalType().getUnqualifiedType();
2375 const TargetInfo &TI = Context.getTargetInfo();
2376 if (!TI.hasLongDoubleType() && UnqualTy == Context.LongDoubleTy) {
2377 PartialDiagnostic PD = PDiag(DiagID: diag::err_target_unsupported_type);
2378 if (D)
2379 PD << D;
2380 else
2381 PD << "expression";
2382
2383 if (Diag(Loc, PD) << false /*show bit size*/ << 0 << Ty
2384 << false /*return*/
2385 << TI.getTriple().str()) {
2386 if (D)
2387 D->setInvalidDecl();
2388 }
2389 if (D)
2390 targetDiag(Loc: D->getLocation(), DiagID: diag::note_defined_here, FD) << D;
2391 }
2392
2393 bool IsDouble = UnqualTy == Context.DoubleTy;
2394 bool IsFloat = UnqualTy == Context.FloatTy;
2395 if (IsRetTy && !TI.hasFPReturn() && (IsDouble || IsFloat)) {
2396 PartialDiagnostic PD = PDiag(DiagID: diag::err_target_unsupported_type);
2397 if (D)
2398 PD << D;
2399 else
2400 PD << "expression";
2401
2402 if (Diag(Loc, PD) << false /*show bit size*/ << 0 << Ty << true /*return*/
2403 << TI.getTriple().str()) {
2404 if (D)
2405 D->setInvalidDecl();
2406 }
2407 if (D)
2408 targetDiag(Loc: D->getLocation(), DiagID: diag::note_defined_here, FD) << D;
2409 }
2410
2411 if (TI.hasRISCVVTypes() && Ty->isRVVSizelessBuiltinType() && FD) {
2412 llvm::StringMap<bool> CallerFeatureMap;
2413 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
2414 RISCV().checkRVVTypeSupport(Ty, Loc, D, FeatureMap: CallerFeatureMap);
2415 }
2416
2417 // Don't allow SVE types in functions without a SVE target.
2418 if (Ty->isSVESizelessBuiltinType() && FD) {
2419 llvm::StringMap<bool> CallerFeatureMap;
2420 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
2421 ARM().checkSVETypeSupport(Ty, Loc, FD, FeatureMap: CallerFeatureMap);
2422 }
2423
2424 if (TI.hasAMDGPUTypes())
2425 AMDGPU().checkAMDGPUTypeSupport(Ty, Loc);
2426
2427 if (auto *VT = Ty->getAs<VectorType>();
2428 VT && FD &&
2429 (VT->getVectorKind() == VectorKind::SveFixedLengthData ||
2430 VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) &&
2431 (LangOpts.VScaleMin != LangOpts.VScaleStreamingMin ||
2432 LangOpts.VScaleMax != LangOpts.VScaleStreamingMax)) {
2433 if (IsArmStreamingFunction(FD, /*IncludeLocallyStreaming=*/true)) {
2434 Diag(Loc, DiagID: diag::err_sve_fixed_vector_in_streaming_function)
2435 << Ty << /*Streaming*/ 0;
2436 } else if (const auto *FTy = FD->getType()->getAs<FunctionProtoType>()) {
2437 if (FTy->getAArch64SMEAttributes() &
2438 FunctionType::SME_PStateSMCompatibleMask) {
2439 Diag(Loc, DiagID: diag::err_sve_fixed_vector_in_streaming_function)
2440 << Ty << /*StreamingCompatible*/ 1;
2441 }
2442 }
2443 }
2444 };
2445
2446 CheckType(Ty);
2447 if (const auto *FPTy = dyn_cast<FunctionProtoType>(Val&: Ty)) {
2448 for (const auto &ParamTy : FPTy->param_types())
2449 CheckType(ParamTy);
2450 CheckType(FPTy->getReturnType(), /*IsRetTy=*/true);
2451 }
2452 if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Val&: Ty))
2453 CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true);
2454}
2455
2456bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
2457 SourceLocation loc = locref;
2458 if (!loc.isMacroID()) return false;
2459
2460 // There's no good way right now to look at the intermediate
2461 // expansions, so just jump to the expansion location.
2462 loc = getSourceManager().getExpansionLoc(Loc: loc);
2463
2464 // If that's written with the name, stop here.
2465 SmallString<16> buffer;
2466 if (getPreprocessor().getSpelling(loc, buffer) == name) {
2467 locref = loc;
2468 return true;
2469 }
2470 return false;
2471}
2472
2473Scope *Sema::getScopeForContext(DeclContext *Ctx) {
2474
2475 if (!Ctx)
2476 return nullptr;
2477
2478 Ctx = Ctx->getPrimaryContext();
2479 for (Scope *S = getCurScope(); S; S = S->getParent()) {
2480 // Ignore scopes that cannot have declarations. This is important for
2481 // out-of-line definitions of static class members.
2482 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
2483 if (DeclContext *Entity = S->getEntity())
2484 if (Ctx == Entity->getPrimaryContext())
2485 return S;
2486 }
2487
2488 return nullptr;
2489}
2490
2491/// Enter a new function scope
2492void Sema::PushFunctionScope() {
2493 if (FunctionScopes.empty() && CachedFunctionScope) {
2494 // Use CachedFunctionScope to avoid allocating memory when possible.
2495 CachedFunctionScope->Clear();
2496 FunctionScopes.push_back(Elt: CachedFunctionScope.release());
2497 } else {
2498 FunctionScopes.push_back(Elt: new FunctionScopeInfo(getDiagnostics()));
2499 }
2500 if (LangOpts.OpenMP)
2501 OpenMP().pushOpenMPFunctionRegion();
2502}
2503
2504void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
2505 FunctionScopes.push_back(Elt: new BlockScopeInfo(getDiagnostics(),
2506 BlockScope, Block));
2507 CapturingFunctionScopes++;
2508}
2509
2510LambdaScopeInfo *Sema::PushLambdaScope() {
2511 LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
2512 FunctionScopes.push_back(Elt: LSI);
2513 CapturingFunctionScopes++;
2514 return LSI;
2515}
2516
2517void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
2518 if (LambdaScopeInfo *const LSI = getCurLambda()) {
2519 LSI->AutoTemplateParameterDepth = Depth;
2520 return;
2521 }
2522 llvm_unreachable(
2523 "Remove assertion if intentionally called in a non-lambda context.");
2524}
2525
2526// Check that the type of the VarDecl has an accessible copy constructor and
2527// resolve its destructor's exception specification.
2528// This also performs initialization of block variables when they are moved
2529// to the heap. It uses the same rules as applicable for implicit moves
2530// according to the C++ standard in effect ([class.copy.elision]p3).
2531static void checkEscapingByref(VarDecl *VD, Sema &S) {
2532 QualType T = VD->getType();
2533 EnterExpressionEvaluationContext scope(
2534 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2535 SourceLocation Loc = VD->getLocation();
2536 Expr *VarRef =
2537 new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
2538 ExprResult Result;
2539 auto IE = InitializedEntity::InitializeBlock(BlockVarLoc: Loc, Type: T);
2540 if (S.getLangOpts().CPlusPlus23) {
2541 auto *E = ImplicitCastExpr::Create(Context: S.Context, T, Kind: CK_NoOp, Operand: VarRef, BasePath: nullptr,
2542 Cat: VK_XValue, FPO: FPOptionsOverride());
2543 Result = S.PerformCopyInitialization(Entity: IE, EqualLoc: SourceLocation(), Init: E);
2544 } else {
2545 Result = S.PerformMoveOrCopyInitialization(
2546 Entity: IE, NRInfo: Sema::NamedReturnInfo{.Candidate: VD, .S: Sema::NamedReturnInfo::MoveEligible},
2547 Value: VarRef);
2548 }
2549
2550 if (!Result.isInvalid()) {
2551 Result = S.MaybeCreateExprWithCleanups(SubExpr: Result);
2552 Expr *Init = Result.getAs<Expr>();
2553 S.Context.setBlockVarCopyInit(VD, CopyExpr: Init, CanThrow: S.canThrow(E: Init));
2554 }
2555
2556 // The destructor's exception specification is needed when IRGen generates
2557 // block copy/destroy functions. Resolve it here.
2558 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2559 if (CXXDestructorDecl *DD = RD->getDestructor()) {
2560 auto *FPT = DD->getType()->castAs<FunctionProtoType>();
2561 S.ResolveExceptionSpec(Loc, FPT);
2562 }
2563}
2564
2565static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
2566 // Set the EscapingByref flag of __block variables captured by
2567 // escaping blocks.
2568 for (const BlockDecl *BD : FSI.Blocks) {
2569 for (const BlockDecl::Capture &BC : BD->captures()) {
2570 VarDecl *VD = BC.getVariable();
2571 if (VD->hasAttr<BlocksAttr>()) {
2572 // Nothing to do if this is a __block variable captured by a
2573 // non-escaping block.
2574 if (BD->doesNotEscape())
2575 continue;
2576 VD->setEscapingByref();
2577 }
2578 // Check whether the captured variable is or contains an object of
2579 // non-trivial C union type.
2580 QualType CapType = BC.getVariable()->getType();
2581 if (CapType.hasNonTrivialToPrimitiveDestructCUnion() ||
2582 CapType.hasNonTrivialToPrimitiveCopyCUnion())
2583 S.checkNonTrivialCUnion(QT: BC.getVariable()->getType(),
2584 Loc: BD->getCaretLocation(),
2585 UseContext: NonTrivialCUnionContext::BlockCapture,
2586 NonTrivialKind: Sema::NTCUK_Destruct | Sema::NTCUK_Copy);
2587 }
2588 }
2589
2590 for (VarDecl *VD : FSI.ByrefBlockVars) {
2591 // __block variables might require us to capture a copy-initializer.
2592 if (!VD->isEscapingByref())
2593 continue;
2594 // It's currently invalid to ever have a __block variable with an
2595 // array type; should we diagnose that here?
2596 // Regardless, we don't want to ignore array nesting when
2597 // constructing this copy.
2598 if (VD->getType()->isStructureOrClassType())
2599 checkEscapingByref(VD, S);
2600 }
2601}
2602
2603Sema::PoppedFunctionScopePtr
2604Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP, Decl *D,
2605 QualType BlockType) {
2606 assert(!FunctionScopes.empty() && "mismatched push/pop!");
2607
2608 markEscapingByrefs(FSI: *FunctionScopes.back(), S&: *this);
2609
2610 PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
2611 PoppedFunctionScopeDeleter(this));
2612
2613 if (LangOpts.OpenMP)
2614 OpenMP().popOpenMPFunctionRegion(OldFSI: Scope.get());
2615
2616 // Issue any analysis-based warnings.
2617 if (WP && D) {
2618 inferNoReturnAttr(S&: *this, D);
2619 AnalysisWarnings.IssueWarnings(P: *WP, fscope: Scope.get(), D, BlockType);
2620 } else
2621 for (const auto &PUD : Scope->PossiblyUnreachableDiags)
2622 Diag(Loc: PUD.Loc, PD: PUD.PD);
2623
2624 return Scope;
2625}
2626
2627void Sema::PoppedFunctionScopeDeleter::
2628operator()(sema::FunctionScopeInfo *Scope) const {
2629 if (!Scope->isPlainFunction())
2630 Self->CapturingFunctionScopes--;
2631 // Stash the function scope for later reuse if it's for a normal function.
2632 if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
2633 Self->CachedFunctionScope.reset(p: Scope);
2634 else
2635 delete Scope;
2636}
2637
2638void Sema::PushCompoundScope(bool IsStmtExpr) {
2639 getCurFunction()->CompoundScopes.push_back(
2640 Elt: CompoundScopeInfo(IsStmtExpr, getCurFPFeatures()));
2641}
2642
2643void Sema::PopCompoundScope() {
2644 FunctionScopeInfo *CurFunction = getCurFunction();
2645 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
2646
2647 CurFunction->CompoundScopes.pop_back();
2648}
2649
2650bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
2651 return getCurFunction()->hasUnrecoverableErrorOccurred();
2652}
2653
2654void Sema::setFunctionHasBranchIntoScope() {
2655 if (!FunctionScopes.empty())
2656 FunctionScopes.back()->setHasBranchIntoScope();
2657}
2658
2659void Sema::setFunctionHasBranchProtectedScope() {
2660 if (!FunctionScopes.empty())
2661 FunctionScopes.back()->setHasBranchProtectedScope();
2662}
2663
2664void Sema::setFunctionHasIndirectGoto() {
2665 if (!FunctionScopes.empty())
2666 FunctionScopes.back()->setHasIndirectGoto();
2667}
2668
2669void Sema::setFunctionHasMustTail() {
2670 if (!FunctionScopes.empty())
2671 FunctionScopes.back()->setHasMustTail();
2672}
2673
2674BlockScopeInfo *Sema::getCurBlock() {
2675 if (FunctionScopes.empty())
2676 return nullptr;
2677
2678 auto CurBSI = dyn_cast<BlockScopeInfo>(Val: FunctionScopes.back());
2679 if (CurBSI && CurBSI->TheDecl &&
2680 !CurBSI->TheDecl->Encloses(DC: CurContext)) {
2681 // We have switched contexts due to template instantiation.
2682 assert(!CodeSynthesisContexts.empty());
2683 return nullptr;
2684 }
2685
2686 return CurBSI;
2687}
2688
2689FunctionScopeInfo *Sema::getEnclosingFunction() const {
2690 if (FunctionScopes.empty())
2691 return nullptr;
2692
2693 for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
2694 if (isa<sema::BlockScopeInfo>(Val: FunctionScopes[e]))
2695 continue;
2696 return FunctionScopes[e];
2697 }
2698 return nullptr;
2699}
2700
2701CapturingScopeInfo *Sema::getEnclosingLambdaOrBlock() const {
2702 for (auto *Scope : llvm::reverse(C: FunctionScopes)) {
2703 if (auto *CSI = dyn_cast<CapturingScopeInfo>(Val: Scope)) {
2704 auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI);
2705 if (LSI && LSI->Lambda && !LSI->Lambda->Encloses(DC: CurContext) &&
2706 LSI->AfterParameterList) {
2707 // We have switched contexts due to template instantiation.
2708 // FIXME: We should swap out the FunctionScopes during code synthesis
2709 // so that we don't need to check for this.
2710 assert(!CodeSynthesisContexts.empty());
2711 return nullptr;
2712 }
2713 return CSI;
2714 }
2715 }
2716 return nullptr;
2717}
2718
2719LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
2720 if (FunctionScopes.empty())
2721 return nullptr;
2722
2723 auto I = FunctionScopes.rbegin();
2724 if (IgnoreNonLambdaCapturingScope) {
2725 auto E = FunctionScopes.rend();
2726 while (I != E && isa<CapturingScopeInfo>(Val: *I) && !isa<LambdaScopeInfo>(Val: *I))
2727 ++I;
2728 if (I == E)
2729 return nullptr;
2730 }
2731 auto *CurLSI = dyn_cast<LambdaScopeInfo>(Val: *I);
2732 if (CurLSI && CurLSI->Lambda && CurLSI->CallOperator &&
2733 !CurLSI->Lambda->Encloses(DC: CurContext) && CurLSI->AfterParameterList) {
2734 // We have switched contexts due to template instantiation.
2735 assert(!CodeSynthesisContexts.empty());
2736 return nullptr;
2737 }
2738
2739 return CurLSI;
2740}
2741
2742// We have a generic lambda if we parsed auto parameters, or we have
2743// an associated template parameter list.
2744LambdaScopeInfo *Sema::getCurGenericLambda() {
2745 if (LambdaScopeInfo *LSI = getCurLambda()) {
2746 return (LSI->TemplateParams.size() ||
2747 LSI->GLTemplateParameterList) ? LSI : nullptr;
2748 }
2749 return nullptr;
2750}
2751
2752
2753void Sema::ActOnComment(SourceRange Comment) {
2754 if (!LangOpts.RetainCommentsFromSystemHeaders &&
2755 SourceMgr.isInSystemHeader(Loc: Comment.getBegin()))
2756 return;
2757 RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
2758 if (RC.isAlmostTrailingComment() || RC.hasUnsupportedSplice(SourceMgr)) {
2759 SourceRange MagicMarkerRange(Comment.getBegin(),
2760 Comment.getBegin().getLocWithOffset(Offset: 3));
2761 StringRef MagicMarkerText;
2762 switch (RC.getKind()) {
2763 case RawComment::RCK_OrdinaryBCPL:
2764 MagicMarkerText = "///<";
2765 break;
2766 case RawComment::RCK_OrdinaryC:
2767 MagicMarkerText = "/**<";
2768 break;
2769 case RawComment::RCK_Invalid:
2770 // FIXME: are there other scenarios that could produce an invalid
2771 // raw comment here?
2772 Diag(Loc: Comment.getBegin(), DiagID: diag::warn_splice_in_doxygen_comment);
2773 return;
2774 default:
2775 llvm_unreachable("if this is an almost Doxygen comment, "
2776 "it should be ordinary");
2777 }
2778 Diag(Loc: Comment.getBegin(), DiagID: diag::warn_not_a_doxygen_trailing_member_comment) <<
2779 FixItHint::CreateReplacement(RemoveRange: MagicMarkerRange, Code: MagicMarkerText);
2780 }
2781 Context.addComment(RC);
2782}
2783
2784// Pin this vtable to this file.
2785ExternalSemaSource::~ExternalSemaSource() {}
2786char ExternalSemaSource::ID;
2787
2788void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
2789void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
2790
2791void ExternalSemaSource::ReadKnownNamespaces(
2792 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
2793}
2794
2795void ExternalSemaSource::ReadUndefinedButUsed(
2796 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
2797
2798void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
2799 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
2800
2801bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
2802 UnresolvedSetImpl &OverloadSet) {
2803 ZeroArgCallReturnTy = QualType();
2804 OverloadSet.clear();
2805
2806 const OverloadExpr *Overloads = nullptr;
2807 bool IsMemExpr = false;
2808 if (E.getType() == Context.OverloadTy) {
2809 OverloadExpr::FindResult FR = OverloadExpr::find(E: &E);
2810
2811 // Ignore overloads that are pointer-to-member constants.
2812 if (FR.HasFormOfMemberPointer)
2813 return false;
2814
2815 Overloads = FR.Expression;
2816 } else if (E.getType() == Context.BoundMemberTy) {
2817 Overloads = dyn_cast<UnresolvedMemberExpr>(Val: E.IgnoreParens());
2818 IsMemExpr = true;
2819 }
2820
2821 bool Ambiguous = false;
2822 bool IsMV = false;
2823
2824 if (Overloads) {
2825 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
2826 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
2827 OverloadSet.addDecl(D: *it);
2828
2829 // Check whether the function is a non-template, non-member which takes no
2830 // arguments.
2831 if (IsMemExpr)
2832 continue;
2833 if (const FunctionDecl *OverloadDecl
2834 = dyn_cast<FunctionDecl>(Val: (*it)->getUnderlyingDecl())) {
2835 if (OverloadDecl->getMinRequiredArguments() == 0) {
2836 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
2837 (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
2838 OverloadDecl->isCPUSpecificMultiVersion()))) {
2839 ZeroArgCallReturnTy = QualType();
2840 Ambiguous = true;
2841 } else {
2842 ZeroArgCallReturnTy = OverloadDecl->getReturnType();
2843 IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
2844 OverloadDecl->isCPUSpecificMultiVersion();
2845 }
2846 }
2847 }
2848 }
2849
2850 // If it's not a member, use better machinery to try to resolve the call
2851 if (!IsMemExpr)
2852 return !ZeroArgCallReturnTy.isNull();
2853 }
2854
2855 // Attempt to call the member with no arguments - this will correctly handle
2856 // member templates with defaults/deduction of template arguments, overloads
2857 // with default arguments, etc.
2858 if (IsMemExpr && !E.isTypeDependent()) {
2859 Sema::TentativeAnalysisScope Trap(*this);
2860 ExprResult R = BuildCallToMemberFunction(S: nullptr, MemExpr: &E, LParenLoc: SourceLocation(), Args: {},
2861 RParenLoc: SourceLocation());
2862 if (R.isUsable()) {
2863 ZeroArgCallReturnTy = R.get()->getType();
2864 return true;
2865 }
2866 return false;
2867 }
2868
2869 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E.IgnoreParens())) {
2870 if (const auto *Fun = dyn_cast<FunctionDecl>(Val: DeclRef->getDecl())) {
2871 if (Fun->getMinRequiredArguments() == 0)
2872 ZeroArgCallReturnTy = Fun->getReturnType();
2873 return true;
2874 }
2875 }
2876
2877 // We don't have an expression that's convenient to get a FunctionDecl from,
2878 // but we can at least check if the type is "function of 0 arguments".
2879 QualType ExprTy = E.getType();
2880 const FunctionType *FunTy = nullptr;
2881 QualType PointeeTy = ExprTy->getPointeeType();
2882 if (!PointeeTy.isNull())
2883 FunTy = PointeeTy->getAs<FunctionType>();
2884 if (!FunTy)
2885 FunTy = ExprTy->getAs<FunctionType>();
2886
2887 if (const auto *FPT = dyn_cast_if_present<FunctionProtoType>(Val: FunTy)) {
2888 if (FPT->getNumParams() == 0)
2889 ZeroArgCallReturnTy = FunTy->getReturnType();
2890 return true;
2891 }
2892 return false;
2893}
2894
2895/// Give notes for a set of overloads.
2896///
2897/// A companion to tryExprAsCall. In cases when the name that the programmer
2898/// wrote was an overloaded function, we may be able to make some guesses about
2899/// plausible overloads based on their return types; such guesses can be handed
2900/// off to this method to be emitted as notes.
2901///
2902/// \param Overloads - The overloads to note.
2903/// \param FinalNoteLoc - If we've suppressed printing some overloads due to
2904/// -fshow-overloads=best, this is the location to attach to the note about too
2905/// many candidates. Typically this will be the location of the original
2906/// ill-formed expression.
2907static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
2908 const SourceLocation FinalNoteLoc) {
2909 unsigned ShownOverloads = 0;
2910 unsigned SuppressedOverloads = 0;
2911 for (UnresolvedSetImpl::iterator It = Overloads.begin(),
2912 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2913 if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) {
2914 ++SuppressedOverloads;
2915 continue;
2916 }
2917
2918 const NamedDecl *Fn = (*It)->getUnderlyingDecl();
2919 // Don't print overloads for non-default multiversioned functions.
2920 if (const auto *FD = Fn->getAsFunction()) {
2921 if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
2922 !FD->getAttr<TargetAttr>()->isDefaultVersion())
2923 continue;
2924 if (FD->isMultiVersion() && FD->hasAttr<TargetVersionAttr>() &&
2925 !FD->getAttr<TargetVersionAttr>()->isDefaultVersion())
2926 continue;
2927 }
2928 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_possible_target_of_call);
2929 ++ShownOverloads;
2930 }
2931
2932 S.Diags.overloadCandidatesShown(N: ShownOverloads);
2933
2934 if (SuppressedOverloads)
2935 S.Diag(Loc: FinalNoteLoc, DiagID: diag::note_ovl_too_many_candidates)
2936 << SuppressedOverloads;
2937}
2938
2939static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
2940 const UnresolvedSetImpl &Overloads,
2941 bool (*IsPlausibleResult)(QualType)) {
2942 if (!IsPlausibleResult)
2943 return noteOverloads(S, Overloads, FinalNoteLoc: Loc);
2944
2945 UnresolvedSet<2> PlausibleOverloads;
2946 for (OverloadExpr::decls_iterator It = Overloads.begin(),
2947 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2948 const auto *OverloadDecl = cast<FunctionDecl>(Val: *It);
2949 QualType OverloadResultTy = OverloadDecl->getReturnType();
2950 if (IsPlausibleResult(OverloadResultTy))
2951 PlausibleOverloads.addDecl(D: It.getDecl());
2952 }
2953 noteOverloads(S, Overloads: PlausibleOverloads, FinalNoteLoc: Loc);
2954}
2955
2956/// Determine whether the given expression can be called by just
2957/// putting parentheses after it. Notably, expressions with unary
2958/// operators can't be because the unary operator will start parsing
2959/// outside the call.
2960static bool IsCallableWithAppend(const Expr *E) {
2961 E = E->IgnoreImplicit();
2962 return (!isa<CStyleCastExpr>(Val: E) &&
2963 !isa<UnaryOperator>(Val: E) &&
2964 !isa<BinaryOperator>(Val: E) &&
2965 !isa<CXXOperatorCallExpr>(Val: E));
2966}
2967
2968static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {
2969 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E))
2970 E = UO->getSubExpr();
2971
2972 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
2973 if (ULE->getNumDecls() == 0)
2974 return false;
2975
2976 const NamedDecl *ND = *ULE->decls_begin();
2977 if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND))
2978 return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();
2979 }
2980 return false;
2981}
2982
2983bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
2984 bool ForceComplain,
2985 bool (*IsPlausibleResult)(QualType)) {
2986 SourceLocation Loc = E.get()->getExprLoc();
2987 SourceRange Range = E.get()->getSourceRange();
2988 UnresolvedSet<4> Overloads;
2989
2990 // If this is a SFINAE context, don't try anything that might trigger ADL
2991 // prematurely.
2992 if (!isSFINAEContext()) {
2993 QualType ZeroArgCallTy;
2994 if (tryExprAsCall(E&: *E.get(), ZeroArgCallReturnTy&: ZeroArgCallTy, OverloadSet&: Overloads) &&
2995 !ZeroArgCallTy.isNull() &&
2996 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
2997 // At this point, we know E is potentially callable with 0
2998 // arguments and that it returns something of a reasonable type,
2999 // so we can emit a fixit and carry on pretending that E was
3000 // actually a CallExpr.
3001 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Loc: Range.getEnd());
3002 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E: E.get());
3003 Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
3004 << (IsCallableWithAppend(E: E.get())
3005 ? FixItHint::CreateInsertion(InsertionLoc: ParenInsertionLoc,
3006 Code: "()")
3007 : FixItHint());
3008 if (!IsMV)
3009 notePlausibleOverloads(S&: *this, Loc, Overloads, IsPlausibleResult);
3010
3011 // FIXME: Try this before emitting the fixit, and suppress diagnostics
3012 // while doing so.
3013 E = BuildCallExpr(S: nullptr, Fn: E.get(), LParenLoc: Range.getEnd(), ArgExprs: {},
3014 RParenLoc: Range.getEnd().getLocWithOffset(Offset: 1));
3015 return true;
3016 }
3017 }
3018 if (!ForceComplain) return false;
3019
3020 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E: E.get());
3021 Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
3022 if (!IsMV)
3023 notePlausibleOverloads(S&: *this, Loc, Overloads, IsPlausibleResult);
3024 E = ExprError();
3025 return true;
3026}
3027
3028IdentifierInfo *Sema::getSuperIdentifier() const {
3029 if (!Ident_super)
3030 Ident_super = &Context.Idents.get(Name: "super");
3031 return Ident_super;
3032}
3033
3034void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
3035 CapturedRegionKind K,
3036 unsigned OpenMPCaptureLevel) {
3037 auto *CSI = new CapturedRegionScopeInfo(
3038 getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
3039 (getLangOpts().OpenMP && K == CR_OpenMP)
3040 ? OpenMP().getOpenMPNestingLevel()
3041 : 0,
3042 OpenMPCaptureLevel);
3043 CSI->ReturnType = Context.VoidTy;
3044 FunctionScopes.push_back(Elt: CSI);
3045 CapturingFunctionScopes++;
3046}
3047
3048CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
3049 if (FunctionScopes.empty())
3050 return nullptr;
3051
3052 return dyn_cast<CapturedRegionScopeInfo>(Val: FunctionScopes.back());
3053}
3054
3055const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
3056Sema::getMismatchingDeleteExpressions() const {
3057 return DeleteExprs;
3058}
3059
3060Sema::FPFeaturesStateRAII::FPFeaturesStateRAII(Sema &S)
3061 : S(S), OldFPFeaturesState(S.CurFPFeatures),
3062 OldOverrides(S.FpPragmaStack.CurrentValue),
3063 OldEvalMethod(S.PP.getCurrentFPEvalMethod()),
3064 OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {}
3065
3066Sema::FPFeaturesStateRAII::~FPFeaturesStateRAII() {
3067 S.CurFPFeatures = OldFPFeaturesState;
3068 S.FpPragmaStack.CurrentValue = OldOverrides;
3069 S.PP.setCurrentFPEvalMethod(PragmaLoc: OldFPPragmaLocation, Val: OldEvalMethod);
3070}
3071
3072bool Sema::isDeclaratorFunctionLike(Declarator &D) {
3073 assert(D.getCXXScopeSpec().isSet() &&
3074 "can only be called for qualified names");
3075
3076 auto LR = LookupResult(*this, D.getIdentifier(), D.getBeginLoc(),
3077 LookupOrdinaryName, forRedeclarationInCurContext());
3078 DeclContext *DC = computeDeclContext(SS: D.getCXXScopeSpec(),
3079 EnteringContext: !D.getDeclSpec().isFriendSpecified());
3080 if (!DC)
3081 return false;
3082
3083 LookupQualifiedName(R&: LR, LookupCtx: DC);
3084 bool Result = llvm::all_of(Range&: LR, P: [](Decl *Dcl) {
3085 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: Dcl)) {
3086 ND = ND->getUnderlyingDecl();
3087 return isa<FunctionDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND) ||
3088 isa<UsingDecl>(Val: ND);
3089 }
3090 return false;
3091 });
3092 return Result;
3093}
3094
3095Attr *Sema::CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
3096 MutableArrayRef<Expr *> Args) {
3097
3098 auto *A = AnnotateAttr::Create(Ctx&: Context, Annotation: Annot, Args: Args.data(), ArgsSize: Args.size(), CommonInfo: CI);
3099 if (!ConstantFoldAttrArgs(
3100 CI, Args: MutableArrayRef<Expr *>(A->args_begin(), A->args_end()))) {
3101 return nullptr;
3102 }
3103 return A;
3104}
3105
3106Attr *Sema::CreateAnnotationAttr(const ParsedAttr &AL) {
3107 // Make sure that there is a string literal as the annotation's first
3108 // argument.
3109 StringRef Str;
3110 if (!checkStringLiteralArgumentAttr(Attr: AL, ArgNum: 0, Str))
3111 return nullptr;
3112
3113 llvm::SmallVector<Expr *, 4> Args;
3114 Args.reserve(N: AL.getNumArgs() - 1);
3115 for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
3116 assert(!AL.isArgIdent(Idx));
3117 Args.push_back(Elt: AL.getArgAsExpr(Arg: Idx));
3118 }
3119
3120 return CreateAnnotationAttr(CI: AL, Annot: Str, Args);
3121}
3122