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