clang 24.0.0git
Sema.cpp
Go to the documentation of this file.
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
15#include "UsedDeclVisitor.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
25#include "clang/AST/StmtCXX.h"
42#include "clang/Sema/Scope.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"
52#include "clang/Sema/SemaHLSL.h"
55#include "clang/Sema/SemaM68k.h"
56#include "clang/Sema/SemaMIPS.h"
59#include "clang/Sema/SemaObjC.h"
63#include "clang/Sema/SemaPPC.h"
67#include "clang/Sema/SemaSYCL.h"
70#include "clang/Sema/SemaWasm.h"
71#include "clang/Sema/SemaX86.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
87
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, 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
114 StringRef Platform) {
116 if (!SDKInfo && !WarnedDarwinSDKInfoMissing) {
117 Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking)
118 << Platform;
119 WarnedDarwinSDKInfoMissing = true;
120 }
121 return SDKInfo;
122}
123
125 if (CachedDarwinSDKInfo)
126 return CachedDarwinSDKInfo->get();
127 auto SDKInfo = parseDarwinSDKInfo(
128 PP.getFileManager().getVirtualFileSystem(),
129 PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot);
130 if (SDKInfo && *SDKInfo) {
131 CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo));
132 return CachedDarwinSDKInfo->get();
133 }
134 if (!SDKInfo)
135 llvm::consumeError(SDKInfo.takeError());
136 CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>();
137 return nullptr;
138}
139
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(OS.str());
151}
152
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(Context.getBoolName())) {
161 Policy.Bool = BoolMacro->isObjectLike() &&
162 BoolMacro->getNumTokens() == 1 &&
163 BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
164 }
165 }
166
167 // Shorten the data output if needed
168 Policy.EntireContentsOfLargeArray = false;
169
170 return Policy;
171}
172
174 TUScope = S;
175 PushDeclContext(S, Context.getTranslationUnitDecl());
176}
177
178namespace clang {
179namespace sema {
180
182 Sema *S = nullptr;
185
186public:
187 void set(Sema &S) { this->S = &S; }
188
189 void reset() { S = nullptr; }
190
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(SM.getFileID(Loc));
200 if (IncludeLoc.isValid()) {
201 if (llvm::timeTraceProfilerEnabled()) {
203 ProfilerStack.push_back(llvm::timeTraceAsyncProfilerBegin(
204 "Source", FE ? FE->getName() : StringRef("<unknown>")));
205 }
206
207 IncludeStack.push_back(IncludeLoc);
208 S->DiagnoseNonDefaultPragmaAlignPack(
210 IncludeLoc);
211 }
212 break;
213 }
214 case ExitFile:
215 if (!IncludeStack.empty()) {
216 if (llvm::timeTraceProfilerEnabled())
217 llvm::timeTraceProfilerEnd(ProfilerStack.pop_back_val());
218
219 S->DiagnoseNonDefaultPragmaAlignPack(
221 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.
240 diag::Flavor Flavor =
242 StringRef Group = Str.substr(2);
243
244 if (S->PP.getDiagnostics().getDiagnosticIDs()->getDiagnosticsInGroup(
245 Flavor, Group, 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().
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;
277
282 Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
286 ExternalSource(nullptr), StackHandler(Diags), CurScope(nullptr),
287 Ident_super(nullptr), AMDGPUPtr(std::make_unique<SemaAMDGPU>(*this)),
288 ARMPtr(std::make_unique<SemaARM>(*this)),
289 AVRPtr(std::make_unique<SemaAVR>(*this)),
290 BPFPtr(std::make_unique<SemaBPF>(*this)),
291 CodeCompletionPtr(
292 std::make_unique<SemaCodeCompletion>(*this, CodeCompleter)),
293 CUDAPtr(std::make_unique<SemaCUDA>(*this)),
294 DirectXPtr(std::make_unique<SemaDirectX>(*this)),
295 HLSLPtr(std::make_unique<SemaHLSL>(*this)),
296 HexagonPtr(std::make_unique<SemaHexagon>(*this)),
297 LoongArchPtr(std::make_unique<SemaLoongArch>(*this)),
298 M68kPtr(std::make_unique<SemaM68k>(*this)),
299 MIPSPtr(std::make_unique<SemaMIPS>(*this)),
300 MSP430Ptr(std::make_unique<SemaMSP430>(*this)),
301 NVPTXPtr(std::make_unique<SemaNVPTX>(*this)),
302 ObjCPtr(std::make_unique<SemaObjC>(*this)),
303 OpenACCPtr(std::make_unique<SemaOpenACC>(*this)),
304 OpenCLPtr(std::make_unique<SemaOpenCL>(*this)),
305 OpenMPPtr(std::make_unique<SemaOpenMP>(*this)),
306 PPCPtr(std::make_unique<SemaPPC>(*this)),
307 PseudoObjectPtr(std::make_unique<SemaPseudoObject>(*this)),
308 RISCVPtr(std::make_unique<SemaRISCV>(*this)),
309 SPIRVPtr(std::make_unique<SemaSPIRV>(*this)),
310 SYCLPtr(std::make_unique<SemaSYCL>(*this)),
311 SwiftPtr(std::make_unique<SemaSwift>(*this)),
312 SystemZPtr(std::make_unique<SemaSystemZ>(*this)),
313 WasmPtr(std::make_unique<SemaWasm>(*this)),
314 X86Ptr(std::make_unique<SemaX86>(*this)),
316 LangOpts.getMSPointerToMemberRepresentationMethod()),
317 MSStructPragmaOn(false), VtorDispStack(LangOpts.getVtorDispMode()),
326 FullyCheckedComparisonCategories(
327 static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
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(new NSAPI(Context));
342
345
346 // Tell diagnostics how to render things from the AST library.
347 Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &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(
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(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(DN) == IdResolver.end())
374 PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
375}
376
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>(&Consumer))
388 SC->InitializeSema(*this);
389
390 // Tell the external Sema source about this Sema object.
391 if (ExternalSemaSource *ExternalSema
392 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
393 ExternalSema->InitializeSema(*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("__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("__int128_t");
409 if (IdResolver.begin(Int128) == IdResolver.end())
410 PushOnScopeChains(Context.getInt128Decl(), TUScope);
411
412 DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
413 if (IdResolver.begin(UInt128) == IdResolver.end())
414 PushOnScopeChains(Context.getUInt128Decl(), 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("SEL");
423 if (IdResolver.begin(SEL) == IdResolver.end())
424 PushOnScopeChains(Context.getObjCSelDecl(), 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("id");
429 if (IdResolver.begin(Id) == IdResolver.end())
430 PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
431
432 // Create the built-in typedef for 'Class'.
433 DeclarationName Class = &Context.Idents.get("Class");
434 if (IdResolver.begin(Class) == IdResolver.end())
435 PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
436
437 // Create the built-in forward declaratino for 'Protocol'.
438 DeclarationName Protocol = &Context.Idents.get("Protocol");
439 if (IdResolver.begin(Protocol) == IdResolver.end())
440 PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
441 }
442
443 // Create the internal type for the *StringMakeConstantString builtins.
444 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
445 if (IdResolver.begin(ConstantString) == IdResolver.end())
446 PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
447
448 // Initialize Microsoft "predefined C++ types".
449 if (getLangOpts().MSVCCompat) {
450 if (getLangOpts().CPlusPlus &&
451 IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
452 PushOnScopeChains(Context.getMSTypeInfoTagDecl(), TUScope);
453
454 addImplicitTypedef("size_t", Context.getSizeType());
455 }
456
457 // Initialize predefined OpenCL types and supported extensions and (optional)
458 // core features.
459 if (getLangOpts().OpenCL) {
461 Context.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts());
462 addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
463 addImplicitTypedef("event_t", Context.OCLEventTy);
464 auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion();
465 if (OCLCompatibleVersion >= 200) {
466 if (getLangOpts().OpenCLCPlusPlus || getLangOpts().Blocks) {
467 addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
468 addImplicitTypedef("queue_t", Context.OCLQueueTy);
469 }
470 if (getLangOpts().OpenCLPipes)
471 addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
472 addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
473 addImplicitTypedef("atomic_uint",
474 Context.getAtomicType(Context.UnsignedIntTy));
475 addImplicitTypedef("atomic_float",
476 Context.getAtomicType(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("atomic_flag", Context.getAtomicType(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(Context.getSizeType());
496 auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
497 auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
498 auto AtomicPtrDiffT =
499 Context.getAtomicType(Context.getPointerDiffType());
500 addImplicitTypedef("atomic_size_t", AtomicSizeT);
501 addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
502 addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
503 addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
504 };
505
506 if (Context.getTypeSize(Context.getSizeType()) == 32) {
507 AddPointerSizeDependentTypes();
508 }
509
510 if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) {
511 auto AtomicHalfT = Context.getAtomicType(Context.HalfTy);
512 addImplicitTypedef("atomic_half", AtomicHalfT);
513 }
514
515 std::vector<QualType> Atomic64BitTypes;
516 if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",
517 getLangOpts()) &&
518 getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",
519 getLangOpts())) {
520 if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {
521 auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
522 addImplicitTypedef("atomic_double", AtomicDoubleT);
523 Atomic64BitTypes.push_back(AtomicDoubleT);
524 }
525 auto AtomicLongT = Context.getAtomicType(Context.LongTy);
526 auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
527 addImplicitTypedef("atomic_long", AtomicLongT);
528 addImplicitTypedef("atomic_ulong", AtomicULongT);
529
530
531 if (Context.getTypeSize(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("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("__builtin_ms_va_list");
595 if (IdResolver.begin(MSVaList) == IdResolver.end())
596 PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
597 }
598
599 if (Context.getTargetInfo().hasBuiltinZOSVaList()) {
600 DeclarationName ZOSVaList = &Context.Idents.get("__builtin_zos_va_list");
601 if (IdResolver.begin(ZOSVaList) == IdResolver.end())
602 PushOnScopeChains(Context.getBuiltinZOSVaListDecl(), TUScope);
603 }
604
605 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
606 if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
607 PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
608}
609
611 assert(InstantiatingSpecializations.empty() &&
612 "failed to clean up an InstantiatingTemplate?");
613
615
616 // Kill all the active scopes.
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>(&Consumer))
622 SC->ForgetSema();
623
624 // Detach from the external Sema source.
625 if (ExternalSemaSource *ExternalSema
626 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
627 ExternalSema->ForgetSema();
628
629 // Delete cached satisfactions.
630 for (auto [_, Node] : SatisfactionCache)
631 delete Node;
632
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
644 llvm::function_ref<void()> Fn) {
645 StackHandler.runWithSufficientStackSpace(Loc, Fn);
646}
647
649 UnavailableAttr::ImplicitReason reason) {
650 // If we're not in a function, it's an error.
651 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
652 if (!fn) return false;
653
654 // If we're in template instantiation, it's an error.
656 return false;
657
658 // If that function's not in a system header, it's an error.
659 if (!Context.getSourceManager().isInSystemHeader(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(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
666 return true;
667}
668
672
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>(ExternalSource.get()))
682 Ex->AddSource(std::move(E));
683 else
684 ExternalSource = llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>(
685 ExternalSource, 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
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, diag::warn_nullability_lost) << SrcType << DstType;
711}
712
713// Generate diagnostics when adding or removing effects in a type conversion.
715 SourceLocation Loc) {
716 const auto SrcFX = FunctionEffectsRef::get(SrcType);
717 const auto DstFX = FunctionEffectsRef::get(DstType);
718 if (SrcFX != DstFX) {
719 for (const auto &Diff : FunctionEffectDiffVector(SrcFX, DstFX)) {
720 if (Diff.shouldDiagnoseConversion(SrcType, SrcFX, DstType, DstFX))
721 Diag(Loc, diag::warn_invalid_add_func_effects) << Diff.effectName();
722 }
723 }
724}
725
727 // nullptr only exists from C++11 on, so don't warn on its absence earlier.
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>(EStripped))
738 return;
739
740 if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
741 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 ==
749 return;
750
751 // Ignore null pointers in defaulted comparison operators.
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(MaybeMacroLoc) &&
764 !findMacroSpelling(MaybeMacroLoc, "NULL"))
765 return;
766
767 Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
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.
776 const CXXCastPath *BasePath,
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
804 if (Context.hasAnyFunctionEffects() && !isCast(CCK) &&
805 Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
807
808 QualType ExprTy = Context.getCanonicalType(E->getType());
809 QualType TypeTy = Context.getCanonicalType(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>(E))
817 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
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.
829 E->getType(), E, !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>(E)) {
844 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
845 if (VD->getStorageClass() == SC_Register) {
846 Diag(E->getExprLoc(), 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>(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>(E) || isa<CXXStaticCastExpr>(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(SourceOBT->getBehaviorKind(), Ty);
873 }
874 }
875 }
876
877 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
879}
880
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>(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, 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(DeclToCheck))
917 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(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(DeclToCheck);
924 }
925
926 if (const VarDecl *VD = dyn_cast<VarDecl>(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(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, 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(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(DeclToCheck);
954 }
955
956 return false;
957}
958
959static bool isFunctionOrVarDeclExternC(const NamedDecl *ND) {
960 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
961 return FD->isExternC();
962 return cast<VarDecl>(ND)->isExternC();
963}
964
965/// Determine whether ND is an external-linkage function or variable whose
966/// type has no linkage.
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() &&
974}
975
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.
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
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>(ND)) {
1006 if (FD->isDefined())
1007 continue;
1008 if (FD->isExternallyVisible() &&
1010 !FD->getMostRecentDecl()->isInlined() &&
1011 !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
1012 continue;
1013 if (FD->getBuiltinID())
1014 continue;
1015 } else {
1016 const auto *VD = cast<VarDecl>(ND);
1017 if (VD->hasDefinition() != VarDecl::DeclarationOnly)
1018 continue;
1019 if (VD->isExternallyVisible() &&
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(std::make_pair(ND, UndefinedUse.second));
1032 }
1033}
1034
1035/// checkUndefinedButUsed - Check for undefined objects with internal linkage
1036/// or that are inline.
1038 if (S.UndefinedButUsed.empty()) return;
1039
1040 // Collect all the still-undefined entities with internal linkage.
1043 S.UndefinedButUsed.clear();
1044 if (Undefined.empty()) return;
1045
1046 for (const auto &Undef : Undefined) {
1047 ValueDecl *VD = cast<ValueDecl>(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.
1061 ? diag::ext_undefined_internal_type
1062 : diag::err_undefined_internal_type)
1063 << isa<VarDecl>(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>(VD)) {
1070 auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();
1071 if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
1072 llvm::omp::TraitProperty::
1073 implementation_extension_disable_implicit_base)) {
1074 const auto *Func = cast<FunctionDecl>(
1075 cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl());
1076 IsImplicitBase = BaseD->isImplicit() &&
1077 Func->getIdentifier()->isMangledOpenMPVariantName();
1078 }
1079 }
1080 if (!S.getLangOpts().OpenMP || !IsImplicitBase)
1081 S.Diag(VD->getLocation(), diag::warn_undefined_internal)
1082 << isa<VarDecl>(VD) << VD;
1083 } else if (auto *FD = dyn_cast<FunctionDecl>(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(VD->getLocation(), 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(VD->getLocation(), diag::err_undefined_inline_var) << VD;
1093 }
1094 if (UseLoc.isValid())
1095 S.Diag(UseLoc, diag::note_used_here);
1096 }
1097}
1098
1100 if (!ExternalSource)
1101 return;
1102
1104 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
1105 for (auto &WeakID : WeakIDs)
1106 (void)WeakUndeclaredIdentifiers[WeakID.first].insert(WeakID.second);
1107}
1108
1110 if (!ExternalSource)
1111 return;
1112
1114 ExternalSource->ReadExtnameUndeclaredIdentifiers(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.
1127 RecordCompleteMap &MNCComplete) {
1128 RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
1129 if (Cache != MNCComplete.end())
1130 return Cache->second;
1131 if (!RD->isCompleteDefinition())
1132 return false;
1133 bool Complete = true;
1135 E = RD->decls_end();
1136 I != E && Complete; ++I) {
1137 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
1138 Complete = M->isDefined() || M->isDefaulted() ||
1139 (M->isPureVirtual() && !isa<CXXDestructorDecl>(M));
1140 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*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>(*I)) {
1148 if (R->isInjectedClassName())
1149 continue;
1150 if (R->hasDefinition())
1151 Complete = MethodsAndNestedClassesComplete(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.
1169 RecordCompleteMap &RecordsComplete,
1170 RecordCompleteMap &MNCComplete) {
1171 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
1172 if (Cache != RecordsComplete.end())
1173 return Cache->second;
1174 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
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(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>(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
1202 // The candidates are collected while iterating a Scope's SmallPtrSet, so sort
1203 // by source location for a deterministic order.
1204 Sorted.assign(UnusedLocalTypedefNameCandidates.begin(),
1206 llvm::sort(Sorted,
1207 [](const TypedefNameDecl *LHS, const TypedefNameDecl *RHS) {
1208 return LHS->getLocation().getRawEncoding() <
1209 RHS->getLocation().getRawEncoding();
1210 });
1211}
1212
1214 if (ExternalSource)
1215 ExternalSource->ReadUnusedLocalTypedefNameCandidates(
1219 for (const TypedefNameDecl *TD : Sorted) {
1220 if (TD->isReferenced())
1221 continue;
1222 Diag(TD->getLocation(), diag::warn_unused_local_typedef)
1223 << isa<TypeAliasDecl>(TD) << TD->getDeclName();
1224 }
1226}
1227
1229 if (getLangOpts().CPlusPlusModules &&
1230 getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit)
1231 HandleStartOfHeaderUnit();
1232}
1233
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");
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.
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.
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.
1274 ExternalSource->ReadPendingInstantiations(Pending);
1275 for (auto PII : Pending)
1276 if (auto Func = dyn_cast<FunctionDecl>(PII.first))
1277 Func->setInstantiationIsPending(true);
1279 Pending.begin(), Pending.end());
1280 }
1281
1282 {
1283 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1285 }
1286
1288
1289 assert(LateParsedInstantiations.empty() &&
1290 "end of TU template instantiation should not create more "
1291 "late-parsed templates");
1292}
1293
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) {
1307
1309 !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1313
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.
1325
1326 if (LangOpts.PCHInstantiateTemplates) {
1327 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1329 }
1330 }
1331
1337
1338 // All delayed member exception specs should be checked or we end up accepting
1339 // incompatible declarations.
1342
1343 // All dllexport classes should have been processed already.
1344 assert(DelayedDllExportClasses.empty());
1345 assert(DelayedDllExportMemberFunctions.empty());
1346
1347 // Remove file scoped decls that turned out to be used.
1349 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
1351 [this](const DeclaratorDecl *DD) {
1352 return ShouldRemoveFromUnused(this, DD);
1353 }),
1354 UnusedFileScopedDecls.end());
1355
1356 if (TUKind == TU_Prefix) {
1357 // Translation unit prefixes don't need any of the checking below.
1358 if (!PP.isIncrementalProcessingEnabled())
1359 TUScope = nullptr;
1360 return;
1361 }
1362
1363 // Check for #pragma weak identifiers that were never declared
1365 for (const auto &WeakIDs : WeakUndeclaredIdentifiers) {
1366 if (WeakIDs.second.empty())
1367 continue;
1368
1369 Decl *PrevDecl = LookupSingleName(TUScope, WeakIDs.first, SourceLocation(),
1371 if (PrevDecl != nullptr &&
1372 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
1373 for (const auto &WI : WeakIDs.second)
1374 Diag(WI.getLocation(), diag::warn_attribute_wrong_decl_type)
1375 << "'weak'" << /*isRegularKeyword=*/0 << ExpectedVariableOrFunction;
1376 else
1377 for (const auto &WI : WeakIDs.second)
1378 Diag(WI.getLocation(), diag::warn_weak_identifier_undeclared)
1379 << WeakIDs.first;
1380 }
1381
1382 if (LangOpts.CPlusPlus11 &&
1383 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
1385
1386 if (!Diags.hasErrorOccurred()) {
1387 if (ExternalSource)
1388 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
1389 checkUndefinedButUsed(*this);
1390 }
1391
1392 // A global-module-fragment is only permitted within a module unit.
1393 if (!ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1395 Diag(ModuleScopes.back().BeginLoc,
1396 diag::err_module_declaration_missing_after_global_module_introducer);
1397 } else if (getLangOpts().getCompilingModule() ==
1399 // We can't use ModuleScopes here since ModuleScopes is always
1400 // empty if we're compiling the BMI.
1401 !getASTContext().getCurrentNamedModule()) {
1402 // If we are building a module interface unit, we should have seen the
1403 // module declaration.
1404 //
1405 // FIXME: Make a better guess as to where to put the module declaration.
1406 Diag(getSourceManager().getLocForStartOfFile(
1407 getSourceManager().getMainFileID()),
1408 diag::err_module_declaration_missing);
1409 }
1410
1411 // Now we can decide whether the modules we're building need an initializer.
1412 if (Module *CurrentModule = getCurrentModule();
1413 CurrentModule && CurrentModule->isInterfaceOrPartition()) {
1414 auto DoesModNeedInit = [this](Module *M) {
1415 for (Decl *D : getASTContext().getModuleInitializers(M)) {
1416 auto *VD = dyn_cast<VarDecl>(D);
1417 // TLS initialization is not handled by the TU's global initializer.
1418 if (!VD || VD->getTLSKind() != VarDecl::TLS_None)
1419 continue;
1420
1421 if (const VarDecl *InitDecl = VD->getInitializingDeclaration();
1422 (InitDecl && !InitDecl->hasConstantInitialization()) ||
1425 return true;
1426 }
1427 for (auto [Exported, _] : M->Exports)
1428 if (Exported->isNamedModuleInterfaceHasInit())
1429 return true;
1430 for (Module *I : M->Imports)
1432 return true;
1433
1434 return false;
1435 };
1436
1437 CurrentModule->NamedModuleHasInit =
1438 DoesModNeedInit(CurrentModule) ||
1439 llvm::any_of(CurrentModule->submodules(), DoesModNeedInit);
1440 }
1441
1442 if (TUKind == TU_ClangModule) {
1443 // If we are building a module, resolve all of the exported declarations
1444 // now.
1445 if (Module *CurrentModule = PP.getCurrentModule()) {
1446 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
1447
1449 Stack.push_back(CurrentModule);
1450 while (!Stack.empty()) {
1451 Module *Mod = Stack.pop_back_val();
1452
1453 // Resolve the exported declarations and conflicts.
1454 // FIXME: Actually complain, once we figure out how to teach the
1455 // diagnostic client to deal with complaints in the module map at this
1456 // point.
1457 ModMap.resolveExports(Mod, /*Complain=*/false);
1458 ModMap.resolveUses(Mod, /*Complain=*/false);
1459 ModMap.resolveConflicts(Mod, /*Complain=*/false);
1460
1461 // Queue the submodules, so their exports will also be resolved.
1462 auto SubmodulesRange = Mod->submodules();
1463 Stack.append(SubmodulesRange.begin(), SubmodulesRange.end());
1464 }
1465 }
1466
1467 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1468 // modules when they are built, not every time they are used.
1470 }
1471
1472 // C++ standard modules. Diagnose cases where a function is declared inline
1473 // in the module purview but has no definition before the end of the TU or
1474 // the start of a Private Module Fragment (if one is present).
1475 if (!PendingInlineFuncDecls.empty()) {
1476 for (auto *FD : PendingInlineFuncDecls) {
1477 bool DefInPMF = false;
1478 if (auto *FDD = FD->getDefinition()) {
1479 DefInPMF = FDD->getOwningModule()->isPrivateModule();
1480 if (!DefInPMF)
1481 continue;
1482 }
1483 Diag(FD->getLocation(), diag::err_export_inline_not_defined) << DefInPMF;
1484 // If we have a PMF it should be at the end of the ModuleScopes.
1485 if (DefInPMF &&
1486 ModuleScopes.back().Module->Kind == Module::PrivateModuleFragment) {
1487 Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
1488 }
1489 }
1490 PendingInlineFuncDecls.clear();
1491 }
1492
1493 // C99 6.9.2p2:
1494 // A declaration of an identifier for an object that has file
1495 // scope without an initializer, and without a storage-class
1496 // specifier or with the storage-class specifier static,
1497 // constitutes a tentative definition. If a translation unit
1498 // contains one or more tentative definitions for an identifier,
1499 // and the translation unit contains no external definition for
1500 // that identifier, then the behavior is exactly as if the
1501 // translation unit contains a file scope declaration of that
1502 // identifier, with the composite type as of the end of the
1503 // translation unit, with an initializer equal to 0.
1505 for (TentativeDefinitionsType::iterator
1506 T = TentativeDefinitions.begin(ExternalSource.get()),
1507 TEnd = TentativeDefinitions.end();
1508 T != TEnd; ++T) {
1509 VarDecl *VD = (*T)->getActingDefinition();
1510
1511 // If the tentative definition was completed, getActingDefinition() returns
1512 // null. If we've already seen this variable before, insert()'s second
1513 // return value is false.
1514 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
1515 continue;
1516
1517 if (const IncompleteArrayType *ArrayT
1518 = Context.getAsIncompleteArrayType(VD->getType())) {
1519 // Set the length of the array to 1 (C99 6.9.2p5).
1520 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
1521 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
1522 QualType T = Context.getConstantArrayType(
1523 ArrayT->getElementType(), One, nullptr, ArraySizeModifier::Normal, 0);
1524 VD->setType(T);
1525 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
1526 diag::err_tentative_def_incomplete_type))
1527 VD->setInvalidDecl();
1528
1529 // No initialization is performed for a tentative definition.
1531
1532 // In C, if the definition is const-qualified and has no initializer, it
1533 // is left uninitialized unless it has static or thread storage duration.
1534 QualType Type = VD->getType();
1535 if (!VD->isInvalidDecl() && !getLangOpts().CPlusPlus &&
1536 Type.isConstQualified() && !VD->getAnyInitializer()) {
1537 unsigned DiagID = diag::warn_default_init_const_unsafe;
1538 if (VD->getStorageDuration() == SD_Static ||
1540 DiagID = diag::warn_default_init_const;
1541
1542 bool EmitCppCompat = !Diags.isIgnored(
1543 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
1544 VD->getLocation());
1545
1546 Diag(VD->getLocation(), DiagID) << Type << EmitCppCompat;
1547 }
1548
1549 // Uninitialized tentative definitions are zero-initialized (C17 6.9.2p2) so
1550 // diagnose fields requiring explicit initialization.
1551 if (!VD->isInvalidDecl() && !getLangOpts().CPlusPlus &&
1552 !VD->getAnyInitializer()) {
1553 if (const RecordDecl *RD = Type->getAsRecordDecl();
1555 Diag(VD->getLocation(), diag::warn_field_requires_explicit_init)
1556 << /*Var-in-Record=*/1 << RD;
1557 for (const FieldDecl *FD : RD->fields())
1558 if (FD->hasAttr<ExplicitInitAttr>())
1559 Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
1560 }
1561 }
1562
1563 // Notify the consumer that we've completed a tentative definition.
1564 if (!VD->isInvalidDecl())
1565 Consumer.CompleteTentativeDefinition(VD);
1566 }
1567
1568 // In incremental mode, tentative definitions belong to the current
1569 // partial translation unit (PTU). Once they have been completed and
1570 // emitted to codegen, drop them to prevent re-emission in future PTUs.
1571 if (PP.isIncrementalProcessingEnabled())
1573 TentativeDefinitions.end());
1574
1575 for (auto *D : ExternalDeclarations) {
1576 if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())
1577 continue;
1578
1579 Consumer.CompleteExternalDeclaration(D);
1580 }
1581
1582 // Visit all pending #pragma export.
1583 for (const PendingPragmaInfo &Exported : PendingExportedNames.values()) {
1584 if (!Exported.Used)
1585 Diag(Exported.NameLoc, diag::warn_failed_to_resolve_pragma) << "export";
1586 }
1587
1588 if (LangOpts.HLSL)
1589 HLSL().ActOnEndOfTranslationUnit(getASTContext().getTranslationUnitDecl());
1590 if (LangOpts.OpenACC)
1592 getASTContext().getTranslationUnitDecl());
1593
1594 // If there were errors, disable 'unused' warnings since they will mostly be
1595 // noise. Don't warn for a use from a module: either we should warn on all
1596 // file-scope declarations in modules or not at all, but whether the
1597 // declaration is used is immaterial.
1598 if (!Diags.hasErrorOccurred() && TUKind != TU_ClangModule) {
1599 // Output warning for unused file scoped decls.
1600 for (UnusedFileScopedDeclsType::iterator
1601 I = UnusedFileScopedDecls.begin(ExternalSource.get()),
1602 E = UnusedFileScopedDecls.end();
1603 I != E; ++I) {
1604 if (ShouldRemoveFromUnused(this, *I))
1605 continue;
1606
1607 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1608 const FunctionDecl *DiagD;
1609 if (!FD->hasBody(DiagD))
1610 DiagD = FD;
1611 if (DiagD->isDeleted())
1612 continue; // Deleted functions are supposed to be unused.
1613 SourceRange DiagRange = DiagD->getLocation();
1614 if (const ASTTemplateArgumentListInfo *ASTTAL =
1616 DiagRange.setEnd(ASTTAL->RAngleLoc);
1617 if (DiagD->isReferenced()) {
1618 if (isa<CXXMethodDecl>(DiagD))
1619 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1620 << DiagD << DiagRange;
1621 else {
1622 if (FD->getStorageClass() == SC_Static &&
1623 !FD->isInlineSpecified() &&
1624 !SourceMgr.isInMainFile(
1625 SourceMgr.getExpansionLoc(FD->getLocation())))
1626 Diag(DiagD->getLocation(),
1627 diag::warn_unneeded_static_internal_decl)
1628 << DiagD << DiagRange;
1629 else
1630 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1631 << /*function=*/0 << DiagD << DiagRange;
1632 }
1633 } else if (!FD->isTargetMultiVersion() ||
1634 FD->isTargetMultiVersionDefault()) {
1635 if (FD->getDescribedFunctionTemplate())
1636 Diag(DiagD->getLocation(), diag::warn_unused_template)
1637 << /*function=*/0 << DiagD << DiagRange;
1638 else
1639 Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)
1640 ? diag::warn_unused_member_function
1641 : diag::warn_unused_function)
1642 << DiagD << DiagRange;
1643 }
1644 } else {
1645 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
1646 if (!DiagD)
1647 DiagD = cast<VarDecl>(*I);
1648 SourceRange DiagRange = DiagD->getLocation();
1649 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(DiagD)) {
1650 if (const ASTTemplateArgumentListInfo *ASTTAL =
1651 VTSD->getTemplateArgsAsWritten())
1652 DiagRange.setEnd(ASTTAL->RAngleLoc);
1653 }
1654 if (DiagD->isReferenced()) {
1655 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1656 << /*variable=*/1 << DiagD << DiagRange;
1657 } else if (DiagD->getDescribedVarTemplate()) {
1658 Diag(DiagD->getLocation(), diag::warn_unused_template)
1659 << /*variable=*/1 << DiagD << DiagRange;
1660 } else if (DiagD->getType().isConstQualified()) {
1661 const SourceManager &SM = SourceMgr;
1662 if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
1663 !PP.getLangOpts().IsHeaderFile)
1664 Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1665 << DiagD << DiagRange;
1666 } else {
1667 Diag(DiagD->getLocation(), diag::warn_unused_variable)
1668 << DiagD << DiagRange;
1669 }
1670 }
1671 }
1672
1674 }
1675
1676 if (!Diags.isIgnored(diag::warn_unused_but_set_global, SourceLocation())) {
1677 // Diagnose unused-but-set static globals in a deterministic order.
1678 // Not tracking shadowing info for static globals; there's nothing to
1679 // shadow.
1680 struct LocAndDiag {
1681 SourceLocation Loc;
1683 };
1685 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
1686 DeclDiags.push_back(LocAndDiag{Loc, std::move(PD)});
1687 };
1688
1689 // For -Wunused-but-set-variable we only care about variables that were
1690 // referenced by the TU end.
1691 for (const auto &Ref : RefsMinusAssignments) {
1692 const VarDecl *VD = Ref.first;
1693 // Only diagnose internal linkage file vars defined in the main file to
1694 // match -Wunused-variable behavior and avoid false positives from
1695 // headers.
1697 DiagnoseUnusedButSetDecl(VD, addDiag);
1698 }
1699
1700 llvm::sort(DeclDiags,
1701 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
1702 // Sorting purely for determinism; matches behavior in
1703 // Sema::ActOnPopScope.
1704 return LHS.Loc < RHS.Loc;
1705 });
1706 for (const LocAndDiag &D : DeclDiags)
1707 Diag(D.Loc, D.PD);
1708 }
1709
1710 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
1711 // FIXME: Load additional unused private field candidates from the external
1712 // source.
1713 RecordCompleteMap RecordsComplete;
1714 RecordCompleteMap MNCComplete;
1715 for (const NamedDecl *D : UnusedPrivateFields) {
1716 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1717 if (RD && !RD->isUnion() && !D->hasAttr<UnusedAttr>() &&
1718 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
1719 Diag(D->getLocation(), diag::warn_unused_private_field)
1720 << D->getDeclName();
1721 }
1722 }
1723 }
1724
1725 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
1726 if (ExternalSource)
1727 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1728 for (const auto &DeletedFieldInfo : DeleteExprs) {
1729 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1730 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
1731 DeleteExprLoc.second);
1732 }
1733 }
1734 }
1735
1736 AnalysisWarnings.IssueWarnings(Context.getTranslationUnitDecl());
1737
1738 if (Context.hasAnyFunctionEffects())
1739 performFunctionEffectAnalysis(Context.getTranslationUnitDecl());
1740
1741 // Check we've noticed that we're no longer parsing the initializer for every
1742 // variable. If we miss cases, then at best we have a performance issue and
1743 // at worst a rejects-valid bug.
1744 assert(ParsingInitForAutoVars.empty() &&
1745 "Didn't unmark var as having its initializer parsed");
1746
1747 if (!PP.isIncrementalProcessingEnabled())
1748 TUScope = nullptr;
1749
1750 checkExposure(Context.getTranslationUnitDecl());
1751}
1752
1753
1754//===----------------------------------------------------------------------===//
1755// Helper functions.
1756//===----------------------------------------------------------------------===//
1757
1759 DeclContext *DC = CurContext;
1760
1761 while (true) {
1763 CXXExpansionStmtDecl>(DC)) {
1764 DC = DC->getParent();
1765 } else if (!AllowLambda && isa<CXXMethodDecl>(DC) &&
1766 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
1767 cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
1768 DC = DC->getParent()->getParent();
1769 } else
1770 break;
1771 }
1772
1773 return DC;
1774}
1775
1776/// getCurFunctionDecl - If inside of a function body, this returns a pointer
1777/// to the function decl for the function being parsed. If we're currently
1778/// in a 'block', this returns the containing context.
1779FunctionDecl *Sema::getCurFunctionDecl(bool AllowLambda) const {
1780 DeclContext *DC = getFunctionLevelDeclContext(AllowLambda);
1781 return dyn_cast<FunctionDecl>(DC);
1782}
1783
1786 while (isa<RecordDecl>(DC))
1787 DC = DC->getParent();
1788 return dyn_cast<ObjCMethodDecl>(DC);
1789}
1790
1794 return cast<NamedDecl>(DC);
1795 return nullptr;
1796}
1797
1803
1804void Sema::EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB) {
1805 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1806 // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1807 // been made more painfully obvious by the refactor that introduced this
1808 // function, but it is possible that the incoming argument can be
1809 // eliminated. If it truly cannot be (for example, there is some reentrancy
1810 // issue I am not seeing yet), then there should at least be a clarifying
1811 // comment somewhere.
1812 Diagnostic DiagInfo(&Diags, DB);
1813 if (SFINAETrap *Trap = getSFINAEContext()) {
1814 sema::TemplateDeductionInfo *Info = Trap->getDeductionInfo();
1817 // We'll report the diagnostic below.
1818 break;
1819
1821 // Count this failure so that we know that template argument deduction
1822 // has failed.
1823 Trap->setErrorOccurred();
1824
1825 // Make a copy of this suppressed diagnostic and store it with the
1826 // template-deduction information.
1827 if (Info && !Info->hasSFINAEDiagnostic())
1828 Info->addSFINAEDiagnostic(
1829 DiagInfo.getLocation(),
1830 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1831
1832 Diags.setLastDiagnosticIgnored(true);
1833 return;
1834
1836 // Per C++ Core Issue 1170, access control is part of SFINAE.
1837 // Additionally, the WithAccessChecking flag can be used to temporarily
1838 // make access control a part of SFINAE for the purposes of checking
1839 // type traits.
1840 if (!Trap->withAccessChecking() && !getLangOpts().CPlusPlus11)
1841 break;
1842
1843 SourceLocation Loc = DiagInfo.getLocation();
1844
1845 // Suppress this diagnostic.
1846 Trap->setErrorOccurred();
1847
1848 // Make a copy of this suppressed diagnostic and store it with the
1849 // template-deduction information.
1850 if (Info && !Info->hasSFINAEDiagnostic())
1851 Info->addSFINAEDiagnostic(
1852 DiagInfo.getLocation(),
1853 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1854
1855 Diags.setLastDiagnosticIgnored(true);
1856
1857 // Now produce a C++98 compatibility warning.
1858 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1859
1860 // The last diagnostic which Sema produced was ignored. Suppress any
1861 // notes attached to it.
1862 Diags.setLastDiagnosticIgnored(true);
1863 return;
1864 }
1865
1867 if (DiagnosticsEngine::Level Level = getDiagnostics().getDiagnosticLevel(
1868 DiagInfo.getID(), DiagInfo.getLocation());
1870 return;
1871 // Make a copy of this suppressed diagnostic and store it with the
1872 // template-deduction information;
1873 if (Info) {
1875 DiagInfo.getLocation(),
1876 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1877 if (!Diags.getDiagnosticIDs()->isNote(DiagID))
1879 Info->addSuppressedDiagnostic(Loc, std::move(PD));
1880 });
1881 }
1882
1883 // Suppress this diagnostic.
1884 Diags.setLastDiagnosticIgnored(true);
1885 return;
1886 }
1887 }
1888
1889 // Copy the diagnostic printing policy over the ASTContext printing policy.
1890 // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292
1891 Context.setPrintingPolicy(getPrintingPolicy());
1892
1893 // Emit the diagnostic.
1894 if (!Diags.EmitDiagnostic(DB))
1895 return;
1896
1897 // If this is not a note, and we're in a template instantiation
1898 // that is different from the last template instantiation where
1899 // we emitted an error, print a template instantiation
1900 // backtrace.
1901 if (!Diags.getDiagnosticIDs()->isNote(DiagID))
1903}
1904
1907 return true;
1908 auto *FD = dyn_cast<FunctionDecl>(CurContext);
1909 if (!FD)
1910 return false;
1911 auto Loc = DeviceDeferredDiags.find(FD);
1912 if (Loc == DeviceDeferredDiags.end())
1913 return false;
1914 for (auto PDAt : Loc->second) {
1915 if (Diags.getDiagnosticIDs()->isDefaultMappingAsError(
1916 PDAt.second.getDiagID()))
1917 return true;
1918 }
1919 return false;
1920}
1921
1922// Print notes showing how we can reach FD starting from an a priori
1923// known-callable function. When a function has multiple callers, emit
1924// each call chain separately. The first note in each chain uses
1925// "called by" and subsequent notes use "which is called by".
1926static void emitCallStackNotes(Sema &S, const FunctionDecl *FD) {
1927 auto FnIt = S.CUDA().DeviceKnownEmittedFns.find(FD);
1928 if (FnIt == S.CUDA().DeviceKnownEmittedFns.end())
1929 return;
1930
1931 for (const auto &CallerInfo : FnIt->second) {
1933 return;
1934 S.Diags.Report(CallerInfo.Loc, diag::note_called_by) << CallerInfo.FD;
1935 // Walk up the rest of the chain using "which is called by".
1936 auto NextIt = S.CUDA().DeviceKnownEmittedFns.find(CallerInfo.FD);
1937 while (NextIt != S.CUDA().DeviceKnownEmittedFns.end()) {
1939 return;
1940 const auto &Next = NextIt->second.front();
1941 S.Diags.Report(Next.Loc, diag::note_which_is_called_by) << Next.FD;
1942 NextIt = S.CUDA().DeviceKnownEmittedFns.find(Next.FD);
1943 }
1944 }
1945}
1946
1947namespace {
1948
1949/// Helper class that emits deferred diagnostic messages if an entity directly
1950/// or indirectly using the function that causes the deferred diagnostic
1951/// messages is known to be emitted.
1952///
1953/// During parsing of AST, certain diagnostic messages are recorded as deferred
1954/// diagnostics since it is unknown whether the functions containing such
1955/// diagnostics will be emitted. A list of potentially emitted functions and
1956/// variables that may potentially trigger emission of functions are also
1957/// recorded. DeferredDiagnosticsEmitter recursively visits used functions
1958/// by each function to emit deferred diagnostics.
1959///
1960/// During the visit, certain OpenMP directives or initializer of variables
1961/// with certain OpenMP attributes will cause subsequent visiting of any
1962/// functions enter a state which is called OpenMP device context in this
1963/// implementation. The state is exited when the directive or initializer is
1964/// exited. This state can change the emission states of subsequent uses
1965/// of functions.
1966///
1967/// Conceptually the functions or variables to be visited form a use graph
1968/// where the parent node uses the child node. At any point of the visit,
1969/// the tree nodes traversed from the tree root to the current node form a use
1970/// stack. The emission state of the current node depends on two factors:
1971/// 1. the emission state of the root node
1972/// 2. whether the current node is in OpenMP device context
1973/// If the function is decided to be emitted, its contained deferred diagnostics
1974/// are emitted, together with the information about the use stack.
1975///
1976class DeferredDiagnosticsEmitter
1977 : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
1978public:
1979 typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited;
1980
1981 // Whether the function is already in the current use-path.
1982 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath;
1983
1984 // The current use-path.
1985 llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath;
1986
1987 // Whether the visiting of the function has been done. Done[0] is for the
1988 // case not in OpenMP device context. Done[1] is for the case in OpenMP
1989 // device context. We need two sets because diagnostics emission may be
1990 // different depending on whether it is in OpenMP device context.
1991 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2];
1992
1993 // Functions that need their deferred diagnostics emitted. Collected
1994 // during the graph walk and emitted afterwards so that all callers
1995 // are known when producing call chain notes.
1996 llvm::SetVector<CanonicalDeclPtr<const FunctionDecl>> FnsToEmit;
1997
1998 // Emission state of the root node of the current use graph.
1999 bool ShouldEmitRootNode;
2000
2001 // Current OpenMP device context level. It is initialized to 0 and each
2002 // entering of device context increases it by 1 and each exit decreases
2003 // it by 1. Non-zero value indicates it is currently in device context.
2004 unsigned InOMPDeviceContext;
2005
2006 DeferredDiagnosticsEmitter(Sema &S)
2007 : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
2008
2009 bool shouldVisitDiscardedStmt() const { return false; }
2010
2011 void VisitOMPTargetDirective(OMPTargetDirective *Node) {
2012 ++InOMPDeviceContext;
2013 Inherited::VisitOMPTargetDirective(Node);
2014 --InOMPDeviceContext;
2015 }
2016
2017 void visitUsedDecl(SourceLocation Loc, Decl *D) {
2018 if (isa<VarDecl>(D))
2019 return;
2020 if (auto *FD = dyn_cast<FunctionDecl>(D))
2021 checkFunc(Loc, FD);
2022 else
2023 Inherited::visitUsedDecl(Loc, D);
2024 }
2025
2026 // Visitor member and parent dtors called by this dtor.
2027 void VisitCalledDestructors(CXXDestructorDecl *DD) {
2028 const CXXRecordDecl *RD = DD->getParent();
2029
2030 // Visit the dtors of all members
2031 for (const FieldDecl *FD : RD->fields()) {
2032 QualType FT = FD->getType();
2033 if (const auto *ClassDecl = FT->getAsCXXRecordDecl();
2034 ClassDecl &&
2035 (ClassDecl->isBeingDefined() || ClassDecl->isCompleteDefinition()))
2036 if (CXXDestructorDecl *MemberDtor = ClassDecl->getDestructor())
2037 asImpl().visitUsedDecl(MemberDtor->getLocation(), MemberDtor);
2038 }
2039
2040 // Also visit base class dtors
2041 for (const auto &Base : RD->bases()) {
2042 QualType BaseType = Base.getType();
2043 if (const auto *BaseDecl = BaseType->getAsCXXRecordDecl();
2044 BaseDecl &&
2045 (BaseDecl->isBeingDefined() || BaseDecl->isCompleteDefinition()))
2046 if (CXXDestructorDecl *BaseDtor = BaseDecl->getDestructor())
2047 asImpl().visitUsedDecl(BaseDtor->getLocation(), BaseDtor);
2048 }
2049 }
2050
2051 void VisitDeclStmt(DeclStmt *DS) {
2052 // Visit dtors called by variables that need destruction
2053 for (auto *D : DS->decls())
2054 if (auto *VD = dyn_cast<VarDecl>(D))
2055 if (VD->isThisDeclarationADefinition() &&
2056 VD->needsDestruction(S.Context)) {
2057 QualType VT = VD->getType();
2058 if (const auto *ClassDecl = VT->getAsCXXRecordDecl();
2059 ClassDecl && (ClassDecl->isBeingDefined() ||
2060 ClassDecl->isCompleteDefinition()))
2061 if (CXXDestructorDecl *Dtor = ClassDecl->getDestructor())
2062 asImpl().visitUsedDecl(Dtor->getLocation(), Dtor);
2063 }
2064
2065 Inherited::VisitDeclStmt(DS);
2066 }
2067 void checkVar(VarDecl *VD) {
2068 assert(VD->isFileVarDecl() &&
2069 "Should only check file-scope variables");
2070 if (auto *Init = VD->getInit()) {
2071 auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
2072 bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
2073 *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
2074 if (IsDev)
2075 ++InOMPDeviceContext;
2076 this->Visit(Init);
2077 if (IsDev)
2078 --InOMPDeviceContext;
2079 }
2080 }
2081
2082 void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
2083 auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];
2084 FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back();
2085 if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||
2086 S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD))
2087 return;
2088 // Finalize analysis of OpenMP-specific constructs.
2089 if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 &&
2090 (ShouldEmitRootNode || InOMPDeviceContext))
2091 S.OpenMP().finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
2092 if (Caller) {
2093 auto &Callers = S.CUDA().DeviceKnownEmittedFns[FD];
2094 CanonicalDeclPtr<const FunctionDecl> CanonCaller(Caller);
2095 if (llvm::none_of(Callers, [CanonCaller](const auto &C) {
2096 return C.FD == CanonCaller;
2097 }))
2098 Callers.push_back({Caller, Loc});
2099 }
2100 if (ShouldEmitRootNode || InOMPDeviceContext)
2101 FnsToEmit.insert(FD);
2102 // Do not revisit a function if the function body has been completely
2103 // visited before.
2104 if (!Done.insert(FD).second)
2105 return;
2106 InUsePath.insert(FD);
2107 UsePath.push_back(FD);
2108 const FunctionDecl *Definition = nullptr;
2109 auto *Body = FD->getBody(Definition);
2110 if (Body)
2111 this->Visit(Body);
2112
2113 if (auto *Ctor = dyn_cast_or_null<CXXConstructorDecl>(Definition)) {
2114 for (auto *Init : Ctor->inits())
2115 this->Visit(Init->getInit());
2116 }
2117
2118 if (CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(FD))
2119 asImpl().VisitCalledDestructors(Dtor);
2120 UsePath.pop_back();
2121 InUsePath.erase(FD);
2122 }
2123
2124 void checkRecordedDecl(Decl *D) {
2125 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2126 ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
2127 Sema::FunctionEmissionStatus::Emitted;
2128 checkFunc(SourceLocation(), FD);
2129 } else
2130 checkVar(cast<VarDecl>(D));
2131 }
2132
2133 void emitDeferredDiags(const FunctionDecl *FD) {
2134 auto It = S.DeviceDeferredDiags.find(FD);
2135 if (It == S.DeviceDeferredDiags.end())
2136 return;
2137 bool HasWarningOrError = false;
2138 for (PartialDiagnosticAt &PDAt : It->second) {
2139 if (S.Diags.hasFatalErrorOccurred())
2140 return;
2141 const SourceLocation &Loc = PDAt.first;
2142 const PartialDiagnostic &PD = PDAt.second;
2143 HasWarningOrError |=
2144 S.getDiagnostics().getDiagnosticLevel(PD.getDiagID(), Loc) >=
2146 {
2147 DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
2148 PD.Emit(Builder);
2149 }
2150 }
2151 if (HasWarningOrError)
2152 emitCallStackNotes(S, FD);
2153 }
2154
2155 void emitCollectedDiags() {
2156 for (const auto &FD : FnsToEmit)
2157 emitDeferredDiags(FD);
2158 }
2159};
2160} // namespace
2161
2163 if (ExternalSource)
2164 ExternalSource->ReadDeclsToCheckForDeferredDiags(
2166
2167 // For each implicit-H+D-explicit-inst function with deferred errors but no
2168 // organic device caller, drop the diagnostics and mark for a trap body.
2169 auto ClassifyImplicitHDExplicitInst = [&]() {
2170 if (!LangOpts.CUDAIsDevice)
2171 return;
2172 for (auto &Pair : DeviceDeferredDiags) {
2173 const FunctionDecl *FD = Pair.first;
2175 continue;
2176 if (CUDA().DeviceKnownEmittedFns.count(FD))
2177 continue;
2178 bool HasError =
2179 llvm::any_of(Pair.second, [&](const PartialDiagnosticAt &PDAt) {
2180 return getDiagnostics().getDiagnosticLevel(PDAt.second.getDiagID(),
2181 PDAt.first) >=
2182 DiagnosticsEngine::Error;
2183 });
2184 if (!HasError)
2185 continue;
2186 Pair.second.clear();
2187 Context.CUDADeviceInvalidFuncs.insert(FD->getCanonicalDecl());
2188 }
2189 };
2190
2191 if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||
2193 ClassifyImplicitHDExplicitInst();
2194 return;
2195 }
2196
2197 DeferredDiagnosticsEmitter DDE(*this);
2198 for (auto *D : DeclsToCheckForDeferredDiags)
2199 DDE.checkRecordedDecl(D);
2200 ClassifyImplicitHDExplicitInst();
2201 DDE.emitCollectedDiags();
2202}
2203
2204// In CUDA, there are some constructs which may appear in semantically-valid
2205// code, but trigger errors if we ever generate code for the function in which
2206// they appear. Essentially every construct you're not allowed to use on the
2207// device falls into this category, because you are allowed to use these
2208// constructs in a __host__ __device__ function, but only if that function is
2209// never codegen'ed on the device.
2210//
2211// To handle semantic checking for these constructs, we keep track of the set of
2212// functions we know will be emitted, either because we could tell a priori that
2213// they would be emitted, or because they were transitively called by a
2214// known-emitted function.
2215//
2216// We also keep a partial call graph of which not-known-emitted functions call
2217// which other not-known-emitted functions.
2218//
2219// When we see something which is illegal if the current function is emitted
2220// (usually by way of DiagIfDeviceCode, DiagIfHostCode, or
2221// CheckCall), we first check if the current function is known-emitted. If
2222// so, we immediately output the diagnostic.
2223//
2224// Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags
2225// until we discover that the function is known-emitted, at which point we take
2226// it out of this map and emit the diagnostic.
2227
2228Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc,
2229 unsigned DiagID,
2230 const FunctionDecl *Fn,
2231 Sema &S)
2232 : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
2233 ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
2234 switch (K) {
2235 case K_Nop:
2236 break;
2237 case K_Immediate:
2238 case K_ImmediateWithCallStack:
2239 ImmediateDiag.emplace(
2240 ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));
2241 break;
2242 case K_Deferred:
2243 assert(Fn && "Must have a function to attach the deferred diag to.");
2244 auto &Diags = S.DeviceDeferredDiags[Fn];
2245 PartialDiagId.emplace(Diags.size());
2246 Diags.emplace_back(Loc, S.PDiag(DiagID));
2247 break;
2248 }
2249}
2250
2251Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D)
2252 : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
2253 ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
2254 PartialDiagId(D.PartialDiagId) {
2255 // Clean the previous diagnostics.
2256 D.ShowCallStack = false;
2257 D.ImmediateDiag.reset();
2258 D.PartialDiagId.reset();
2259}
2260
2261Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
2262 if (ImmediateDiag) {
2263 // Emit our diagnostic and, if it was a warning or error, output a callstack
2264 // if Fn isn't a priori known-emitted.
2265 ImmediateDiag.reset(); // Emit the immediate diag.
2266
2267 if (ShowCallStack) {
2268 bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
2269 DiagID, Loc) >= DiagnosticsEngine::Warning;
2270 if (IsWarningOrError)
2271 emitCallStackNotes(S, Fn);
2272 }
2273 } else {
2274 assert((!PartialDiagId || ShowCallStack) &&
2275 "Must always show call stack for deferred diags.");
2276 }
2277}
2278
2279Sema::SemaDiagnosticBuilder
2280Sema::targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD) {
2281 FD = FD ? FD : getCurFunctionDecl();
2282 // OpenMPSimd is set only for -fopenmp-simd without -fopenmp. It has no device
2283 // compilation and ignores 'declare target', so there is nothing to defer for.
2284 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
2285 return LangOpts.OpenMPIsTargetDevice
2286 ? OpenMP().diagIfOpenMPDeviceCode(Loc, DiagID, FD)
2287 : OpenMP().diagIfOpenMPHostCode(Loc, DiagID, FD);
2288 if (getLangOpts().CUDA)
2289 return getLangOpts().CUDAIsDevice ? CUDA().DiagIfDeviceCode(Loc, DiagID)
2290 : CUDA().DiagIfHostCode(Loc, DiagID);
2291
2292 if (getLangOpts().SYCLIsDevice)
2293 return SYCL().DiagIfDeviceCode(Loc, DiagID);
2294
2296 FD, *this);
2297}
2298
2300 if (isUnevaluatedContext() || Ty.isNull())
2301 return;
2302
2303 // The original idea behind checkTypeSupport function is that unused
2304 // declarations can be replaced with an array of bytes of the same size during
2305 // codegen, such replacement doesn't seem to be possible for types without
2306 // constant byte size like zero length arrays. So, do a deep check for SYCL.
2307 if (D && LangOpts.SYCLIsDevice) {
2308 llvm::DenseSet<QualType> Visited;
2309 SYCL().deepTypeCheckForDevice(Loc, Visited, D);
2310 }
2311
2313
2314 // Memcpy operations for structs containing a member with unsupported type
2315 // are ok, though.
2316 if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
2317 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
2318 MD->isTrivial())
2319 return;
2320
2321 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
2322 if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())
2323 return;
2324 }
2325
2326 // Try to associate errors with the lexical context, if that is a function, or
2327 // the value declaration otherwise.
2328 const FunctionDecl *FD = isa<FunctionDecl>(C)
2330 : dyn_cast_or_null<FunctionDecl>(D);
2331
2332 auto CheckDeviceType = [&](QualType Ty) {
2333 if (Ty->isDependentType())
2334 return;
2335
2336 if (Ty->isBitIntType()) {
2337 if (!Context.getTargetInfo().hasBitIntType()) {
2338 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2339 if (D)
2340 PD << D;
2341 else
2342 PD << "expression";
2343 targetDiag(Loc, PD, FD)
2344 << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/
2345 << Ty << Context.getTargetInfo().getTriple().str();
2346 }
2347 return;
2348 }
2349
2350 // Check if we are dealing with two 'long double' but with different
2351 // semantics.
2352 bool LongDoubleMismatched = false;
2353 if (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128) {
2354 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(Ty);
2355 if ((&Sem != &llvm::APFloat::PPCDoubleDouble() &&
2356 !Context.getTargetInfo().hasFloat128Type()) ||
2357 (&Sem == &llvm::APFloat::PPCDoubleDouble() &&
2358 !Context.getTargetInfo().hasIbm128Type()))
2359 LongDoubleMismatched = true;
2360 }
2361
2362 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
2363 (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
2364 (Ty->isIbm128Type() && !Context.getTargetInfo().hasIbm128Type()) ||
2365 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
2366 !Context.getTargetInfo().hasInt128Type()) ||
2367 (Ty->isBFloat16Type() && !Context.getTargetInfo().hasBFloat16Type() &&
2368 !LangOpts.CUDAIsDevice) ||
2369 LongDoubleMismatched) {
2370 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2371 if (D)
2372 PD << D;
2373 else
2374 PD << "expression";
2375
2376 if (targetDiag(Loc, PD, FD)
2377 << true /*show bit size*/
2378 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
2379 << false /*return*/ << Context.getTargetInfo().getTriple().str()) {
2380 if (D)
2381 D->setInvalidDecl();
2382 }
2383 if (D)
2384 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2385 }
2386 };
2387
2388 auto CheckType = [&](QualType Ty, bool IsRetTy = false) {
2389 if (LangOpts.SYCLIsDevice ||
2390 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice) ||
2391 LangOpts.CUDAIsDevice)
2392 CheckDeviceType(Ty);
2393
2395 const TargetInfo &TI = Context.getTargetInfo();
2396 if (!TI.hasLongDoubleType() && UnqualTy == Context.LongDoubleTy) {
2397 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2398 if (D)
2399 PD << D;
2400 else
2401 PD << "expression";
2402
2403 if (Diag(Loc, PD) << false /*show bit size*/ << 0 << Ty
2404 << false /*return*/
2405 << TI.getTriple().str()) {
2406 if (D)
2407 D->setInvalidDecl();
2408 }
2409 if (D)
2410 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2411 }
2412
2413 bool IsDouble = UnqualTy == Context.DoubleTy;
2414 bool IsFloat = UnqualTy == Context.FloatTy;
2415 if (IsRetTy && !TI.hasFPReturn() && (IsDouble || IsFloat)) {
2416 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2417 if (D)
2418 PD << D;
2419 else
2420 PD << "expression";
2421
2422 if (Diag(Loc, PD) << false /*show bit size*/ << 0 << Ty << true /*return*/
2423 << TI.getTriple().str()) {
2424 if (D)
2425 D->setInvalidDecl();
2426 }
2427 if (D)
2428 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2429 }
2430
2431 if (TI.hasRISCVVTypes() && Ty->isRVVSizelessBuiltinType() && FD) {
2432 llvm::StringMap<bool> CallerFeatureMap;
2433 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
2434 RISCV().checkRVVTypeSupport(Ty, Loc, D, CallerFeatureMap);
2435 }
2436
2437 // Don't allow SVE types in functions without a SVE target.
2438 if (Ty->isSVESizelessBuiltinType() && FD) {
2439 llvm::StringMap<bool> CallerFeatureMap;
2440 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
2441 ARM().checkSVETypeSupport(Ty, Loc, FD, CallerFeatureMap);
2442 }
2443
2444 if (TI.hasAMDGPUTypes())
2445 AMDGPU().checkAMDGPUTypeSupport(Ty, Loc);
2446
2447 if (auto *VT = Ty->getAs<VectorType>();
2448 VT && FD &&
2449 (VT->getVectorKind() == VectorKind::SveFixedLengthData ||
2450 VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) &&
2451 (LangOpts.VScaleMin != LangOpts.VScaleStreamingMin ||
2452 LangOpts.VScaleMax != LangOpts.VScaleStreamingMax)) {
2453 if (IsArmStreamingFunction(FD, /*IncludeLocallyStreaming=*/true)) {
2454 Diag(Loc, diag::err_sve_fixed_vector_in_streaming_function)
2455 << Ty << /*Streaming*/ 0;
2456 } else if (const auto *FTy = FD->getType()->getAs<FunctionProtoType>()) {
2457 if (FTy->getAArch64SMEAttributes() &
2459 Diag(Loc, diag::err_sve_fixed_vector_in_streaming_function)
2460 << Ty << /*StreamingCompatible*/ 1;
2461 }
2462 }
2463 }
2464 };
2465
2466 CheckType(Ty);
2467 if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
2468 for (const auto &ParamTy : FPTy->param_types())
2469 CheckType(ParamTy);
2470 CheckType(FPTy->getReturnType(), /*IsRetTy=*/true);
2471 }
2472 if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty))
2473 CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true);
2474}
2475
2476bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
2477 SourceLocation loc = locref;
2478 if (!loc.isMacroID()) return false;
2479
2480 // There's no good way right now to look at the intermediate
2481 // expansions, so just jump to the expansion location.
2482 loc = getSourceManager().getExpansionLoc(loc);
2483
2484 // If that's written with the name, stop here.
2485 SmallString<16> buffer;
2486 if (getPreprocessor().getSpelling(loc, buffer) == name) {
2487 locref = loc;
2488 return true;
2489 }
2490 return false;
2491}
2492
2494
2495 if (!Ctx)
2496 return nullptr;
2497
2498 Ctx = Ctx->getPrimaryContext();
2499 for (Scope *S = getCurScope(); S; S = S->getParent()) {
2500 // Ignore scopes that cannot have declarations. This is important for
2501 // out-of-line definitions of static class members.
2502 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
2503 if (DeclContext *Entity = S->getEntity())
2504 if (Ctx == Entity->getPrimaryContext())
2505 return S;
2506 }
2507
2508 return nullptr;
2509}
2510
2511/// Enter a new function scope
2513 if (FunctionScopes.empty() && CachedFunctionScope) {
2514 // Use CachedFunctionScope to avoid allocating memory when possible.
2515 CachedFunctionScope->Clear();
2516 FunctionScopes.push_back(CachedFunctionScope.release());
2517 } else {
2519 }
2520 if (LangOpts.OpenMP)
2521 OpenMP().pushOpenMPFunctionRegion();
2522}
2523
2526 BlockScope, Block));
2528}
2529
2532 FunctionScopes.push_back(LSI);
2534 return LSI;
2535}
2536
2538 if (LambdaScopeInfo *const LSI = getCurLambda()) {
2539 LSI->AutoTemplateParameterDepth = Depth;
2540 return;
2541 }
2542 llvm_unreachable(
2543 "Remove assertion if intentionally called in a non-lambda context.");
2544}
2545
2546// Check that the type of the VarDecl has an accessible copy constructor and
2547// resolve its destructor's exception specification.
2548// This also performs initialization of block variables when they are moved
2549// to the heap. It uses the same rules as applicable for implicit moves
2550// according to the C++ standard in effect ([class.copy.elision]p3).
2551static void checkEscapingByref(VarDecl *VD, Sema &S) {
2552 QualType T = VD->getType();
2555 SourceLocation Loc = VD->getLocation();
2556 Expr *VarRef =
2557 new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
2559 auto IE = InitializedEntity::InitializeBlock(Loc, T);
2560 if (S.getLangOpts().CPlusPlus23) {
2561 auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr,
2564 } else {
2567 VarRef);
2568 }
2569
2570 if (!Result.isInvalid()) {
2572 Expr *Init = Result.getAs<Expr>();
2574 }
2575
2576 // The destructor's exception specification is needed when IRGen generates
2577 // block copy/destroy functions. Resolve it here.
2578 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2579 if (CXXDestructorDecl *DD = RD->getDestructor()) {
2580 auto *FPT = DD->getType()->castAs<FunctionProtoType>();
2581 S.ResolveExceptionSpec(Loc, FPT);
2582 }
2583}
2584
2585static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
2586 // Set the EscapingByref flag of __block variables captured by
2587 // escaping blocks.
2588 for (const BlockDecl *BD : FSI.Blocks) {
2589 for (const BlockDecl::Capture &BC : BD->captures()) {
2590 VarDecl *VD = BC.getVariable();
2591 if (VD->hasAttr<BlocksAttr>()) {
2592 // Nothing to do if this is a __block variable captured by a
2593 // non-escaping block.
2594 if (BD->doesNotEscape())
2595 continue;
2596 VD->setEscapingByref();
2597 }
2598 // Check whether the captured variable is or contains an object of
2599 // non-trivial C union type.
2600 QualType CapType = BC.getVariable()->getType();
2603 S.checkNonTrivialCUnion(BC.getVariable()->getType(),
2604 BD->getCaretLocation(),
2607 }
2608 }
2609
2610 for (VarDecl *VD : FSI.ByrefBlockVars) {
2611 // __block variables might require us to capture a copy-initializer.
2612 if (!VD->isEscapingByref())
2613 continue;
2614 // It's currently invalid to ever have a __block variable with an
2615 // array type; should we diagnose that here?
2616 // Regardless, we don't want to ignore array nesting when
2617 // constructing this copy.
2618 if (VD->getType()->isStructureOrClassType())
2619 checkEscapingByref(VD, S);
2620 }
2621}
2622
2625 QualType BlockType) {
2626 assert(!FunctionScopes.empty() && "mismatched push/pop!");
2627
2628 markEscapingByrefs(*FunctionScopes.back(), *this);
2629
2632
2633 if (LangOpts.OpenMP)
2634 OpenMP().popOpenMPFunctionRegion(Scope.get());
2635
2636 // Issue any analysis-based warnings.
2637 if (WP && D) {
2638 inferNoReturnAttr(*this, D);
2639 AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
2640 } else
2641 for (const auto &PUD : Scope->PossiblyUnreachableDiags)
2642 Diag(PUD.Loc, PUD.PD);
2643
2644 return Scope;
2645}
2646
2649 if (!Scope->isPlainFunction())
2650 Self->CapturingFunctionScopes--;
2651 // Stash the function scope for later reuse if it's for a normal function.
2652 if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
2653 Self->CachedFunctionScope.reset(Scope);
2654 else
2655 delete Scope;
2656}
2657
2658void Sema::PushCompoundScope(bool IsStmtExpr) {
2659 getCurFunction()->CompoundScopes.push_back(
2660 CompoundScopeInfo(IsStmtExpr, getCurFPFeatures()));
2661}
2662
2664 FunctionScopeInfo *CurFunction = getCurFunction();
2665 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
2666
2667 CurFunction->CompoundScopes.pop_back();
2668}
2669
2671 return getCurFunction()->hasUnrecoverableErrorOccurred();
2672}
2673
2675 if (!FunctionScopes.empty())
2676 FunctionScopes.back()->setHasBranchIntoScope();
2677}
2678
2680 if (!FunctionScopes.empty())
2681 FunctionScopes.back()->setHasBranchProtectedScope();
2682}
2683
2685 if (!FunctionScopes.empty())
2686 FunctionScopes.back()->setHasIndirectGoto();
2687}
2688
2690 if (!FunctionScopes.empty())
2691 FunctionScopes.back()->setHasMustTail();
2692}
2693
2695 if (FunctionScopes.empty())
2696 return nullptr;
2697
2698 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
2699 if (CurBSI && CurBSI->TheDecl &&
2700 !CurBSI->TheDecl->Encloses(CurContext)) {
2701 // We have switched contexts due to template instantiation.
2702 assert(!CodeSynthesisContexts.empty());
2703 return nullptr;
2704 }
2705
2706 return CurBSI;
2707}
2708
2710 if (FunctionScopes.empty())
2711 return nullptr;
2712
2713 for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
2715 continue;
2716 return FunctionScopes[e];
2717 }
2718 return nullptr;
2719}
2720
2722 for (auto *Scope : llvm::reverse(FunctionScopes)) {
2723 if (auto *CSI = dyn_cast<CapturingScopeInfo>(Scope)) {
2724 auto *LSI = dyn_cast<LambdaScopeInfo>(CSI);
2725 if (LSI && LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&
2726 LSI->AfterParameterList) {
2727 // We have switched contexts due to template instantiation.
2728 // FIXME: We should swap out the FunctionScopes during code synthesis
2729 // so that we don't need to check for this.
2730 assert(!CodeSynthesisContexts.empty());
2731 return nullptr;
2732 }
2733 return CSI;
2734 }
2735 }
2736 return nullptr;
2737}
2738
2739LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
2740 if (FunctionScopes.empty())
2741 return nullptr;
2742
2743 auto I = FunctionScopes.rbegin();
2744 if (IgnoreNonLambdaCapturingScope) {
2745 auto E = FunctionScopes.rend();
2746 while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
2747 ++I;
2748 if (I == E)
2749 return nullptr;
2750 }
2751 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
2752 if (CurLSI && CurLSI->Lambda && CurLSI->CallOperator &&
2753 !CurLSI->Lambda->Encloses(CurContext) && CurLSI->AfterParameterList) {
2754 // We have switched contexts due to template instantiation.
2755 assert(!CodeSynthesisContexts.empty());
2756 return nullptr;
2757 }
2758
2759 return CurLSI;
2760}
2761
2762// We have a generic lambda if we parsed auto parameters, or we have
2763// an associated template parameter list.
2765 if (LambdaScopeInfo *LSI = getCurLambda()) {
2766 return (LSI->TemplateParams.size() ||
2767 LSI->GLTemplateParameterList) ? LSI : nullptr;
2768 }
2769 return nullptr;
2770}
2771
2773 if (!LangOpts.CommentOpts.RetainCommentsFromSystemHeaders &&
2774 SourceMgr.isInSystemHeader(Loc))
2775 return false;
2776
2777 if (LangOpts.CommentOpts.ParseAllComments)
2778 return true;
2779
2780 if (LangOpts.CommentOpts.RetainComments)
2781 return true;
2782
2783 // When building a PCH the comments are serialized into the AST file
2784 // so downstream consumers like clangd) can retrieve documentation, and the
2785 // incremental/REPL front end may query them interactively.
2786 if (TUKind != TU_Complete)
2787 return true;
2788
2789 if (PP.isCodeCompletionEnabled())
2790 return true;
2791
2792 // Keep the comment if a documentation warning is enabled at its location.
2793 // Checking the location, rather than globally, is what makes a warning
2794 // turned on by a `#pragma clang diagnostic` take effect.
2795 return areDocumentationDiagsEnabled(Loc);
2796}
2797
2798bool Sema::computeDocumentationDiagsAt(SourceLocation Loc) const {
2799 return !Diags.areAllIgnored("documentation", Loc) ||
2800 !Diags.areAllIgnored("documentation-pedantic", Loc);
2801}
2802
2804 DocDiagsStateKey = nullptr;
2805 DocDiagsExactComputed = 0;
2806}
2807
2809 // Under a suppression mapping the severity depends on the file path rather
2810 // than the diagnostic state, so there is nothing stable to key a cache on.
2811 if (Loc.isInvalid() || Diags.hasDiagSuppressionMapping())
2812 return computeDocumentationDiagsAt(Loc);
2813
2814 const void *StateKey = Diags.getDiagStateKeyForLoc(Loc);
2815 if (StateKey != DocDiagsStateKey) {
2816 DocDiagsStateKey = StateKey;
2817 {
2818 // Answer as if Loc were not in a system header.
2819 ForceSystemWarningsRAII ShowSystemWarnings(Diags);
2820 DocDiagsEnabledIgnoringSystem = computeDocumentationDiagsAt(Loc);
2821 }
2822 DocDiagsExactComputed = 0;
2823 }
2824
2825 if (!DocDiagsEnabledIgnoringSystem)
2826 return false;
2827
2828 DiagStateSystemClass SysClass = Diags.getDiagStateSystemClassForLoc(Loc);
2829 if (SysClass == DiagStateSystemClass::UserCode)
2830 return true;
2831
2832 const unsigned Bit = 1u << static_cast<unsigned>(SysClass);
2833 if (!(DocDiagsExactComputed & Bit)) {
2834 DocDiagsExactComputed |= Bit;
2835 if (computeDocumentationDiagsAt(Loc))
2836 DocDiagsExactEnabled |= Bit;
2837 else
2838 DocDiagsExactEnabled &= ~Bit;
2839 }
2840 return (DocDiagsExactEnabled & Bit) != 0;
2841}
2842
2844 if (!shouldRetainCommentsInAST(Comment.getBegin()))
2845 return;
2846 RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
2848 SourceRange MagicMarkerRange(Comment.getBegin(),
2849 Comment.getBegin().getLocWithOffset(3));
2850 StringRef MagicMarkerText;
2851 switch (RC.getKind()) {
2853 MagicMarkerText = "///<";
2854 break;
2856 MagicMarkerText = "/**<";
2857 break;
2859 // FIXME: are there other scenarios that could produce an invalid
2860 // raw comment here?
2861 Diag(Comment.getBegin(), diag::warn_splice_in_doxygen_comment);
2862 return;
2863 default:
2864 llvm_unreachable("if this is an almost Doxygen comment, "
2865 "it should be ordinary");
2866 }
2867 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
2868 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
2869 }
2870 Context.addComment(RC);
2871}
2872
2873// Pin this vtable to this file.
2875char ExternalSemaSource::ID;
2876
2879
2883
2885 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
2886
2888 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
2889
2890bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
2892 ZeroArgCallReturnTy = QualType();
2893 OverloadSet.clear();
2894
2895 const OverloadExpr *Overloads = nullptr;
2896 bool IsMemExpr = false;
2897 if (E.getType() == Context.OverloadTy) {
2899
2900 // Ignore overloads that are pointer-to-member constants.
2902 return false;
2903
2904 Overloads = FR.Expression;
2905 } else if (E.getType() == Context.BoundMemberTy) {
2906 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
2907 IsMemExpr = true;
2908 }
2909
2910 bool Ambiguous = false;
2911 bool IsMV = false;
2912
2913 if (Overloads) {
2914 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
2915 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
2916 OverloadSet.addDecl(*it);
2917
2918 // Check whether the function is a non-template, non-member which takes no
2919 // arguments.
2920 if (IsMemExpr)
2921 continue;
2922 if (const FunctionDecl *OverloadDecl
2923 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
2924 if (OverloadDecl->getMinRequiredArguments() == 0) {
2925 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
2926 (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
2927 OverloadDecl->isCPUSpecificMultiVersion()))) {
2928 ZeroArgCallReturnTy = QualType();
2929 Ambiguous = true;
2930 } else {
2931 ZeroArgCallReturnTy = OverloadDecl->getReturnType();
2932 IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
2933 OverloadDecl->isCPUSpecificMultiVersion();
2934 }
2935 }
2936 }
2937 }
2938
2939 // If it's not a member, use better machinery to try to resolve the call
2940 if (!IsMemExpr)
2941 return !ZeroArgCallReturnTy.isNull();
2942 }
2943
2944 // Attempt to call the member with no arguments - this will correctly handle
2945 // member templates with defaults/deduction of template arguments, overloads
2946 // with default arguments, etc.
2947 if (IsMemExpr && !E.isTypeDependent()) {
2948 Sema::TentativeAnalysisScope Trap(*this);
2950 SourceLocation());
2951 if (R.isUsable()) {
2952 ZeroArgCallReturnTy = R.get()->getType();
2953 return true;
2954 }
2955 return false;
2956 }
2957
2958 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
2959 if (const auto *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
2960 if (Fun->getMinRequiredArguments() == 0)
2961 ZeroArgCallReturnTy = Fun->getReturnType();
2962 return true;
2963 }
2964 }
2965
2966 // We don't have an expression that's convenient to get a FunctionDecl from,
2967 // but we can at least check if the type is "function of 0 arguments".
2968 QualType ExprTy = E.getType();
2969 const FunctionType *FunTy = nullptr;
2970 QualType PointeeTy = ExprTy->getPointeeType();
2971 if (!PointeeTy.isNull())
2972 FunTy = PointeeTy->getAs<FunctionType>();
2973 if (!FunTy)
2974 FunTy = ExprTy->getAs<FunctionType>();
2975
2976 if (const auto *FPT = dyn_cast_if_present<FunctionProtoType>(FunTy)) {
2977 if (FPT->getNumParams() == 0)
2978 ZeroArgCallReturnTy = FunTy->getReturnType();
2979 return true;
2980 }
2981 return false;
2982}
2983
2984/// Give notes for a set of overloads.
2985///
2986/// A companion to tryExprAsCall. In cases when the name that the programmer
2987/// wrote was an overloaded function, we may be able to make some guesses about
2988/// plausible overloads based on their return types; such guesses can be handed
2989/// off to this method to be emitted as notes.
2990///
2991/// \param Overloads - The overloads to note.
2992/// \param FinalNoteLoc - If we've suppressed printing some overloads due to
2993/// -fshow-overloads=best, this is the location to attach to the note about too
2994/// many candidates. Typically this will be the location of the original
2995/// ill-formed expression.
2996static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
2997 const SourceLocation FinalNoteLoc) {
2998 unsigned ShownOverloads = 0;
2999 unsigned SuppressedOverloads = 0;
3000 for (UnresolvedSetImpl::iterator It = Overloads.begin(),
3001 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
3002 if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) {
3003 ++SuppressedOverloads;
3004 continue;
3005 }
3006
3007 const NamedDecl *Fn = (*It)->getUnderlyingDecl();
3008 // Don't print overloads for non-default multiversioned functions.
3009 if (const auto *FD = Fn->getAsFunction()) {
3010 if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
3011 !FD->getAttr<TargetAttr>()->isDefaultVersion())
3012 continue;
3013 if (FD->isMultiVersion() && FD->hasAttr<TargetVersionAttr>() &&
3014 !FD->getAttr<TargetVersionAttr>()->isDefaultVersion())
3015 continue;
3016 }
3017 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
3018 ++ShownOverloads;
3019 }
3020
3021 S.Diags.overloadCandidatesShown(ShownOverloads);
3022
3023 if (SuppressedOverloads)
3024 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
3025 << SuppressedOverloads;
3026}
3027
3029 const UnresolvedSetImpl &Overloads,
3030 bool (*IsPlausibleResult)(QualType)) {
3031 if (!IsPlausibleResult)
3032 return noteOverloads(S, Overloads, Loc);
3033
3034 UnresolvedSet<2> PlausibleOverloads;
3035 for (OverloadExpr::decls_iterator It = Overloads.begin(),
3036 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
3037 const auto *OverloadDecl = cast<FunctionDecl>(*It);
3038 QualType OverloadResultTy = OverloadDecl->getReturnType();
3039 if (IsPlausibleResult(OverloadResultTy))
3040 PlausibleOverloads.addDecl(It.getDecl());
3041 }
3042 noteOverloads(S, PlausibleOverloads, Loc);
3043}
3044
3045/// Determine whether the given expression can be called by just
3046/// putting parentheses after it. Notably, expressions with unary
3047/// operators can't be because the unary operator will start parsing
3048/// outside the call.
3049static bool IsCallableWithAppend(const Expr *E) {
3050 E = E->IgnoreImplicit();
3051 return (!isa<CStyleCastExpr>(E) &&
3052 !isa<UnaryOperator>(E) &&
3053 !isa<BinaryOperator>(E) &&
3055}
3056
3058 if (const auto *UO = dyn_cast<UnaryOperator>(E))
3059 E = UO->getSubExpr();
3060
3061 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3062 if (ULE->getNumDecls() == 0)
3063 return false;
3064
3065 const NamedDecl *ND = *ULE->decls_begin();
3066 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3068 }
3069 return false;
3070}
3071
3073 bool ForceComplain,
3074 bool (*IsPlausibleResult)(QualType)) {
3075 SourceLocation Loc = E.get()->getExprLoc();
3076 SourceRange Range = E.get()->getSourceRange();
3077 UnresolvedSet<4> Overloads;
3078
3079 // If this is a SFINAE context, don't try anything that might trigger ADL
3080 // prematurely.
3081 if (!isSFINAEContext()) {
3082 QualType ZeroArgCallTy;
3083 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
3084 !ZeroArgCallTy.isNull() &&
3085 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
3086 // At this point, we know E is potentially callable with 0
3087 // arguments and that it returns something of a reasonable type,
3088 // so we can emit a fixit and carry on pretending that E was
3089 // actually a CallExpr.
3090 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
3092 Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
3093 << (IsCallableWithAppend(E.get())
3094 ? FixItHint::CreateInsertion(ParenInsertionLoc,
3095 "()")
3096 : FixItHint());
3097 if (!IsMV)
3098 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
3099
3100 // FIXME: Try this before emitting the fixit, and suppress diagnostics
3101 // while doing so.
3102 E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), {},
3103 Range.getEnd().getLocWithOffset(1));
3104 return true;
3105 }
3106 }
3107 if (!ForceComplain) return false;
3108
3110 Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
3111 if (!IsMV)
3112 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
3113 E = ExprError();
3114 return true;
3115}
3116
3118 if (!Ident_super)
3119 Ident_super = &Context.Idents.get("super");
3120 return Ident_super;
3121}
3122
3125 unsigned OpenMPCaptureLevel) {
3126 auto *CSI = new CapturedRegionScopeInfo(
3127 getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
3128 (getLangOpts().OpenMP && K == CR_OpenMP)
3129 ? OpenMP().getOpenMPNestingLevel()
3130 : 0,
3131 OpenMPCaptureLevel);
3132 CSI->ReturnType = Context.VoidTy;
3133 FunctionScopes.push_back(CSI);
3135}
3136
3138 if (FunctionScopes.empty())
3139 return nullptr;
3140
3141 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
3142}
3143
3144const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
3148
3150 : S(S), OldFPFeaturesState(S.CurFPFeatures),
3151 OldOverrides(S.FpPragmaStack.CurrentValue),
3152 OldEvalMethod(S.PP.getCurrentFPEvalMethod()),
3153 OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {}
3154
3156 S.CurFPFeatures = OldFPFeaturesState;
3157 S.FpPragmaStack.CurrentValue = OldOverrides;
3158 S.PP.setCurrentFPEvalMethod(OldFPPragmaLocation, OldEvalMethod);
3159}
3160
3162 assert(D.getCXXScopeSpec().isSet() &&
3163 "can only be called for qualified names");
3164
3165 auto LR = LookupResult(*this, D.getIdentifier(), D.getBeginLoc(),
3169 if (!DC)
3170 return false;
3171
3172 LookupQualifiedName(LR, DC);
3173 bool Result = llvm::all_of(LR, [](Decl *Dcl) {
3174 if (NamedDecl *ND = dyn_cast<NamedDecl>(Dcl)) {
3175 ND = ND->getUnderlyingDecl();
3176 return isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
3177 isa<UsingDecl>(ND);
3178 }
3179 return false;
3180 });
3181 return Result;
3182}
3183
3186
3187 auto *A = AnnotateAttr::Create(Context, Annot, Args.data(), Args.size(), CI);
3189 CI, MutableArrayRef<Expr *>(A->args_begin(), A->args_end()))) {
3190 return nullptr;
3191 }
3192 return A;
3193}
3194
3196 // Make sure that there is a string literal as the annotation's first
3197 // argument.
3198 StringRef Str;
3199 if (!checkStringLiteralArgumentAttr(AL, 0, Str))
3200 return nullptr;
3201
3203 Args.reserve(AL.getNumArgs() - 1);
3204 for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
3205 assert(!AL.isArgIdent(Idx));
3206 Args.push_back(AL.getArgAsExpr(Idx));
3207 }
3208
3209 return CreateAnnotationAttr(AL, Str, Args);
3210}
Defines the clang::ASTContext interface.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Next
The next token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to AVR.
This file declares semantic analysis functions specific to BPF.
This file declares semantic analysis for CUDA constructs.
This file declares facilities that support code completion.
This file declares semantic analysis for DirectX constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to M68k.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to MSP430.
This file declares semantic analysis functions specific to NVPTX.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis for expressions involving.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SPIRV constructs.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to Swift.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
static void checkEscapingByref(VarDecl *VD, Sema &S)
Definition Sema.cpp:2551
static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E)
Definition Sema.cpp:3057
llvm::DenseMap< const CXXRecordDecl *, bool > RecordCompleteMap
Definition Sema.cpp:1119
static bool IsCallableWithAppend(const Expr *E)
Determine whether the given expression can be called by just putting parentheses after it.
Definition Sema.cpp:3049
static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD, RecordCompleteMap &MNCComplete)
Returns true, if all methods and nested classes of the given CXXRecordDecl are defined in this transl...
Definition Sema.cpp:1126
static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, const SourceLocation FinalNoteLoc)
Give notes for a set of overloads.
Definition Sema.cpp:2996
static bool isFunctionOrVarDeclExternC(const NamedDecl *ND)
Definition Sema.cpp:959
static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S)
Definition Sema.cpp:2585
static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D)
Used to prune the decls of Sema's UnusedFileScopedDecls vector.
Definition Sema.cpp:898
static void emitCallStackNotes(Sema &S, const FunctionDecl *FD)
Definition Sema.cpp:1926
static void notePlausibleOverloads(Sema &S, SourceLocation Loc, const UnresolvedSetImpl &Overloads, bool(*IsPlausibleResult)(QualType))
Definition Sema.cpp:3028
static void checkUndefinedButUsed(Sema &S)
checkUndefinedButUsed - Check for undefined objects with internal linkage or that are inline.
Definition Sema.cpp:1037
static bool IsRecordFullyDefined(const CXXRecordDecl *RD, RecordCompleteMap &RecordsComplete, RecordCompleteMap &MNCComplete)
Returns true, if the given CXXRecordDecl is fully defined in this translation unit,...
Definition Sema.cpp:1168
Defines the SourceManager interface.
Allows QualTypes to be sorted and hence used in maps and sets.
TypePropertyCache< Private > Cache
Definition Type.cpp:5092
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition ASTConsumer.h:35
virtual ASTMutationListener * GetASTMutationListener()
If the consumer is interested in entities getting modified after their initial creation,...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
Attr - This represents one attribute.
Definition Attr.h:47
A class which contains all the information about a particular captured value.
Definition Decl.h:4862
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4856
ArrayRef< Capture > captures() const
Definition Decl.h:4983
SourceLocation getCaretLocation() const
Definition Decl.h:4929
bool doesNotEscape() const
Definition Decl.h:5007
Represents a C++ destructor within a class.
Definition DeclCXX.h:2915
Represents a C++26 expansion statement declaration.
CXXFieldCollector - Used to keep track of CXXFieldDecls during parsing of C++ classes.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
An iterator over the friend declarations of a class.
Definition DeclFriend.h:123
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
friend_iterator friend_begin() const
Definition DeclFriend.h:175
base_class_range bases()
Definition DeclCXX.h:609
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2129
friend_iterator friend_end() const
Definition DeclFriend.h:179
bool isSet() const
Deprecated.
Definition DeclSpec.h:202
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition Decl.h:5128
ImplicitParamDecl * getContextParam() const
Retrieve the parameter containing captured variables.
Definition Decl.h:5186
static const char * getCastKindName(CastKind CK)
Definition Expr.cpp:1987
Abstract interface for a consumer of code-completion information.
The information about the darwin SDK that was used during this compilation.
decl_iterator - Iterates through the declarations stored within this context.
Definition DeclBase.h:2362
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2108
decl_iterator decls_end() const
Definition DeclBase.h:2407
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_iterator decls_begin() const
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:894
decl_range decls()
Definition Stmt.h:1690
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:582
void addAttr(Attr *A)
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition DeclBase.cpp:604
bool isInvalidDecl() const
Definition DeclBase.h:597
SourceLocation getLocation() const
Definition DeclBase.h:448
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:579
bool hasAttr() const
Definition DeclBase.h:586
The name of a declaration.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:782
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1996
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2182
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2161
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2430
A little helper class used to produce diagnostics.
static SFINAEResponse getDiagnosticSFINAEResponse(unsigned DiagID)
Determines whether the given built-in diagnostic ID is for an error that is suppressed if it occurs d...
@ SFINAE_SubstitutionFailure
The diagnostic should not be reported, but it should cause template argument deduction to fail.
@ SFINAE_Suppress
The diagnostic should be suppressed entirely.
@ SFINAE_AccessControl
The diagnostic is an access-control diagnostic, which will be substitution failures in some contexts ...
@ SFINAE_Report
The diagnostic should be reported.
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
const SourceLocation & getLocation() const
unsigned getID() const
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:818
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:803
Level
The level of the diagnostic, after it has been through mapping.
Definition Diagnostic.h:246
bool hasFatalErrorOccurred() const
Definition Diagnostic.h:920
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4192
This represents one expression.
Definition Expr.h:114
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3117
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool isPRValue() const
Definition Expr.h:287
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
An abstract interface that should be implemented by external AST sources that also provide informatio...
virtual void updateOutOfDateSelector(Selector Sel)
Load the contents of the global method pool for a given selector if necessary.
Definition Sema.cpp:2878
virtual void ReadMethodPool(Selector Sel)
Load the contents of the global method pool for a given selector.
Definition Sema.cpp:2877
virtual void ReadUndefinedButUsed(llvm::MapVector< NamedDecl *, SourceLocation > &Undefined)
Load the set of used but not defined functions or variables with internal linkage,...
Definition Sema.cpp:2884
~ExternalSemaSource() override
Definition Sema.cpp:2874
virtual void ReadKnownNamespaces(SmallVectorImpl< NamespaceDecl * > &Namespaces)
Load the set of namespaces that are known to the external source, which will be used during typo corr...
Definition Sema.cpp:2880
virtual void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &)
Definition Sema.cpp:2887
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3341
StringRef getName() const
The name of this FileEntry.
Definition FileEntry.h:61
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
RAII class that temporarily forces warnings in system headers and system macros to be shown on a Diag...
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:46
Represents a function declaration or definition.
Definition Decl.h:2082
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2862
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3284
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3779
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3820
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2709
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3775
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2554
const ASTTemplateArgumentListInfo * getTemplateSpecializationArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
Definition Decl.cpp:4414
static FunctionEffectsRef get(QualType QT)
Extract the effects from a Type if it is a function, block, or member function pointer,...
Definition TypeBase.h:9536
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
Declaration of a template function.
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
QualType getReturnType() const
Definition TypeBase.h:5084
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3922
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2109
Represents a C array with an unspecified size.
Definition TypeBase.h:4007
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type)
@ CMK_HeaderUnit
Compiling a module header unit.
@ CMK_ModuleInterface
Compiling a C++ modules interface unit.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
static std::optional< Token > findNextToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeComments=false)
Finds the token that comes right after the given location.
Definition Lexer.cpp:1381
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition Lexer.cpp:882
Represents the results of name lookup.
Definition Lookup.h:147
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:40
Abstract interface for a module loader.
bool resolveExports(Module *Mod, bool Complain)
Resolve all of the unresolved exports in the given module.
bool resolveConflicts(Module *Mod, bool Complain)
Resolve all of the unresolved conflicts in the given module.
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Describes a module or submodule.
Definition Module.h:340
bool isNamedModuleInterfaceHasInit() const
Definition Module.h:905
bool isInterfaceOrPartition() const
Definition Module.h:892
llvm::iterator_range< submodule_iterator > submodules()
Definition Module.h:1079
@ PrivateModuleFragment
This is the private module fragment within some C++ module.
Definition Module.h:376
@ ExplicitGlobalModuleFragment
This is the explicit Global Module Fragment of a modular TU.
Definition Module.h:373
llvm::SmallVector< ModuleRef, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition Module.h:661
static const unsigned NumNSNumberLiteralMethods
Definition NSAPI.h:191
This represents a decl that may have a name.
Definition Decl.h:276
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition Decl.h:431
NamedDecl * getMostRecentDecl()
Definition Decl.h:503
bool isExternallyVisible() const
Definition Decl.h:435
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
void addSupport(const llvm::StringMap< bool > &FeaturesMap, const LangOptions &Opts)
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3143
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3204
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3234
decls_iterator decls_begin() const
Definition ExprCXX.h:3236
decls_iterator decls_end() const
Definition ExprCXX.h:3239
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition PPCallbacks.h:37
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition ParsedAttr.h:371
bool isArgIdent(unsigned Arg) const
Definition ParsedAttr.h:385
Expr * getArgAsExpr(unsigned Arg) const
Definition ParsedAttr.h:383
void Emit(const DiagnosticBuilder &DB) const
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition Type.h:85
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition Type.h:79
QualType getCanonicalType() const
Definition TypeBase.h:8630
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8651
bool hasUnsupportedSplice(const SourceManager &SourceMgr) const
@ RCK_OrdinaryC
Any normal C comment.
@ RCK_Invalid
Invalid comment.
@ RCK_OrdinaryBCPL
Any normal BCPL comments.
bool isAlmostTrailingComment() const LLVM_READONLY
Returns true if it is a probable typo:
CommentKind getKind() const LLVM_READONLY
Represents a struct/union/class.
Definition Decl.h:4506
field_range fields() const
Definition Decl.h:4709
bool hasUninitializedExplicitInitFields() const
Definition Decl.h:4632
Represents the body of a requires-expression.
Definition DeclCXX.h:2122
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
Smart pointer class that efficiently represents Objective-C method names.
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
@ K_Immediate
Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
Definition SemaBase.h:117
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaBase(Sema &S)
Definition SemaBase.cpp:7
const LangOptions & getLangOpts() const
Definition SemaBase.cpp:11
DiagnosticsEngine & getDiagnostics() const
Definition SemaBase.cpp:10
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
static bool isImplicitHDExplicitInstantiation(const FunctionDecl *FD)
Null-tolerant wrapper for FunctionDecl::isImplicitHDExplicitInstantiation.
Definition SemaCUDA.cpp:406
llvm::DenseMap< CanonicalDeclPtr< const FunctionDecl >, llvm::SmallVector< FunctionDeclAndLoc, 1 > > DeviceKnownEmittedFns
An inverse call graph, mapping known-emitted functions to their known-emitted callers (plus the locat...
Definition SemaCUDA.h:83
An abstract interface that should be implemented by clients that read ASTs and then require further s...
void ActOnEndOfTranslationUnit(TranslationUnitDecl *TU)
ObjCMethodDecl * NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]
The Objective-C NSNumber methods used to create NSNumber literals.
Definition SemaObjC.h:606
void DiagnoseUseOfUnimplementedSelectors()
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
void ActOnEndOfTranslationUnit(TranslationUnitDecl *TU)
void DiagnoseUnterminatedOpenMPDeclareTarget()
Report unterminated 'omp declare target' or 'omp begin declare target' at the end of a compilation un...
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1411
sema::DelayedDiagnosticPool * getCurrentPool() const
Returns the current delayed-diagnostics pool.
Definition Sema.h:1426
Custom deleter to allow FunctionScopeInfos to be kept alive for a short time after they've been poppe...
Definition Sema.h:1068
void operator()(sema::FunctionScopeInfo *Scope) const
Definition Sema.cpp:2648
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12708
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12752
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:862
SemaAMDGPU & AMDGPU()
Definition Sema.h:1473
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition Sema.h:3743
bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs (unless they are value dependent ...
Definition SemaAttr.cpp:546
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13871
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13322
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2721
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1164
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition Sema.h:10261
void LoadExternalWeakUndeclaredIdentifiers()
Load weak undeclared identifiers from the external source.
Definition Sema.cpp:1099
bool isExternalWithNoLinkageType(const ValueDecl *VD) const
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can't b...
Definition Sema.cpp:967
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition Sema.cpp:2890
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9529
const Decl * PragmaAttributeCurrentTargetDecl
The declaration that is currently receiving an attribute from the pragma attribute stack.
Definition Sema.h:2174
OpaquePtr< QualType > TypeTy
Definition Sema.h:1324
void addImplicitTypedef(StringRef Name, QualType T)
Definition Sema.cpp:371
void PrintContextStack()
Definition Sema.h:13950
SemaOpenMP & OpenMP()
Definition Sema.h:1558
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition Sema.h:6502
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition Sema.h:1285
void emitAndClearUnusedLocalTypedefWarnings()
Definition Sema.cpp:1213
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition Sema.h:6673
bool areDocumentationDiagsEnabled(SourceLocation Loc)
Returns true if any of the documentation warnings is enabled at Loc.
Definition Sema.cpp:2808
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition Sema.h:1274
SemaCUDA & CUDA()
Definition Sema.h:1498
void Initialize()
Perform initialization that occurs after the parser has been initialized but before it parses anythin...
Definition Sema.cpp:377
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1267
void clearDocumentationDiagsCache()
Discard the areDocumentationDiagsEnabled() cache, for when a #pragma clang diagnostic has changed dia...
Definition Sema.cpp:2803
Preprocessor & getPreprocessor() const
Definition Sema.h:933
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2493
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2105
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2099
void setFunctionHasBranchIntoScope()
Definition Sema.cpp:2674
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
void ActOnComment(SourceRange Comment)
Definition Sema.cpp:2843
void ActOnEndOfTranslationUnit()
ActOnEndOfTranslationUnit - This is called at the very end of the translation unit when EOF is reache...
Definition Sema.cpp:1294
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2106
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
void ActOnTranslationUnitScope(Scope *S)
Scope actions.
Definition Sema.cpp:173
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
SemaSYCL & SYCL()
Definition Sema.h:1583
IdentifierInfo * getSuperIdentifier() const
Definition Sema.cpp:3117
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1779
void DiagnosePrecisionLossInComplexDivision()
bool DisableTypoCorrection
Tracks whether we are in a context where typo correction is disabled.
Definition Sema.h:9473
ASTContext & Context
Definition Sema.h:1331
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition Sema.cpp:698
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
Definition Sema.h:2393
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:931
SemaObjC & ObjC()
Definition Sema.h:1543
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain=false, bool(*IsPlausibleResult)(QualType)=nullptr)
Try to recover by turning the given expression into a call.
Definition Sema.cpp:3072
SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags
Diagnostics that are emitted only if we discover that the given function must be codegen'ed.
Definition Sema.h:1468
void CheckDelayedMemberExceptionSpecs()
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
ClassTemplateDecl * StdCoroutineTraitsCache
The C++ "std::coroutine_traits" template, which is defined in <coroutine_traits>
Definition Sema.h:3313
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2102
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used.
Definition Sema.h:3733
ASTContext & getASTContext() const
Definition Sema.h:934
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1076
void addExternalSource(IntrusiveRefCntPtr< ExternalSemaSource > E)
Registers an external source.
Definition Sema.cpp:673
ClassTemplateDecl * StdInitializerList
The C++ "std::initializer_list" template, which is defined in <initializer_list>.
Definition Sema.h:6699
SmallVector< std::pair< FunctionDecl *, FunctionDecl * >, 2 > DelayedEquivalentExceptionSpecChecks
All the function redeclarations seen during a class definition that had their exception spec checks d...
Definition Sema.h:6783
PragmaStack< StringLiteral * > ConstSegStack
Definition Sema.h:2098
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:774
InitSegPragmaState CurInitSeg
Definition Sema.h:2145
unsigned TyposCorrected
The number of typos corrected by CorrectTypo.
Definition Sema.h:9476
static const unsigned MaxAlignmentExponent
The maximum alignment, same as in llvm::Value.
Definition Sema.h:1257
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1235
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1784
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition Sema.cpp:2764
void setFunctionHasIndirectGoto()
Definition Sema.cpp:2684
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1798
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2512
FPOptions & getCurFPFeatures()
Definition Sema.h:929
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8498
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:278
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
sema::LambdaScopeInfo * PushLambdaScope()
Definition Sema.cpp:2530
void PopCompoundScope()
Definition Sema.cpp:2663
api_notes::APINotesManager APINotes
Definition Sema.h:1335
const LangOptions & getLangOpts() const
Definition Sema.h:927
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2624
SemaOpenACC & OpenACC()
Definition Sema.h:1548
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
ASTConsumer & getASTConsumer() const
Definition Sema.h:935
void * OpaqueParser
Definition Sema.h:1377
Preprocessor & PP
Definition Sema.h:1330
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
threadSafety::BeforeSet * ThreadSafetyDeclCache
Definition Sema.h:1372
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition Sema.cpp:2299
const LangOptions & LangOpts
Definition Sema.h:1329
std::unique_ptr< sema::FunctionScopeInfo > CachedFunctionScope
Definition Sema.h:1263
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2739
static const uint64_t MaximumAlignment
Definition Sema.h:1258
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6677
SemaHLSL & HLSL()
Definition Sema.h:1508
bool CollectStats
Flag indicating whether or not to collect detailed statistics.
Definition Sema.h:1261
void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind)
Definition Sema.cpp:1234
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
bool shouldRetainCommentsInAST(SourceLocation Loc)
Returns true if a comment at Loc should be retained in the AST (some consumer such as -Wdocumentation...
Definition Sema.cpp:2772
IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName, unsigned Index)
Invent a new identifier for parameters of abbreviated templates.
Definition Sema.cpp:140
SemaRISCV & RISCV()
Definition Sema.h:1573
SmallVector< PendingImplicitInstantiation, 1 > LateParsedInstantiations
Queue of implicit template instantiations that cannot be performed eagerly.
Definition Sema.h:14293
void performFunctionEffectAnalysis(TranslationUnitDecl *TU)
PragmaStack< AlignPackInfo > AlignPackStack
Definition Sema.h:2087
SmallVector< std::pair< const CXXMethodDecl *, const CXXMethodDecl * >, 2 > DelayedOverridingExceptionSpecChecks
All the overriding functions seen during a class definition that had their exception spec checks dela...
Definition Sema.h:6775
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2097
DeclContext * getCurLexicalContext() const
Definition Sema.h:1168
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1791
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition Sema.cpp:881
llvm::SmallSetVector< Decl *, 4 > DeclsToCheckForDeferredDiags
Function or variable declarations to be checked for whether the deferred diagnostics should be emitte...
Definition Sema.h:4948
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1366
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2658
bool isDeclaratorFunctionLike(Declarator &D)
Determine whether.
Definition Sema.cpp:3161
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:7137
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2476
llvm::MapVector< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3716
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:10057
static bool isCast(CheckedConversionKind CCK)
Definition Sema.h:2680
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2694
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1471
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
ClassTemplateDecl * StdTypeIdentity
The C++ "std::type_identity" template, which is defined in <type_traits>.
Definition Sema.h:6703
SemaOpenCL & OpenCL()
Definition Sema.h:1553
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8365
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1758
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
bool GlobalNewDeleteDeclared
A flag to remember whether the implicit forms of operator new and delete have been declared.
Definition Sema.h:8557
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition Sema.h:3747
bool MSStructPragmaOn
Definition Sema.h:1861
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition Sema.h:13902
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14241
SourceManager & getSourceManager() const
Definition Sema.h:932
bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason)
makeUnavailableInSystemHeader - There is an error in the current context.
Definition Sema.cpp:648
void getUndefinedButUsed(SmallVectorImpl< std::pair< NamedDecl *, SourceLocation > > &Undefined)
Obtain a sorted list of functions that are undefined but ODR-used.
Definition Sema.cpp:984
void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn when implicitly changing function effects.
Definition Sema.cpp:714
void PerformPendingInstantiations(bool LocalOnly=false, bool AtEndOfTU=true)
Performs template instantiation for all implicit template instantiations we have seen until this poin...
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value, bool SupressSimplerImplicitMoves=false)
Perform the initialization of a potentially-movable value, which is the result of return value.
CanThrowResult canThrow(const Stmt *E)
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
@ NTCUK_Destruct
Definition Sema.h:4261
@ NTCUK_Copy
Definition Sema.h:4262
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition Sema.cpp:2524
PragmaStack< MSVtorDispMode > VtorDispStack
Whether to insert vtordisps prior to virtual bases in the Microsoft C++ ABI.
Definition Sema.h:2086
void * VisContext
VisContext - Manages the stack for #pragma GCC visibility.
Definition Sema.h:2151
bool isSFINAEContext() const
Definition Sema.h:13962
UnsignedOrNone ArgPackSubstIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition Sema.h:13918
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel=0)
Definition Sema.cpp:3123
void emitDeferredDiags()
Definition Sema.cpp:2162
void setFunctionHasMustTail()
Definition Sema.cpp:2689
RecordDecl * CXXTypeInfoDecl
The C++ "type_info" declaration, which is defined in <typeinfo>.
Definition Sema.h:8553
void CheckCompleteVariableDeclaration(VarDecl *VD)
void setFunctionHasBranchProtectedScope()
Definition Sema.cpp:2679
RedeclarationKind forRedeclarationInCurContext() const
void ActOnStartOfTranslationUnit()
This is called before the very first declaration in the translation unit is parsed.
Definition Sema.cpp:1228
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition Sema.h:1609
ASTConsumer & Consumer
Definition Sema.h:1332
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4835
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1371
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1905
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14289
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
Definition Sema.cpp:110
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6915
std::pair< SourceLocation, bool > DeleteExprLoc
Definition Sema.h:983
void RecordParsingTemplateParameterDepth(unsigned Depth)
This is used to inform Sema what the current TemplateParameterDepth is during Parsing.
Definition Sema.cpp:2537
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1290
void DiagnoseUnterminatedPragmaAttribute()
void FreeVisContext()
FreeVisContext - Deallocate and null out VisContext.
LateTemplateParserCB * LateTemplateParser
Definition Sema.h:1376
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
llvm::MapVector< FieldDecl *, DeleteLocs > DeleteExprs
Delete-expressions to be analyzed at the end of translation unit.
Definition Sema.h:8564
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition Sema.h:3740
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
DarwinSDKInfo * getDarwinSDKInfoForAvailabilityChecking()
Definition Sema.cpp:124
const llvm::MapVector< FieldDecl *, DeleteLocs > & getMismatchingDeleteExpressions() const
Retrieves list of suspicious delete-expressions that will be checked at the end of translation unit.
Definition Sema.cpp:3145
llvm::SmallPtrSet< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3720
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8501
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
SourceManager & SourceMgr
Definition Sema.h:1334
DiagnosticsEngine & Diags
Definition Sema.h:1333
void DiagnoseUnterminatedPragmaAlignPack()
Definition SemaAttr.cpp:632
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:928
FPOptions CurFPFeatures
Definition Sema.h:1327
void LoadExternalExtnameUndeclaredIdentifiers()
Load pragma redefine_extname'd undeclared identifiers from the external source.
Definition Sema.cpp:1109
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2096
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Attr * CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef< Expr * > Args)
CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
Definition Sema.cpp:3184
bool isMainFileLoc(SourceLocation Loc) const
Determines whether the given source location is in the main file and we're in a context where we shou...
Definition Sema.cpp:976
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6711
void PrintStats() const
Print out statistics about the semantic analysis.
Definition Sema.cpp:688
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
Definition Sema.h:1859
llvm::BumpPtrAllocator BumpAlloc
Definition Sema.h:1276
SourceRange getRangeForNextToken(SourceLocation Loc, bool IncludeMacros, bool IncludeComments, std::optional< tok::TokenKind > ExpectedToken=std::nullopt)
Calls Lexer::findNextToken() to find the next token, and if the locations of both ends of the token c...
Definition Sema.cpp:89
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:643
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6501
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition Sema.h:3709
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2280
DeclarationName VAListTagName
VAListTagName - The declaration name corresponding to __va_list_tag.
Definition Sema.h:1390
void getSortedUnusedLocalTypedefNameCandidates(SmallVectorImpl< const TypedefNameDecl * > &Sorted) const
Store UnusedLocalTypedefNameCandidates in Sorted in a deterministic order.
Definition Sema.cpp:1200
void DiagnoseUnusedAPINotesSelectors()
Diagnose exact API notes selectors that were not matched by any declaration processed in this transla...
sema::FunctionScopeInfo * getEnclosingFunction() const
Definition Sema.cpp:2709
sema::CapturedRegionScopeInfo * getCurCapturedRegion()
Retrieve the current captured region, if any.
Definition Sema.cpp:3137
void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E)
Warn when implicitly casting 0 to nullptr.
Definition Sema.cpp:726
void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB)
Cause the built diagnostic to be emitted on the DiagosticsEngine.
Definition Sema.cpp:1804
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
IdentifierResolver IdResolver
Definition Sema.h:3632
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2670
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
SemaARM & ARM()
Definition Sema.h:1478
llvm::DenseSet< InstantiatingSpecializationsKey > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition Sema.h:13874
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:669
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13959
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
UIntTy getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it.
This class handles loading and caching of source files into memory.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
FileID getMainFileID() const
Returns the FileID of the main source file.
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include'd file otherwise it returns an invalid location.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void setEnd(SourceLocation e)
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3999
bool isUnion() const
Definition Decl.h:4109
Exposes information about the current target.
Definition TargetInfo.h:228
virtual bool hasLongDoubleType() const
Determine whether the long double type is supported on this target.
Definition TargetInfo.h:731
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool hasAMDGPUTypes() const
Returns whether or not the AMDGPU built-in types are available on this target.
virtual bool hasFPReturn() const
Determine whether return of a floating point value is supported on this target.
Definition TargetInfo.h:735
bool hasRISCVVTypes() const
Returns whether or not the RISC-V V built-in types are available on this target.
A container of type source information.
Definition TypeBase.h:8549
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isFloat16Type() const
Definition TypeBase.h:9213
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2795
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isFloat128Type() const
Definition TypeBase.h:9233
bool isBitIntType() const
Definition TypeBase.h:9090
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition Type.cpp:2582
bool isIbm128Type() const
Definition TypeBase.h:9237
bool isOverflowBehaviorType() const
Definition TypeBase.h:8986
bool isBFloat16Type() const
Definition TypeBase.h:9225
bool isStructureOrClassType() const
Definition Type.cpp:839
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2533
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2816
Linkage getLinkage() const
Determine the linkage of this type.
Definition Type.cpp:5200
@ STK_FloatingComplex
Definition TypeBase.h:2845
@ STK_ObjCObjectPointer
Definition TypeBase.h:2839
@ STK_IntegralComplex
Definition TypeBase.h:2844
@ STK_MemberPointer
Definition TypeBase.h:2840
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
bool isNullPtrType() const
Definition TypeBase.h:9241
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5325
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3743
A set of unresolved declarations.
UnresolvedSetIterator iterator
void addDecl(NamedDecl *D)
A set of unresolved declarations.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
void setType(QualType newType)
Definition Decl.h:726
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2802
void setEscapingByref()
Definition Decl.h:1644
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isInternalLinkageFileVar() const
Returns true if this is a file-scope variable with internal linkage.
Definition Decl.h:1224
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2368
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition Decl.h:1367
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2843
const Expr * getInit() const
Definition Decl.h:1393
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition Decl.cpp:2431
@ TLS_None
Not a TLS variable.
Definition Decl.h:954
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition Decl.cpp:2347
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1320
StorageDuration getStorageDuration() const
Get the storage duration of this variable, per C++ [basic.stc].
Definition Decl.h:1252
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition Decl.cpp:2703
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1383
Declaration of a variable template.
Represents a GCC generic vector type.
Definition TypeBase.h:4398
Retains information about a block that is currently being parsed.
Definition ScopeInfo.h:791
Retains information about a captured region.
Definition ScopeInfo.h:817
Contains information about the compound statement currently being parsed.
Definition ScopeInfo.h:67
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
SmallVector< CompoundScopeInfo, 4 > CompoundScopes
The stack of currently active compound statement scopes in the function.
Definition ScopeInfo.h:233
llvm::SmallPtrSet< const BlockDecl *, 1 > Blocks
The set of blocks that are introduced in this function.
Definition ScopeInfo.h:236
llvm::TinyPtrVector< VarDecl * > ByrefBlockVars
The set of __block variables that are introduced in this function.
Definition ScopeInfo.h:239
void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID) override
Callback invoked whenever a source file is entered or exited.
Definition Sema.cpp:191
void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace, diag::Severity Mapping, StringRef Str) override
Callback invoked when a #pragma gcc diagnostic directive is read.
Definition Sema.cpp:228
Provides information about an attempted template argument deduction, whose success or failure was des...
void addSuppressedDiagnostic(SourceLocation Loc, PartialDiagnostic PD)
Add a new diagnostic to the set of diagnostics.
void addSFINAEDiagnostic(SourceLocation Loc, PartialDiagnostic PD)
Set the diagnostic which caused the SFINAE failure.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Flavor
Flavors of diagnostics we can emit.
@ WarningOrError
A diagnostic that indicates a problem or potential problem.
@ Remark
A diagnostic that indicates normal progress through compilation.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing),...
void threadSafetyCleanup(BeforeSet *Cache)
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:196
@ CPlusPlus
@ CPlusPlus11
@ ExpectedVariableOrFunction
@ Nullable
Values of this type can be null.
Definition Specifiers.h:354
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:352
DiagStateSystemClass
Whether a source location is in a system header and/or a system macro.
Definition Diagnostic.h:227
Expected< std::optional< DarwinSDKInfo > > parseDarwinSDKInfo(llvm::vfs::FileSystem &VFS, StringRef SDKRootPath)
Parse the SDK information from the SDKSettings.json file.
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:629
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
CapturedRegionKind
The different kinds of captured statement.
@ CR_OpenMP
@ SC_Register
Definition Specifiers.h:261
@ SC_Static
Definition Specifiers.h:256
void inferNoReturnAttr(Sema &S, Decl *D)
@ Undefined
Keep undefined.
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:344
@ SD_Static
Static storage duration.
Definition Specifiers.h:345
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TUFragmentKind
Definition Sema.h:480
@ Private
The private module fragment, between 'module :private;' and the end of the translation unit.
Definition Sema.h:489
@ Global
The global module fragment, between 'module;' and a module-declaration.
Definition Sema.h:482
@ Normal
A normal translation unit fragment.
Definition Sema.h:486
ExprResult ExprError()
Definition Ownership.h:265
@ OverloadSet
The name was classified as an overload set, and an expression representing that overload set has been...
Definition Sema.h:574
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
TranslationUnitKind
Describes the kind of translation unit being processed.
@ TU_Complete
The translation unit is a complete translation unit.
@ TU_ClangModule
The translation unit is a clang module.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
ComparisonCategoryType
An enumeration representing the different comparison categories types.
void FormatASTNodeDiagnosticArgument(DiagnosticsEngine::ArgumentKind Kind, intptr_t Val, StringRef Modifier, StringRef Argument, ArrayRef< DiagnosticsEngine::ArgumentValue > PrevArgs, SmallVectorImpl< char > &Output, void *Cookie, ArrayRef< intptr_t > QualTypeVals)
DiagnosticsEngine argument formatting function for diagnostics that involve AST nodes.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:148
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
bool isExternalFormalLinkage(Linkage L)
Definition Linkage.h:117
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4252
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4255
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6157
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
Definition Decl.cpp:6214
bool isExternallyVisible(Linkage L)
Definition Linkage.h:90
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
CheckedConversionKind
The kind of conversion being performed.
Definition Sema.h:431
OptionalUnsigned< NullabilityKind > NullabilityKindOrNone
Definition Specifiers.h:366
unsigned long uint64_t
#define false
Definition stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Describes how types, statements, expressions, and declarations should be printed.
unsigned Bool
Whether we can use 'bool' rather than '_Bool' (even if the language doesn't actually have 'bool',...
unsigned EntireContentsOfLargeArray
Whether to print the entire array initializers, especially on non-type template parameters,...
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13458
Information from a C++ pragma export, for a symbol that we haven't seen the declaration for yet.
Definition Sema.h:2388