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