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