xref: /freebsd/contrib/llvm-project/clang/lib/Sema/Sema.cpp (revision 5f757f3ff9144b609b3c433dfd370cc6bdc191ad)
10b57cec5SDimitry Andric //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the actions class which performs semantic analysis and
100b57cec5SDimitry Andric // builds an AST out of a parse stream.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
145ffd83dbSDimitry Andric #include "UsedDeclVisitor.h"
150b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
160b57cec5SDimitry Andric #include "clang/AST/ASTDiagnostic.h"
17d409305fSDimitry Andric #include "clang/AST/Decl.h"
180b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
190b57cec5SDimitry Andric #include "clang/AST/DeclFriend.h"
200b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
210b57cec5SDimitry Andric #include "clang/AST/Expr.h"
220b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h"
230b57cec5SDimitry Andric #include "clang/AST/PrettyDeclStackTrace.h"
240b57cec5SDimitry Andric #include "clang/AST/StmtCXX.h"
25fe6060f1SDimitry Andric #include "clang/Basic/DarwinSDKInfo.h"
260b57cec5SDimitry Andric #include "clang/Basic/DiagnosticOptions.h"
270b57cec5SDimitry Andric #include "clang/Basic/PartialDiagnostic.h"
285ffd83dbSDimitry Andric #include "clang/Basic/SourceManager.h"
29a7dea167SDimitry Andric #include "clang/Basic/Stack.h"
300b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
310b57cec5SDimitry Andric #include "clang/Lex/HeaderSearch.h"
32fe6060f1SDimitry Andric #include "clang/Lex/HeaderSearchOptions.h"
330b57cec5SDimitry Andric #include "clang/Lex/Preprocessor.h"
340b57cec5SDimitry Andric #include "clang/Sema/CXXFieldCollector.h"
350b57cec5SDimitry Andric #include "clang/Sema/DelayedDiagnostic.h"
3606c3fb27SDimitry Andric #include "clang/Sema/EnterExpressionEvaluationContext.h"
370b57cec5SDimitry Andric #include "clang/Sema/ExternalSemaSource.h"
380b57cec5SDimitry Andric #include "clang/Sema/Initialization.h"
390b57cec5SDimitry Andric #include "clang/Sema/MultiplexExternalSemaSource.h"
400b57cec5SDimitry Andric #include "clang/Sema/ObjCMethodList.h"
41972a253aSDimitry Andric #include "clang/Sema/RISCVIntrinsicManager.h"
420b57cec5SDimitry Andric #include "clang/Sema/Scope.h"
430b57cec5SDimitry Andric #include "clang/Sema/ScopeInfo.h"
440b57cec5SDimitry Andric #include "clang/Sema/SemaConsumer.h"
450b57cec5SDimitry Andric #include "clang/Sema/SemaInternal.h"
460b57cec5SDimitry Andric #include "clang/Sema/TemplateDeduction.h"
470b57cec5SDimitry Andric #include "clang/Sema/TemplateInstCallback.h"
48a7dea167SDimitry Andric #include "clang/Sema/TypoCorrection.h"
490b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
50bdd1243dSDimitry Andric #include "llvm/ADT/STLExtras.h"
51e8d8bef9SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
520b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h"
53bdd1243dSDimitry Andric #include <optional>
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric using namespace clang;
560b57cec5SDimitry Andric using namespace sema;
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
590b57cec5SDimitry Andric   return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
600b57cec5SDimitry Andric }
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
630b57cec5SDimitry Andric 
64fe6060f1SDimitry Andric DarwinSDKInfo *
65fe6060f1SDimitry Andric Sema::getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
66fe6060f1SDimitry Andric                                               StringRef Platform) {
6704eeddc0SDimitry Andric   auto *SDKInfo = getDarwinSDKInfoForAvailabilityChecking();
6804eeddc0SDimitry Andric   if (!SDKInfo && !WarnedDarwinSDKInfoMissing) {
6904eeddc0SDimitry Andric     Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking)
7004eeddc0SDimitry Andric         << Platform;
7104eeddc0SDimitry Andric     WarnedDarwinSDKInfoMissing = true;
7204eeddc0SDimitry Andric   }
7304eeddc0SDimitry Andric   return SDKInfo;
7404eeddc0SDimitry Andric }
7504eeddc0SDimitry Andric 
7604eeddc0SDimitry Andric DarwinSDKInfo *Sema::getDarwinSDKInfoForAvailabilityChecking() {
77fe6060f1SDimitry Andric   if (CachedDarwinSDKInfo)
78fe6060f1SDimitry Andric     return CachedDarwinSDKInfo->get();
79fe6060f1SDimitry Andric   auto SDKInfo = parseDarwinSDKInfo(
80fe6060f1SDimitry Andric       PP.getFileManager().getVirtualFileSystem(),
81fe6060f1SDimitry Andric       PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot);
82fe6060f1SDimitry Andric   if (SDKInfo && *SDKInfo) {
83fe6060f1SDimitry Andric     CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo));
84fe6060f1SDimitry Andric     return CachedDarwinSDKInfo->get();
85fe6060f1SDimitry Andric   }
86fe6060f1SDimitry Andric   if (!SDKInfo)
87fe6060f1SDimitry Andric     llvm::consumeError(SDKInfo.takeError());
88fe6060f1SDimitry Andric   CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>();
89fe6060f1SDimitry Andric   return nullptr;
90fe6060f1SDimitry Andric }
91fe6060f1SDimitry Andric 
9255e4f9d5SDimitry Andric IdentifierInfo *
9355e4f9d5SDimitry Andric Sema::InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
9455e4f9d5SDimitry Andric                                                  unsigned int Index) {
9555e4f9d5SDimitry Andric   std::string InventedName;
9655e4f9d5SDimitry Andric   llvm::raw_string_ostream OS(InventedName);
9755e4f9d5SDimitry Andric 
9855e4f9d5SDimitry Andric   if (!ParamName)
9955e4f9d5SDimitry Andric     OS << "auto:" << Index + 1;
10055e4f9d5SDimitry Andric   else
10155e4f9d5SDimitry Andric     OS << ParamName->getName() << ":auto";
10255e4f9d5SDimitry Andric 
10355e4f9d5SDimitry Andric   OS.flush();
10455e4f9d5SDimitry Andric   return &Context.Idents.get(OS.str());
10555e4f9d5SDimitry Andric }
10655e4f9d5SDimitry Andric 
1070b57cec5SDimitry Andric PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
1080b57cec5SDimitry Andric                                        const Preprocessor &PP) {
1090b57cec5SDimitry Andric   PrintingPolicy Policy = Context.getPrintingPolicy();
1100b57cec5SDimitry Andric   // In diagnostics, we print _Bool as bool if the latter is defined as the
1110b57cec5SDimitry Andric   // former.
1120b57cec5SDimitry Andric   Policy.Bool = Context.getLangOpts().Bool;
1130b57cec5SDimitry Andric   if (!Policy.Bool) {
1140b57cec5SDimitry Andric     if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
1150b57cec5SDimitry Andric       Policy.Bool = BoolMacro->isObjectLike() &&
1160b57cec5SDimitry Andric                     BoolMacro->getNumTokens() == 1 &&
1170b57cec5SDimitry Andric                     BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
1180b57cec5SDimitry Andric     }
1190b57cec5SDimitry Andric   }
1200b57cec5SDimitry Andric 
12181ad6265SDimitry Andric   // Shorten the data output if needed
12281ad6265SDimitry Andric   Policy.EntireContentsOfLargeArray = false;
12381ad6265SDimitry Andric 
1240b57cec5SDimitry Andric   return Policy;
1250b57cec5SDimitry Andric }
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric void Sema::ActOnTranslationUnitScope(Scope *S) {
1280b57cec5SDimitry Andric   TUScope = S;
1290b57cec5SDimitry Andric   PushDeclContext(S, Context.getTranslationUnitDecl());
1300b57cec5SDimitry Andric }
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric namespace clang {
1330b57cec5SDimitry Andric namespace sema {
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric class SemaPPCallbacks : public PPCallbacks {
1360b57cec5SDimitry Andric   Sema *S = nullptr;
1370b57cec5SDimitry Andric   llvm::SmallVector<SourceLocation, 8> IncludeStack;
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric public:
1400b57cec5SDimitry Andric   void set(Sema &S) { this->S = &S; }
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric   void reset() { S = nullptr; }
1430b57cec5SDimitry Andric 
144972a253aSDimitry Andric   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
1450b57cec5SDimitry Andric                    SrcMgr::CharacteristicKind FileType,
1460b57cec5SDimitry Andric                    FileID PrevFID) override {
1470b57cec5SDimitry Andric     if (!S)
1480b57cec5SDimitry Andric       return;
1490b57cec5SDimitry Andric     switch (Reason) {
1500b57cec5SDimitry Andric     case EnterFile: {
1510b57cec5SDimitry Andric       SourceManager &SM = S->getSourceManager();
1520b57cec5SDimitry Andric       SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
1530b57cec5SDimitry Andric       if (IncludeLoc.isValid()) {
1540b57cec5SDimitry Andric         if (llvm::timeTraceProfilerEnabled()) {
155*5f757f3fSDimitry Andric           OptionalFileEntryRef FE = SM.getFileEntryRefForID(SM.getFileID(Loc));
156*5f757f3fSDimitry Andric           llvm::timeTraceProfilerBegin("Source", FE ? FE->getName()
157*5f757f3fSDimitry Andric                                                     : StringRef("<unknown>"));
1580b57cec5SDimitry Andric         }
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric         IncludeStack.push_back(IncludeLoc);
161e8d8bef9SDimitry Andric         S->DiagnoseNonDefaultPragmaAlignPack(
162e8d8bef9SDimitry Andric             Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude,
163e8d8bef9SDimitry Andric             IncludeLoc);
1640b57cec5SDimitry Andric       }
1650b57cec5SDimitry Andric       break;
1660b57cec5SDimitry Andric     }
1670b57cec5SDimitry Andric     case ExitFile:
1680b57cec5SDimitry Andric       if (!IncludeStack.empty()) {
1690b57cec5SDimitry Andric         if (llvm::timeTraceProfilerEnabled())
1700b57cec5SDimitry Andric           llvm::timeTraceProfilerEnd();
1710b57cec5SDimitry Andric 
172e8d8bef9SDimitry Andric         S->DiagnoseNonDefaultPragmaAlignPack(
173e8d8bef9SDimitry Andric             Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit,
1740b57cec5SDimitry Andric             IncludeStack.pop_back_val());
1750b57cec5SDimitry Andric       }
1760b57cec5SDimitry Andric       break;
1770b57cec5SDimitry Andric     default:
1780b57cec5SDimitry Andric       break;
1790b57cec5SDimitry Andric     }
1800b57cec5SDimitry Andric   }
1810b57cec5SDimitry Andric };
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric } // end namespace sema
1840b57cec5SDimitry Andric } // end namespace clang
1850b57cec5SDimitry Andric 
1865ffd83dbSDimitry Andric const unsigned Sema::MaxAlignmentExponent;
187349cc55cSDimitry Andric const uint64_t Sema::MaximumAlignment;
1885ffd83dbSDimitry Andric 
1890b57cec5SDimitry Andric Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1900b57cec5SDimitry Andric            TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
191bdd1243dSDimitry Andric     : ExternalSource(nullptr), CurFPFeatures(pp.getLangOpts()),
192bdd1243dSDimitry Andric       LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer),
193bdd1243dSDimitry Andric       Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
194*5f757f3fSDimitry Andric       APINotes(SourceMgr, LangOpts), CollectStats(false),
195*5f757f3fSDimitry Andric       CodeCompleter(CodeCompleter), CurContext(nullptr),
1960b57cec5SDimitry Andric       OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
1970b57cec5SDimitry Andric       MSPointerToMemberRepresentationMethod(
1980b57cec5SDimitry Andric           LangOpts.getMSPointerToMemberRepresentationMethod()),
199e8d8bef9SDimitry Andric       VtorDispStack(LangOpts.getVtorDispMode()),
200e8d8bef9SDimitry Andric       AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)),
2010b57cec5SDimitry Andric       DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
202bdd1243dSDimitry Andric       CodeSegStack(nullptr), StrictGuardStackCheckStack(false),
203bdd1243dSDimitry Andric       FpPragmaStack(FPOptionsOverride()), CurInitSeg(nullptr),
204bdd1243dSDimitry Andric       VisContext(nullptr), PragmaAttributeCurrentTargetDecl(nullptr),
20504eeddc0SDimitry Andric       IsBuildingRecoveryCallExpr(false), LateTemplateParser(nullptr),
2060b57cec5SDimitry Andric       LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
20706c3fb27SDimitry Andric       StdInitializerList(nullptr), StdCoroutineTraitsCache(nullptr),
20806c3fb27SDimitry Andric       CXXTypeInfoDecl(nullptr), StdSourceLocationImplDecl(nullptr),
20981ad6265SDimitry Andric       NSNumberDecl(nullptr), NSValueDecl(nullptr), NSStringDecl(nullptr),
21081ad6265SDimitry Andric       StringWithUTF8StringMethod(nullptr),
2110b57cec5SDimitry Andric       ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
2120b57cec5SDimitry Andric       ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
2130b57cec5SDimitry Andric       DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
2140b57cec5SDimitry Andric       TUKind(TUKind), NumSFINAEErrors(0),
2150b57cec5SDimitry Andric       FullyCheckedComparisonCategories(
2160b57cec5SDimitry Andric           static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
21755e4f9d5SDimitry Andric       SatisfactionCache(Context), AccessCheckingSFINAE(false),
21855e4f9d5SDimitry Andric       InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
21955e4f9d5SDimitry Andric       ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
22055e4f9d5SDimitry Andric       DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
2210b57cec5SDimitry Andric       ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
22206c3fb27SDimitry Andric       CurScope(nullptr), Ident_super(nullptr) {
223fe6060f1SDimitry Andric   assert(pp.TUKind == TUKind);
2240b57cec5SDimitry Andric   TUScope = nullptr;
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric   LoadedExternalKnownNamespaces = false;
2270b57cec5SDimitry Andric   for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
2280b57cec5SDimitry Andric     NSNumberLiteralMethods[I] = nullptr;
2290b57cec5SDimitry Andric 
2300b57cec5SDimitry Andric   if (getLangOpts().ObjC)
2310b57cec5SDimitry Andric     NSAPIObj.reset(new NSAPI(Context));
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus)
2340b57cec5SDimitry Andric     FieldCollector.reset(new CXXFieldCollector());
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric   // Tell diagnostics how to render things from the AST library.
2370b57cec5SDimitry Andric   Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
2380b57cec5SDimitry Andric 
23981ad6265SDimitry Andric   // This evaluation context exists to ensure that there's always at least one
24081ad6265SDimitry Andric   // valid evaluation context available. It is never removed from the
24181ad6265SDimitry Andric   // evaluation stack.
2420b57cec5SDimitry Andric   ExprEvalContexts.emplace_back(
2430b57cec5SDimitry Andric       ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
2440b57cec5SDimitry Andric       nullptr, ExpressionEvaluationContextRecord::EK_Other);
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric   // Initialization of data sharing attributes stack for OpenMP
2470b57cec5SDimitry Andric   InitDataSharingAttributesStack();
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric   std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
250a7dea167SDimitry Andric       std::make_unique<sema::SemaPPCallbacks>();
2510b57cec5SDimitry Andric   SemaPPCallbackHandler = Callbacks.get();
2520b57cec5SDimitry Andric   PP.addPPCallbacks(std::move(Callbacks));
2530b57cec5SDimitry Andric   SemaPPCallbackHandler->set(*this);
25481ad6265SDimitry Andric 
25581ad6265SDimitry Andric   CurFPFeatures.setFPEvalMethod(PP.getCurrentFPEvalMethod());
2560b57cec5SDimitry Andric }
2570b57cec5SDimitry Andric 
258480093f4SDimitry Andric // Anchor Sema's type info to this TU.
259480093f4SDimitry Andric void Sema::anchor() {}
260480093f4SDimitry Andric 
2610b57cec5SDimitry Andric void Sema::addImplicitTypedef(StringRef Name, QualType T) {
2620b57cec5SDimitry Andric   DeclarationName DN = &Context.Idents.get(Name);
2630b57cec5SDimitry Andric   if (IdResolver.begin(DN) == IdResolver.end())
2640b57cec5SDimitry Andric     PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
2650b57cec5SDimitry Andric }
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric void Sema::Initialize() {
2680b57cec5SDimitry Andric   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
2690b57cec5SDimitry Andric     SC->InitializeSema(*this);
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric   // Tell the external Sema source about this Sema object.
2720b57cec5SDimitry Andric   if (ExternalSemaSource *ExternalSema
2730b57cec5SDimitry Andric       = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
2740b57cec5SDimitry Andric     ExternalSema->InitializeSema(*this);
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric   // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
2770b57cec5SDimitry Andric   // will not be able to merge any duplicate __va_list_tag decls correctly.
2780b57cec5SDimitry Andric   VAListTagName = PP.getIdentifierInfo("__va_list_tag");
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric   if (!TUScope)
2810b57cec5SDimitry Andric     return;
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric   // Initialize predefined 128-bit integer types, if needed.
284e8d8bef9SDimitry Andric   if (Context.getTargetInfo().hasInt128Type() ||
285e8d8bef9SDimitry Andric       (Context.getAuxTargetInfo() &&
286e8d8bef9SDimitry Andric        Context.getAuxTargetInfo()->hasInt128Type())) {
2870b57cec5SDimitry Andric     // If either of the 128-bit integer types are unavailable to name lookup,
2880b57cec5SDimitry Andric     // define them now.
2890b57cec5SDimitry Andric     DeclarationName Int128 = &Context.Idents.get("__int128_t");
2900b57cec5SDimitry Andric     if (IdResolver.begin(Int128) == IdResolver.end())
2910b57cec5SDimitry Andric       PushOnScopeChains(Context.getInt128Decl(), TUScope);
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric     DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
2940b57cec5SDimitry Andric     if (IdResolver.begin(UInt128) == IdResolver.end())
2950b57cec5SDimitry Andric       PushOnScopeChains(Context.getUInt128Decl(), TUScope);
2960b57cec5SDimitry Andric   }
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   // Initialize predefined Objective-C types:
3000b57cec5SDimitry Andric   if (getLangOpts().ObjC) {
3010b57cec5SDimitry Andric     // If 'SEL' does not yet refer to any declarations, make it refer to the
3020b57cec5SDimitry Andric     // predefined 'SEL'.
3030b57cec5SDimitry Andric     DeclarationName SEL = &Context.Idents.get("SEL");
3040b57cec5SDimitry Andric     if (IdResolver.begin(SEL) == IdResolver.end())
3050b57cec5SDimitry Andric       PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric     // If 'id' does not yet refer to any declarations, make it refer to the
3080b57cec5SDimitry Andric     // predefined 'id'.
3090b57cec5SDimitry Andric     DeclarationName Id = &Context.Idents.get("id");
3100b57cec5SDimitry Andric     if (IdResolver.begin(Id) == IdResolver.end())
3110b57cec5SDimitry Andric       PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric     // Create the built-in typedef for 'Class'.
3140b57cec5SDimitry Andric     DeclarationName Class = &Context.Idents.get("Class");
3150b57cec5SDimitry Andric     if (IdResolver.begin(Class) == IdResolver.end())
3160b57cec5SDimitry Andric       PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric     // Create the built-in forward declaratino for 'Protocol'.
3190b57cec5SDimitry Andric     DeclarationName Protocol = &Context.Idents.get("Protocol");
3200b57cec5SDimitry Andric     if (IdResolver.begin(Protocol) == IdResolver.end())
3210b57cec5SDimitry Andric       PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
3220b57cec5SDimitry Andric   }
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric   // Create the internal type for the *StringMakeConstantString builtins.
3250b57cec5SDimitry Andric   DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
3260b57cec5SDimitry Andric   if (IdResolver.begin(ConstantString) == IdResolver.end())
3270b57cec5SDimitry Andric     PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   // Initialize Microsoft "predefined C++ types".
3300b57cec5SDimitry Andric   if (getLangOpts().MSVCCompat) {
3310b57cec5SDimitry Andric     if (getLangOpts().CPlusPlus &&
3320b57cec5SDimitry Andric         IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
333*5f757f3fSDimitry Andric       PushOnScopeChains(
334*5f757f3fSDimitry Andric           Context.buildImplicitRecord("type_info", TagTypeKind::Class),
3350b57cec5SDimitry Andric           TUScope);
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric     addImplicitTypedef("size_t", Context.getSizeType());
3380b57cec5SDimitry Andric   }
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric   // Initialize predefined OpenCL types and supported extensions and (optional)
3410b57cec5SDimitry Andric   // core features.
3420b57cec5SDimitry Andric   if (getLangOpts().OpenCL) {
3430b57cec5SDimitry Andric     getOpenCLOptions().addSupport(
344e8d8bef9SDimitry Andric         Context.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts());
3450b57cec5SDimitry Andric     addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
3460b57cec5SDimitry Andric     addImplicitTypedef("event_t", Context.OCLEventTy);
34704eeddc0SDimitry Andric     auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion();
34804eeddc0SDimitry Andric     if (OCLCompatibleVersion >= 200) {
34904eeddc0SDimitry Andric       if (getLangOpts().OpenCLCPlusPlus || getLangOpts().Blocks) {
3500b57cec5SDimitry Andric         addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
3510b57cec5SDimitry Andric         addImplicitTypedef("queue_t", Context.OCLQueueTy);
35204eeddc0SDimitry Andric       }
3536e75b2fbSDimitry Andric       if (getLangOpts().OpenCLPipes)
3540b57cec5SDimitry Andric         addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
3550b57cec5SDimitry Andric       addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
3560b57cec5SDimitry Andric       addImplicitTypedef("atomic_uint",
3570b57cec5SDimitry Andric                          Context.getAtomicType(Context.UnsignedIntTy));
3580b57cec5SDimitry Andric       addImplicitTypedef("atomic_float",
3590b57cec5SDimitry Andric                          Context.getAtomicType(Context.FloatTy));
3600b57cec5SDimitry Andric       // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
3610b57cec5SDimitry Andric       // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
3620b57cec5SDimitry Andric       addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
363fe6060f1SDimitry Andric 
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric       // OpenCL v2.0 s6.13.11.6:
3660b57cec5SDimitry Andric       // - The atomic_long and atomic_ulong types are supported if the
3670b57cec5SDimitry Andric       //   cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
3680b57cec5SDimitry Andric       //   extensions are supported.
3690b57cec5SDimitry Andric       // - The atomic_double type is only supported if double precision
3700b57cec5SDimitry Andric       //   is supported and the cl_khr_int64_base_atomics and
3710b57cec5SDimitry Andric       //   cl_khr_int64_extended_atomics extensions are supported.
3720b57cec5SDimitry Andric       // - If the device address space is 64-bits, the data types
3730b57cec5SDimitry Andric       //   atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
3740b57cec5SDimitry Andric       //   atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
3750b57cec5SDimitry Andric       //   cl_khr_int64_extended_atomics extensions are supported.
376fe6060f1SDimitry Andric 
377fe6060f1SDimitry Andric       auto AddPointerSizeDependentTypes = [&]() {
378fe6060f1SDimitry Andric         auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
379fe6060f1SDimitry Andric         auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
380fe6060f1SDimitry Andric         auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
381fe6060f1SDimitry Andric         auto AtomicPtrDiffT =
382fe6060f1SDimitry Andric             Context.getAtomicType(Context.getPointerDiffType());
383fe6060f1SDimitry Andric         addImplicitTypedef("atomic_size_t", AtomicSizeT);
384fe6060f1SDimitry Andric         addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
385fe6060f1SDimitry Andric         addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
386fe6060f1SDimitry Andric         addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
387fe6060f1SDimitry Andric       };
388fe6060f1SDimitry Andric 
389fe6060f1SDimitry Andric       if (Context.getTypeSize(Context.getSizeType()) == 32) {
390fe6060f1SDimitry Andric         AddPointerSizeDependentTypes();
391fe6060f1SDimitry Andric       }
392fe6060f1SDimitry Andric 
393349cc55cSDimitry Andric       if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) {
394349cc55cSDimitry Andric         auto AtomicHalfT = Context.getAtomicType(Context.HalfTy);
395349cc55cSDimitry Andric         addImplicitTypedef("atomic_half", AtomicHalfT);
396349cc55cSDimitry Andric       }
397349cc55cSDimitry Andric 
3980b57cec5SDimitry Andric       std::vector<QualType> Atomic64BitTypes;
399fe6060f1SDimitry Andric       if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",
400fe6060f1SDimitry Andric                                          getLangOpts()) &&
401fe6060f1SDimitry Andric           getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",
402fe6060f1SDimitry Andric                                          getLangOpts())) {
403fe6060f1SDimitry Andric         if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {
404fe6060f1SDimitry Andric           auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
405fe6060f1SDimitry Andric           addImplicitTypedef("atomic_double", AtomicDoubleT);
4060b57cec5SDimitry Andric           Atomic64BitTypes.push_back(AtomicDoubleT);
4070b57cec5SDimitry Andric         }
408fe6060f1SDimitry Andric         auto AtomicLongT = Context.getAtomicType(Context.LongTy);
409fe6060f1SDimitry Andric         auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
410fe6060f1SDimitry Andric         addImplicitTypedef("atomic_long", AtomicLongT);
411fe6060f1SDimitry Andric         addImplicitTypedef("atomic_ulong", AtomicULongT);
4120b57cec5SDimitry Andric 
413fe6060f1SDimitry Andric 
414fe6060f1SDimitry Andric         if (Context.getTypeSize(Context.getSizeType()) == 64) {
415fe6060f1SDimitry Andric           AddPointerSizeDependentTypes();
416fe6060f1SDimitry Andric         }
417fe6060f1SDimitry Andric       }
4180b57cec5SDimitry Andric     }
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric #define EXT_OPAQUE_TYPE(ExtType, Id, Ext)                                      \
421fe6060f1SDimitry Andric   if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) {                   \
4220b57cec5SDimitry Andric     addImplicitTypedef(#ExtType, Context.Id##Ty);                              \
423fe6060f1SDimitry Andric   }
4240b57cec5SDimitry Andric #include "clang/Basic/OpenCLExtensionTypes.def"
425a7dea167SDimitry Andric   }
426a7dea167SDimitry Andric 
427a7dea167SDimitry Andric   if (Context.getTargetInfo().hasAArch64SVETypes()) {
428a7dea167SDimitry Andric #define SVE_TYPE(Name, Id, SingletonId) \
429a7dea167SDimitry Andric     addImplicitTypedef(Name, Context.SingletonId);
430a7dea167SDimitry Andric #include "clang/Basic/AArch64SVEACLETypes.def"
431a7dea167SDimitry Andric   }
4320b57cec5SDimitry Andric 
433349cc55cSDimitry Andric   if (Context.getTargetInfo().getTriple().isPPC64()) {
434e8d8bef9SDimitry Andric #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
435e8d8bef9SDimitry Andric       addImplicitTypedef(#Name, Context.Id##Ty);
436e8d8bef9SDimitry Andric #include "clang/Basic/PPCTypes.def"
437e8d8bef9SDimitry Andric #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
438e8d8bef9SDimitry Andric     addImplicitTypedef(#Name, Context.Id##Ty);
439e8d8bef9SDimitry Andric #include "clang/Basic/PPCTypes.def"
440e8d8bef9SDimitry Andric   }
441e8d8bef9SDimitry Andric 
442fe6060f1SDimitry Andric   if (Context.getTargetInfo().hasRISCVVTypes()) {
443fe6060f1SDimitry Andric #define RVV_TYPE(Name, Id, SingletonId)                                        \
444fe6060f1SDimitry Andric   addImplicitTypedef(Name, Context.SingletonId);
445fe6060f1SDimitry Andric #include "clang/Basic/RISCVVTypes.def"
446fe6060f1SDimitry Andric   }
447fe6060f1SDimitry Andric 
44806c3fb27SDimitry Andric   if (Context.getTargetInfo().getTriple().isWasm() &&
44906c3fb27SDimitry Andric       Context.getTargetInfo().hasFeature("reference-types")) {
45006c3fb27SDimitry Andric #define WASM_TYPE(Name, Id, SingletonId)                                       \
45106c3fb27SDimitry Andric   addImplicitTypedef(Name, Context.SingletonId);
45206c3fb27SDimitry Andric #include "clang/Basic/WebAssemblyReferenceTypes.def"
45306c3fb27SDimitry Andric   }
45406c3fb27SDimitry Andric 
4550b57cec5SDimitry Andric   if (Context.getTargetInfo().hasBuiltinMSVaList()) {
4560b57cec5SDimitry Andric     DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
4570b57cec5SDimitry Andric     if (IdResolver.begin(MSVaList) == IdResolver.end())
4580b57cec5SDimitry Andric       PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
4590b57cec5SDimitry Andric   }
4600b57cec5SDimitry Andric 
4610b57cec5SDimitry Andric   DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
4620b57cec5SDimitry Andric   if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
4630b57cec5SDimitry Andric     PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
4640b57cec5SDimitry Andric }
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric Sema::~Sema() {
467e8d8bef9SDimitry Andric   assert(InstantiatingSpecializations.empty() &&
468e8d8bef9SDimitry Andric          "failed to clean up an InstantiatingTemplate?");
469e8d8bef9SDimitry Andric 
4700b57cec5SDimitry Andric   if (VisContext) FreeVisContext();
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   // Kill all the active scopes.
4730b57cec5SDimitry Andric   for (sema::FunctionScopeInfo *FSI : FunctionScopes)
4740b57cec5SDimitry Andric     delete FSI;
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric   // Tell the SemaConsumer to forget about us; we're going out of scope.
4770b57cec5SDimitry Andric   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
4780b57cec5SDimitry Andric     SC->ForgetSema();
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric   // Detach from the external Sema source.
4810b57cec5SDimitry Andric   if (ExternalSemaSource *ExternalSema
4820b57cec5SDimitry Andric         = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
4830b57cec5SDimitry Andric     ExternalSema->ForgetSema();
4840b57cec5SDimitry Andric 
48555e4f9d5SDimitry Andric   // Delete cached satisfactions.
48655e4f9d5SDimitry Andric   std::vector<ConstraintSatisfaction *> Satisfactions;
487*5f757f3fSDimitry Andric   Satisfactions.reserve(SatisfactionCache.size());
48855e4f9d5SDimitry Andric   for (auto &Node : SatisfactionCache)
48955e4f9d5SDimitry Andric     Satisfactions.push_back(&Node);
49055e4f9d5SDimitry Andric   for (auto *Node : Satisfactions)
49155e4f9d5SDimitry Andric     delete Node;
49255e4f9d5SDimitry Andric 
4930b57cec5SDimitry Andric   threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric   // Destroys data sharing attributes stack for OpenMP
4960b57cec5SDimitry Andric   DestroyDataSharingAttributesStack();
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric   // Detach from the PP callback handler which outlives Sema since it's owned
4990b57cec5SDimitry Andric   // by the preprocessor.
5000b57cec5SDimitry Andric   SemaPPCallbackHandler->reset();
501a7dea167SDimitry Andric }
5020b57cec5SDimitry Andric 
503a7dea167SDimitry Andric void Sema::warnStackExhausted(SourceLocation Loc) {
504a7dea167SDimitry Andric   // Only warn about this once.
505a7dea167SDimitry Andric   if (!WarnedStackExhausted) {
506a7dea167SDimitry Andric     Diag(Loc, diag::warn_stack_exhausted);
507a7dea167SDimitry Andric     WarnedStackExhausted = true;
508a7dea167SDimitry Andric   }
509a7dea167SDimitry Andric }
510a7dea167SDimitry Andric 
511a7dea167SDimitry Andric void Sema::runWithSufficientStackSpace(SourceLocation Loc,
512a7dea167SDimitry Andric                                        llvm::function_ref<void()> Fn) {
513a7dea167SDimitry Andric   clang::runWithSufficientStackSpace([&] { warnStackExhausted(Loc); }, Fn);
5140b57cec5SDimitry Andric }
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric /// makeUnavailableInSystemHeader - There is an error in the current
5170b57cec5SDimitry Andric /// context.  If we're still in a system header, and we can plausibly
5180b57cec5SDimitry Andric /// make the relevant declaration unavailable instead of erroring, do
5190b57cec5SDimitry Andric /// so and return true.
5200b57cec5SDimitry Andric bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
5210b57cec5SDimitry Andric                                       UnavailableAttr::ImplicitReason reason) {
5220b57cec5SDimitry Andric   // If we're not in a function, it's an error.
5230b57cec5SDimitry Andric   FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
5240b57cec5SDimitry Andric   if (!fn) return false;
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric   // If we're in template instantiation, it's an error.
5270b57cec5SDimitry Andric   if (inTemplateInstantiation())
5280b57cec5SDimitry Andric     return false;
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric   // If that function's not in a system header, it's an error.
5310b57cec5SDimitry Andric   if (!Context.getSourceManager().isInSystemHeader(loc))
5320b57cec5SDimitry Andric     return false;
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric   // If the function is already unavailable, it's not an error.
5350b57cec5SDimitry Andric   if (fn->hasAttr<UnavailableAttr>()) return true;
5360b57cec5SDimitry Andric 
5370b57cec5SDimitry Andric   fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
5380b57cec5SDimitry Andric   return true;
5390b57cec5SDimitry Andric }
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric ASTMutationListener *Sema::getASTMutationListener() const {
5420b57cec5SDimitry Andric   return getASTConsumer().GetASTMutationListener();
5430b57cec5SDimitry Andric }
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric ///Registers an external source. If an external source already exists,
5460b57cec5SDimitry Andric /// creates a multiplex external source and appends to it.
5470b57cec5SDimitry Andric ///
5480b57cec5SDimitry Andric ///\param[in] E - A non-null external sema source.
5490b57cec5SDimitry Andric ///
5500b57cec5SDimitry Andric void Sema::addExternalSource(ExternalSemaSource *E) {
5510b57cec5SDimitry Andric   assert(E && "Cannot use with NULL ptr");
5520b57cec5SDimitry Andric 
5530b57cec5SDimitry Andric   if (!ExternalSource) {
5540b57cec5SDimitry Andric     ExternalSource = E;
5550b57cec5SDimitry Andric     return;
5560b57cec5SDimitry Andric   }
5570b57cec5SDimitry Andric 
558bdd1243dSDimitry Andric   if (auto *Ex = dyn_cast<MultiplexExternalSemaSource>(ExternalSource))
559bdd1243dSDimitry Andric     Ex->AddSource(E);
560bdd1243dSDimitry Andric   else
561bdd1243dSDimitry Andric     ExternalSource = new MultiplexExternalSemaSource(ExternalSource.get(), E);
5620b57cec5SDimitry Andric }
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric /// Print out statistics about the semantic analysis.
5650b57cec5SDimitry Andric void Sema::PrintStats() const {
5660b57cec5SDimitry Andric   llvm::errs() << "\n*** Semantic Analysis Stats:\n";
5670b57cec5SDimitry Andric   llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric   BumpAlloc.PrintStats();
5700b57cec5SDimitry Andric   AnalysisWarnings.PrintStats();
5710b57cec5SDimitry Andric }
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
5740b57cec5SDimitry Andric                                                QualType SrcType,
5750b57cec5SDimitry Andric                                                SourceLocation Loc) {
576bdd1243dSDimitry Andric   std::optional<NullabilityKind> ExprNullability = SrcType->getNullability();
577e8d8bef9SDimitry Andric   if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable &&
578e8d8bef9SDimitry Andric                            *ExprNullability != NullabilityKind::NullableResult))
5790b57cec5SDimitry Andric     return;
5800b57cec5SDimitry Andric 
581bdd1243dSDimitry Andric   std::optional<NullabilityKind> TypeNullability = DstType->getNullability();
5820b57cec5SDimitry Andric   if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
5830b57cec5SDimitry Andric     return;
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric   Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
5860b57cec5SDimitry Andric }
5870b57cec5SDimitry Andric 
5880b57cec5SDimitry Andric void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E) {
5890b57cec5SDimitry Andric   // nullptr only exists from C++11 on, so don't warn on its absence earlier.
5900b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus11)
5910b57cec5SDimitry Andric     return;
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric   if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
5940b57cec5SDimitry Andric     return;
595*5f757f3fSDimitry Andric 
596*5f757f3fSDimitry Andric   const Expr *EStripped = E->IgnoreParenImpCasts();
597*5f757f3fSDimitry Andric   if (EStripped->getType()->isNullPtrType())
598*5f757f3fSDimitry Andric     return;
599*5f757f3fSDimitry Andric   if (isa<GNUNullExpr>(EStripped))
6000b57cec5SDimitry Andric     return;
6010b57cec5SDimitry Andric 
602bdd1243dSDimitry Andric   if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
603bdd1243dSDimitry Andric                       E->getBeginLoc()))
604bdd1243dSDimitry Andric     return;
605bdd1243dSDimitry Andric 
606d409305fSDimitry Andric   // Don't diagnose the conversion from a 0 literal to a null pointer argument
607d409305fSDimitry Andric   // in a synthesized call to operator<=>.
608d409305fSDimitry Andric   if (!CodeSynthesisContexts.empty() &&
609d409305fSDimitry Andric       CodeSynthesisContexts.back().Kind ==
610d409305fSDimitry Andric           CodeSynthesisContext::RewritingOperatorAsSpaceship)
611d409305fSDimitry Andric     return;
612d409305fSDimitry Andric 
613bdd1243dSDimitry Andric   // Ignore null pointers in defaulted comparison operators.
614bdd1243dSDimitry Andric   FunctionDecl *FD = getCurFunctionDecl();
615bdd1243dSDimitry Andric   if (FD && FD->isDefaulted()) {
616bdd1243dSDimitry Andric     return;
617bdd1243dSDimitry Andric   }
618bdd1243dSDimitry Andric 
6190b57cec5SDimitry Andric   // If it is a macro from system header, and if the macro name is not "NULL",
6200b57cec5SDimitry Andric   // do not warn.
621*5f757f3fSDimitry Andric   // Note that uses of "NULL" will be ignored above on systems that define it
622*5f757f3fSDimitry Andric   // as __null.
6230b57cec5SDimitry Andric   SourceLocation MaybeMacroLoc = E->getBeginLoc();
6240b57cec5SDimitry Andric   if (Diags.getSuppressSystemWarnings() &&
6250b57cec5SDimitry Andric       SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
6260b57cec5SDimitry Andric       !findMacroSpelling(MaybeMacroLoc, "NULL"))
6270b57cec5SDimitry Andric     return;
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric   Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
6300b57cec5SDimitry Andric       << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
6310b57cec5SDimitry Andric }
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
6340b57cec5SDimitry Andric /// If there is already an implicit cast, merge into the existing one.
6350b57cec5SDimitry Andric /// The result is of the given category.
6360b57cec5SDimitry Andric ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
6370b57cec5SDimitry Andric                                    CastKind Kind, ExprValueKind VK,
6380b57cec5SDimitry Andric                                    const CXXCastPath *BasePath,
6390b57cec5SDimitry Andric                                    CheckedConversionKind CCK) {
6400b57cec5SDimitry Andric #ifndef NDEBUG
641fe6060f1SDimitry Andric   if (VK == VK_PRValue && !E->isPRValue()) {
6420b57cec5SDimitry Andric     switch (Kind) {
6430b57cec5SDimitry Andric     default:
644fe6060f1SDimitry Andric       llvm_unreachable(
645fe6060f1SDimitry Andric           ("can't implicitly cast glvalue to prvalue with this cast "
646e8d8bef9SDimitry Andric            "kind: " +
647e8d8bef9SDimitry Andric            std::string(CastExpr::getCastKindName(Kind)))
648e8d8bef9SDimitry Andric               .c_str());
6490b57cec5SDimitry Andric     case CK_Dependent:
6500b57cec5SDimitry Andric     case CK_LValueToRValue:
6510b57cec5SDimitry Andric     case CK_ArrayToPointerDecay:
6520b57cec5SDimitry Andric     case CK_FunctionToPointerDecay:
6530b57cec5SDimitry Andric     case CK_ToVoid:
6540b57cec5SDimitry Andric     case CK_NonAtomicToAtomic:
6550b57cec5SDimitry Andric       break;
6560b57cec5SDimitry Andric     }
6570b57cec5SDimitry Andric   }
658fe6060f1SDimitry Andric   assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) &&
659fe6060f1SDimitry Andric          "can't cast prvalue to glvalue");
6600b57cec5SDimitry Andric #endif
6610b57cec5SDimitry Andric 
6620b57cec5SDimitry Andric   diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc());
6630b57cec5SDimitry Andric   diagnoseZeroToNullptrConversion(Kind, E);
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric   QualType ExprTy = Context.getCanonicalType(E->getType());
6660b57cec5SDimitry Andric   QualType TypeTy = Context.getCanonicalType(Ty);
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric   if (ExprTy == TypeTy)
6690b57cec5SDimitry Andric     return E;
6700b57cec5SDimitry Andric 
671fe6060f1SDimitry Andric   if (Kind == CK_ArrayToPointerDecay) {
6720b57cec5SDimitry Andric     // C++1z [conv.array]: The temporary materialization conversion is applied.
6730b57cec5SDimitry Andric     // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
674fe6060f1SDimitry Andric     if (getLangOpts().CPlusPlus && E->isPRValue()) {
6750b57cec5SDimitry Andric       // The temporary is an lvalue in C++98 and an xvalue otherwise.
6760b57cec5SDimitry Andric       ExprResult Materialized = CreateMaterializeTemporaryExpr(
6770b57cec5SDimitry Andric           E->getType(), E, !getLangOpts().CPlusPlus11);
6780b57cec5SDimitry Andric       if (Materialized.isInvalid())
6790b57cec5SDimitry Andric         return ExprError();
6800b57cec5SDimitry Andric       E = Materialized.get();
6810b57cec5SDimitry Andric     }
682fe6060f1SDimitry Andric     // C17 6.7.1p6 footnote 124: The implementation can treat any register
683fe6060f1SDimitry Andric     // declaration simply as an auto declaration. However, whether or not
684fe6060f1SDimitry Andric     // addressable storage is actually used, the address of any part of an
685fe6060f1SDimitry Andric     // object declared with storage-class specifier register cannot be
686fe6060f1SDimitry Andric     // computed, either explicitly(by use of the unary & operator as discussed
687fe6060f1SDimitry Andric     // in 6.5.3.2) or implicitly(by converting an array name to a pointer as
688fe6060f1SDimitry Andric     // discussed in 6.3.2.1).Thus, the only operator that can be applied to an
689fe6060f1SDimitry Andric     // array declared with storage-class specifier register is sizeof.
690fe6060f1SDimitry Andric     if (VK == VK_PRValue && !getLangOpts().CPlusPlus && !E->isPRValue()) {
691fe6060f1SDimitry Andric       if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
692fe6060f1SDimitry Andric         if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
693fe6060f1SDimitry Andric           if (VD->getStorageClass() == SC_Register) {
694fe6060f1SDimitry Andric             Diag(E->getExprLoc(), diag::err_typecheck_address_of)
695fe6060f1SDimitry Andric                 << /*register variable*/ 3 << E->getSourceRange();
696fe6060f1SDimitry Andric             return ExprError();
697fe6060f1SDimitry Andric           }
698fe6060f1SDimitry Andric         }
699fe6060f1SDimitry Andric       }
700fe6060f1SDimitry Andric     }
701fe6060f1SDimitry Andric   }
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric   if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
7040b57cec5SDimitry Andric     if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
7050b57cec5SDimitry Andric       ImpCast->setType(Ty);
7060b57cec5SDimitry Andric       ImpCast->setValueKind(VK);
7070b57cec5SDimitry Andric       return E;
7080b57cec5SDimitry Andric     }
7090b57cec5SDimitry Andric   }
7100b57cec5SDimitry Andric 
711e8d8bef9SDimitry Andric   return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
712e8d8bef9SDimitry Andric                                   CurFPFeatureOverrides());
7130b57cec5SDimitry Andric }
7140b57cec5SDimitry Andric 
7150b57cec5SDimitry Andric /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
7160b57cec5SDimitry Andric /// to the conversion from scalar type ScalarTy to the Boolean type.
7170b57cec5SDimitry Andric CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
7180b57cec5SDimitry Andric   switch (ScalarTy->getScalarTypeKind()) {
7190b57cec5SDimitry Andric   case Type::STK_Bool: return CK_NoOp;
7200b57cec5SDimitry Andric   case Type::STK_CPointer: return CK_PointerToBoolean;
7210b57cec5SDimitry Andric   case Type::STK_BlockPointer: return CK_PointerToBoolean;
7220b57cec5SDimitry Andric   case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
7230b57cec5SDimitry Andric   case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
7240b57cec5SDimitry Andric   case Type::STK_Integral: return CK_IntegralToBoolean;
7250b57cec5SDimitry Andric   case Type::STK_Floating: return CK_FloatingToBoolean;
7260b57cec5SDimitry Andric   case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
7270b57cec5SDimitry Andric   case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
7280b57cec5SDimitry Andric   case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
7290b57cec5SDimitry Andric   }
7300b57cec5SDimitry Andric   llvm_unreachable("unknown scalar type kind");
7310b57cec5SDimitry Andric }
7320b57cec5SDimitry Andric 
7330b57cec5SDimitry Andric /// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
7340b57cec5SDimitry Andric static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
7350b57cec5SDimitry Andric   if (D->getMostRecentDecl()->isUsed())
7360b57cec5SDimitry Andric     return true;
7370b57cec5SDimitry Andric 
7380b57cec5SDimitry Andric   if (D->isExternallyVisible())
7390b57cec5SDimitry Andric     return true;
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7420b57cec5SDimitry Andric     // If this is a function template and none of its specializations is used,
7430b57cec5SDimitry Andric     // we should warn.
7440b57cec5SDimitry Andric     if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
7450b57cec5SDimitry Andric       for (const auto *Spec : Template->specializations())
7460b57cec5SDimitry Andric         if (ShouldRemoveFromUnused(SemaRef, Spec))
7470b57cec5SDimitry Andric           return true;
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric     // UnusedFileScopedDecls stores the first declaration.
7500b57cec5SDimitry Andric     // The declaration may have become definition so check again.
7510b57cec5SDimitry Andric     const FunctionDecl *DeclToCheck;
7520b57cec5SDimitry Andric     if (FD->hasBody(DeclToCheck))
7530b57cec5SDimitry Andric       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric     // Later redecls may add new information resulting in not having to warn,
7560b57cec5SDimitry Andric     // so check again.
7570b57cec5SDimitry Andric     DeclToCheck = FD->getMostRecentDecl();
7580b57cec5SDimitry Andric     if (DeclToCheck != FD)
7590b57cec5SDimitry Andric       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
7600b57cec5SDimitry Andric   }
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7630b57cec5SDimitry Andric     // If a variable usable in constant expressions is referenced,
7640b57cec5SDimitry Andric     // don't warn if it isn't used: if the value of a variable is required
7650b57cec5SDimitry Andric     // for the computation of a constant expression, it doesn't make sense to
7660b57cec5SDimitry Andric     // warn even if the variable isn't odr-used.  (isReferenced doesn't
7670b57cec5SDimitry Andric     // precisely reflect that, but it's a decent approximation.)
7680b57cec5SDimitry Andric     if (VD->isReferenced() &&
7690b57cec5SDimitry Andric         VD->mightBeUsableInConstantExpressions(SemaRef->Context))
7700b57cec5SDimitry Andric       return true;
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric     if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
7730b57cec5SDimitry Andric       // If this is a variable template and none of its specializations is used,
7740b57cec5SDimitry Andric       // we should warn.
7750b57cec5SDimitry Andric       for (const auto *Spec : Template->specializations())
7760b57cec5SDimitry Andric         if (ShouldRemoveFromUnused(SemaRef, Spec))
7770b57cec5SDimitry Andric           return true;
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric     // UnusedFileScopedDecls stores the first declaration.
7800b57cec5SDimitry Andric     // The declaration may have become definition so check again.
7810b57cec5SDimitry Andric     const VarDecl *DeclToCheck = VD->getDefinition();
7820b57cec5SDimitry Andric     if (DeclToCheck)
7830b57cec5SDimitry Andric       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
7840b57cec5SDimitry Andric 
7850b57cec5SDimitry Andric     // Later redecls may add new information resulting in not having to warn,
7860b57cec5SDimitry Andric     // so check again.
7870b57cec5SDimitry Andric     DeclToCheck = VD->getMostRecentDecl();
7880b57cec5SDimitry Andric     if (DeclToCheck != VD)
7890b57cec5SDimitry Andric       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
7900b57cec5SDimitry Andric   }
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric   return false;
7930b57cec5SDimitry Andric }
7940b57cec5SDimitry Andric 
79506c3fb27SDimitry Andric static bool isFunctionOrVarDeclExternC(const NamedDecl *ND) {
79606c3fb27SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
7970b57cec5SDimitry Andric     return FD->isExternC();
7980b57cec5SDimitry Andric   return cast<VarDecl>(ND)->isExternC();
7990b57cec5SDimitry Andric }
8000b57cec5SDimitry Andric 
8010b57cec5SDimitry Andric /// Determine whether ND is an external-linkage function or variable whose
8020b57cec5SDimitry Andric /// type has no linkage.
80306c3fb27SDimitry Andric bool Sema::isExternalWithNoLinkageType(const ValueDecl *VD) const {
8040b57cec5SDimitry Andric   // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
8050b57cec5SDimitry Andric   // because we also want to catch the case where its type has VisibleNoLinkage,
8060b57cec5SDimitry Andric   // which does not affect the linkage of VD.
8070b57cec5SDimitry Andric   return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
8080b57cec5SDimitry Andric          !isExternalFormalLinkage(VD->getType()->getLinkage()) &&
8090b57cec5SDimitry Andric          !isFunctionOrVarDeclExternC(VD);
8100b57cec5SDimitry Andric }
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric /// Obtains a sorted list of functions and variables that are undefined but
8130b57cec5SDimitry Andric /// ODR-used.
8140b57cec5SDimitry Andric void Sema::getUndefinedButUsed(
8150b57cec5SDimitry Andric     SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
8160b57cec5SDimitry Andric   for (const auto &UndefinedUse : UndefinedButUsed) {
8170b57cec5SDimitry Andric     NamedDecl *ND = UndefinedUse.first;
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric     // Ignore attributes that have become invalid.
8200b57cec5SDimitry Andric     if (ND->isInvalidDecl()) continue;
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric     // __attribute__((weakref)) is basically a definition.
8230b57cec5SDimitry Andric     if (ND->hasAttr<WeakRefAttr>()) continue;
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric     if (isa<CXXDeductionGuideDecl>(ND))
8260b57cec5SDimitry Andric       continue;
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric     if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
8290b57cec5SDimitry Andric       // An exported function will always be emitted when defined, so even if
8300b57cec5SDimitry Andric       // the function is inline, it doesn't have to be emitted in this TU. An
8310b57cec5SDimitry Andric       // imported function implies that it has been exported somewhere else.
8320b57cec5SDimitry Andric       continue;
8330b57cec5SDimitry Andric     }
8340b57cec5SDimitry Andric 
835*5f757f3fSDimitry Andric     if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
8360b57cec5SDimitry Andric       if (FD->isDefined())
8370b57cec5SDimitry Andric         continue;
8380b57cec5SDimitry Andric       if (FD->isExternallyVisible() &&
8390b57cec5SDimitry Andric           !isExternalWithNoLinkageType(FD) &&
8400b57cec5SDimitry Andric           !FD->getMostRecentDecl()->isInlined() &&
8410b57cec5SDimitry Andric           !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
8420b57cec5SDimitry Andric         continue;
8430b57cec5SDimitry Andric       if (FD->getBuiltinID())
8440b57cec5SDimitry Andric         continue;
8450b57cec5SDimitry Andric     } else {
846*5f757f3fSDimitry Andric       const auto *VD = cast<VarDecl>(ND);
8470b57cec5SDimitry Andric       if (VD->hasDefinition() != VarDecl::DeclarationOnly)
8480b57cec5SDimitry Andric         continue;
8490b57cec5SDimitry Andric       if (VD->isExternallyVisible() &&
8500b57cec5SDimitry Andric           !isExternalWithNoLinkageType(VD) &&
8510b57cec5SDimitry Andric           !VD->getMostRecentDecl()->isInline() &&
8520b57cec5SDimitry Andric           !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
8530b57cec5SDimitry Andric         continue;
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric       // Skip VarDecls that lack formal definitions but which we know are in
8560b57cec5SDimitry Andric       // fact defined somewhere.
8570b57cec5SDimitry Andric       if (VD->isKnownToBeDefined())
8580b57cec5SDimitry Andric         continue;
8590b57cec5SDimitry Andric     }
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric     Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
8620b57cec5SDimitry Andric   }
8630b57cec5SDimitry Andric }
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric /// checkUndefinedButUsed - Check for undefined objects with internal linkage
8660b57cec5SDimitry Andric /// or that are inline.
8670b57cec5SDimitry Andric static void checkUndefinedButUsed(Sema &S) {
8680b57cec5SDimitry Andric   if (S.UndefinedButUsed.empty()) return;
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric   // Collect all the still-undefined entities with internal linkage.
8710b57cec5SDimitry Andric   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
8720b57cec5SDimitry Andric   S.getUndefinedButUsed(Undefined);
873*5f757f3fSDimitry Andric   S.UndefinedButUsed.clear();
8740b57cec5SDimitry Andric   if (Undefined.empty()) return;
8750b57cec5SDimitry Andric 
87606c3fb27SDimitry Andric   for (const auto &Undef : Undefined) {
8770b57cec5SDimitry Andric     ValueDecl *VD = cast<ValueDecl>(Undef.first);
8780b57cec5SDimitry Andric     SourceLocation UseLoc = Undef.second;
8790b57cec5SDimitry Andric 
8800b57cec5SDimitry Andric     if (S.isExternalWithNoLinkageType(VD)) {
8810b57cec5SDimitry Andric       // C++ [basic.link]p8:
8820b57cec5SDimitry Andric       //   A type without linkage shall not be used as the type of a variable
8830b57cec5SDimitry Andric       //   or function with external linkage unless
8840b57cec5SDimitry Andric       //    -- the entity has C language linkage
8850b57cec5SDimitry Andric       //    -- the entity is not odr-used or is defined in the same TU
8860b57cec5SDimitry Andric       //
8870b57cec5SDimitry Andric       // As an extension, accept this in cases where the type is externally
8880b57cec5SDimitry Andric       // visible, since the function or variable actually can be defined in
8890b57cec5SDimitry Andric       // another translation unit in that case.
8900b57cec5SDimitry Andric       S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
8910b57cec5SDimitry Andric                                     ? diag::ext_undefined_internal_type
8920b57cec5SDimitry Andric                                     : diag::err_undefined_internal_type)
8930b57cec5SDimitry Andric         << isa<VarDecl>(VD) << VD;
8940b57cec5SDimitry Andric     } else if (!VD->isExternallyVisible()) {
8950b57cec5SDimitry Andric       // FIXME: We can promote this to an error. The function or variable can't
8960b57cec5SDimitry Andric       // be defined anywhere else, so the program must necessarily violate the
8970b57cec5SDimitry Andric       // one definition rule.
898fe6060f1SDimitry Andric       bool IsImplicitBase = false;
899fe6060f1SDimitry Andric       if (const auto *BaseD = dyn_cast<FunctionDecl>(VD)) {
900fe6060f1SDimitry Andric         auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();
901fe6060f1SDimitry Andric         if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
902fe6060f1SDimitry Andric                           llvm::omp::TraitProperty::
903fe6060f1SDimitry Andric                               implementation_extension_disable_implicit_base)) {
904fe6060f1SDimitry Andric           const auto *Func = cast<FunctionDecl>(
905fe6060f1SDimitry Andric               cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl());
906fe6060f1SDimitry Andric           IsImplicitBase = BaseD->isImplicit() &&
907fe6060f1SDimitry Andric                            Func->getIdentifier()->isMangledOpenMPVariantName();
908fe6060f1SDimitry Andric         }
909fe6060f1SDimitry Andric       }
910fe6060f1SDimitry Andric       if (!S.getLangOpts().OpenMP || !IsImplicitBase)
9110b57cec5SDimitry Andric         S.Diag(VD->getLocation(), diag::warn_undefined_internal)
9120b57cec5SDimitry Andric             << isa<VarDecl>(VD) << VD;
9130b57cec5SDimitry Andric     } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
9140b57cec5SDimitry Andric       (void)FD;
9150b57cec5SDimitry Andric       assert(FD->getMostRecentDecl()->isInlined() &&
9160b57cec5SDimitry Andric              "used object requires definition but isn't inline or internal?");
9170b57cec5SDimitry Andric       // FIXME: This is ill-formed; we should reject.
9180b57cec5SDimitry Andric       S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
9190b57cec5SDimitry Andric     } else {
9200b57cec5SDimitry Andric       assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
9210b57cec5SDimitry Andric              "used var requires definition but isn't inline or internal?");
9220b57cec5SDimitry Andric       S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
9230b57cec5SDimitry Andric     }
9240b57cec5SDimitry Andric     if (UseLoc.isValid())
9250b57cec5SDimitry Andric       S.Diag(UseLoc, diag::note_used_here);
9260b57cec5SDimitry Andric   }
9270b57cec5SDimitry Andric }
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric void Sema::LoadExternalWeakUndeclaredIdentifiers() {
9300b57cec5SDimitry Andric   if (!ExternalSource)
9310b57cec5SDimitry Andric     return;
9320b57cec5SDimitry Andric 
9330b57cec5SDimitry Andric   SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
9340b57cec5SDimitry Andric   ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
9350b57cec5SDimitry Andric   for (auto &WeakID : WeakIDs)
93681ad6265SDimitry Andric     (void)WeakUndeclaredIdentifiers[WeakID.first].insert(WeakID.second);
9370b57cec5SDimitry Andric }
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
9410b57cec5SDimitry Andric 
9420b57cec5SDimitry Andric /// Returns true, if all methods and nested classes of the given
9430b57cec5SDimitry Andric /// CXXRecordDecl are defined in this translation unit.
9440b57cec5SDimitry Andric ///
9450b57cec5SDimitry Andric /// Should only be called from ActOnEndOfTranslationUnit so that all
9460b57cec5SDimitry Andric /// definitions are actually read.
9470b57cec5SDimitry Andric static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
9480b57cec5SDimitry Andric                                             RecordCompleteMap &MNCComplete) {
9490b57cec5SDimitry Andric   RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
9500b57cec5SDimitry Andric   if (Cache != MNCComplete.end())
9510b57cec5SDimitry Andric     return Cache->second;
9520b57cec5SDimitry Andric   if (!RD->isCompleteDefinition())
9530b57cec5SDimitry Andric     return false;
9540b57cec5SDimitry Andric   bool Complete = true;
9550b57cec5SDimitry Andric   for (DeclContext::decl_iterator I = RD->decls_begin(),
9560b57cec5SDimitry Andric                                   E = RD->decls_end();
9570b57cec5SDimitry Andric        I != E && Complete; ++I) {
9580b57cec5SDimitry Andric     if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
9590b57cec5SDimitry Andric       Complete = M->isDefined() || M->isDefaulted() ||
9600b57cec5SDimitry Andric                  (M->isPure() && !isa<CXXDestructorDecl>(M));
9610b57cec5SDimitry Andric     else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
9620b57cec5SDimitry Andric       // If the template function is marked as late template parsed at this
9630b57cec5SDimitry Andric       // point, it has not been instantiated and therefore we have not
9640b57cec5SDimitry Andric       // performed semantic analysis on it yet, so we cannot know if the type
9650b57cec5SDimitry Andric       // can be considered complete.
9660b57cec5SDimitry Andric       Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
9670b57cec5SDimitry Andric                   F->getTemplatedDecl()->isDefined();
9680b57cec5SDimitry Andric     else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
9690b57cec5SDimitry Andric       if (R->isInjectedClassName())
9700b57cec5SDimitry Andric         continue;
9710b57cec5SDimitry Andric       if (R->hasDefinition())
9720b57cec5SDimitry Andric         Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
9730b57cec5SDimitry Andric                                                    MNCComplete);
9740b57cec5SDimitry Andric       else
9750b57cec5SDimitry Andric         Complete = false;
9760b57cec5SDimitry Andric     }
9770b57cec5SDimitry Andric   }
9780b57cec5SDimitry Andric   MNCComplete[RD] = Complete;
9790b57cec5SDimitry Andric   return Complete;
9800b57cec5SDimitry Andric }
9810b57cec5SDimitry Andric 
9820b57cec5SDimitry Andric /// Returns true, if the given CXXRecordDecl is fully defined in this
9830b57cec5SDimitry Andric /// translation unit, i.e. all methods are defined or pure virtual and all
9840b57cec5SDimitry Andric /// friends, friend functions and nested classes are fully defined in this
9850b57cec5SDimitry Andric /// translation unit.
9860b57cec5SDimitry Andric ///
9870b57cec5SDimitry Andric /// Should only be called from ActOnEndOfTranslationUnit so that all
9880b57cec5SDimitry Andric /// definitions are actually read.
9890b57cec5SDimitry Andric static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
9900b57cec5SDimitry Andric                                  RecordCompleteMap &RecordsComplete,
9910b57cec5SDimitry Andric                                  RecordCompleteMap &MNCComplete) {
9920b57cec5SDimitry Andric   RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
9930b57cec5SDimitry Andric   if (Cache != RecordsComplete.end())
9940b57cec5SDimitry Andric     return Cache->second;
9950b57cec5SDimitry Andric   bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
9960b57cec5SDimitry Andric   for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
9970b57cec5SDimitry Andric                                       E = RD->friend_end();
9980b57cec5SDimitry Andric        I != E && Complete; ++I) {
9990b57cec5SDimitry Andric     // Check if friend classes and methods are complete.
10000b57cec5SDimitry Andric     if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
10010b57cec5SDimitry Andric       // Friend classes are available as the TypeSourceInfo of the FriendDecl.
10020b57cec5SDimitry Andric       if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
10030b57cec5SDimitry Andric         Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
10040b57cec5SDimitry Andric       else
10050b57cec5SDimitry Andric         Complete = false;
10060b57cec5SDimitry Andric     } else {
10070b57cec5SDimitry Andric       // Friend functions are available through the NamedDecl of FriendDecl.
10080b57cec5SDimitry Andric       if (const FunctionDecl *FD =
10090b57cec5SDimitry Andric           dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
10100b57cec5SDimitry Andric         Complete = FD->isDefined();
10110b57cec5SDimitry Andric       else
10120b57cec5SDimitry Andric         // This is a template friend, give up.
10130b57cec5SDimitry Andric         Complete = false;
10140b57cec5SDimitry Andric     }
10150b57cec5SDimitry Andric   }
10160b57cec5SDimitry Andric   RecordsComplete[RD] = Complete;
10170b57cec5SDimitry Andric   return Complete;
10180b57cec5SDimitry Andric }
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric void Sema::emitAndClearUnusedLocalTypedefWarnings() {
10210b57cec5SDimitry Andric   if (ExternalSource)
10220b57cec5SDimitry Andric     ExternalSource->ReadUnusedLocalTypedefNameCandidates(
10230b57cec5SDimitry Andric         UnusedLocalTypedefNameCandidates);
10240b57cec5SDimitry Andric   for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
10250b57cec5SDimitry Andric     if (TD->isReferenced())
10260b57cec5SDimitry Andric       continue;
10270b57cec5SDimitry Andric     Diag(TD->getLocation(), diag::warn_unused_local_typedef)
10280b57cec5SDimitry Andric         << isa<TypeAliasDecl>(TD) << TD->getDeclName();
10290b57cec5SDimitry Andric   }
10300b57cec5SDimitry Andric   UnusedLocalTypedefNameCandidates.clear();
10310b57cec5SDimitry Andric }
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric /// This is called before the very first declaration in the translation unit
10340b57cec5SDimitry Andric /// is parsed. Note that the ASTContext may have already injected some
10350b57cec5SDimitry Andric /// declarations.
10360b57cec5SDimitry Andric void Sema::ActOnStartOfTranslationUnit() {
103781ad6265SDimitry Andric   if (getLangOpts().CPlusPlusModules &&
103881ad6265SDimitry Andric       getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit)
103981ad6265SDimitry Andric     HandleStartOfHeaderUnit();
10400b57cec5SDimitry Andric }
10410b57cec5SDimitry Andric 
10420b57cec5SDimitry Andric void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {
10430b57cec5SDimitry Andric   // No explicit actions are required at the end of the global module fragment.
10440b57cec5SDimitry Andric   if (Kind == TUFragmentKind::Global)
10450b57cec5SDimitry Andric     return;
10460b57cec5SDimitry Andric 
10470b57cec5SDimitry Andric   // Transfer late parsed template instantiations over to the pending template
10480b57cec5SDimitry Andric   // instantiation list. During normal compilation, the late template parser
10490b57cec5SDimitry Andric   // will be installed and instantiating these templates will succeed.
10500b57cec5SDimitry Andric   //
10510b57cec5SDimitry Andric   // If we are building a TU prefix for serialization, it is also safe to
10520b57cec5SDimitry Andric   // transfer these over, even though they are not parsed. The end of the TU
10530b57cec5SDimitry Andric   // should be outside of any eager template instantiation scope, so when this
10540b57cec5SDimitry Andric   // AST is deserialized, these templates will not be parsed until the end of
10550b57cec5SDimitry Andric   // the combined TU.
10560b57cec5SDimitry Andric   PendingInstantiations.insert(PendingInstantiations.end(),
10570b57cec5SDimitry Andric                                LateParsedInstantiations.begin(),
10580b57cec5SDimitry Andric                                LateParsedInstantiations.end());
10590b57cec5SDimitry Andric   LateParsedInstantiations.clear();
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric   // If DefinedUsedVTables ends up marking any virtual member functions it
10620b57cec5SDimitry Andric   // might lead to more pending template instantiations, which we then need
10630b57cec5SDimitry Andric   // to instantiate.
10640b57cec5SDimitry Andric   DefineUsedVTables();
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric   // C++: Perform implicit template instantiations.
10670b57cec5SDimitry Andric   //
10680b57cec5SDimitry Andric   // FIXME: When we perform these implicit instantiations, we do not
10690b57cec5SDimitry Andric   // carefully keep track of the point of instantiation (C++ [temp.point]).
10700b57cec5SDimitry Andric   // This means that name lookup that occurs within the template
10710b57cec5SDimitry Andric   // instantiation will always happen at the end of the translation unit,
10720b57cec5SDimitry Andric   // so it will find some names that are not required to be found. This is
10730b57cec5SDimitry Andric   // valid, but we could do better by diagnosing if an instantiation uses a
10740b57cec5SDimitry Andric   // name that was not visible at its first point of instantiation.
10750b57cec5SDimitry Andric   if (ExternalSource) {
10760b57cec5SDimitry Andric     // Load pending instantiations from the external source.
10770b57cec5SDimitry Andric     SmallVector<PendingImplicitInstantiation, 4> Pending;
10780b57cec5SDimitry Andric     ExternalSource->ReadPendingInstantiations(Pending);
10790b57cec5SDimitry Andric     for (auto PII : Pending)
10800b57cec5SDimitry Andric       if (auto Func = dyn_cast<FunctionDecl>(PII.first))
10810b57cec5SDimitry Andric         Func->setInstantiationIsPending(true);
10820b57cec5SDimitry Andric     PendingInstantiations.insert(PendingInstantiations.begin(),
10830b57cec5SDimitry Andric                                  Pending.begin(), Pending.end());
10840b57cec5SDimitry Andric   }
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric   {
1087480093f4SDimitry Andric     llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
10880b57cec5SDimitry Andric     PerformPendingInstantiations();
10890b57cec5SDimitry Andric   }
10900b57cec5SDimitry Andric 
10915ffd83dbSDimitry Andric   emitDeferredDiags();
1092a7dea167SDimitry Andric 
10930b57cec5SDimitry Andric   assert(LateParsedInstantiations.empty() &&
10940b57cec5SDimitry Andric          "end of TU template instantiation should not create more "
10950b57cec5SDimitry Andric          "late-parsed templates");
1096a7dea167SDimitry Andric 
1097a7dea167SDimitry Andric   // Report diagnostics for uncorrected delayed typos. Ideally all of them
1098a7dea167SDimitry Andric   // should have been corrected by that time, but it is very hard to cover all
1099a7dea167SDimitry Andric   // cases in practice.
1100a7dea167SDimitry Andric   for (const auto &Typo : DelayedTypos) {
1101a7dea167SDimitry Andric     // We pass an empty TypoCorrection to indicate no correction was performed.
1102a7dea167SDimitry Andric     Typo.second.DiagHandler(TypoCorrection());
1103a7dea167SDimitry Andric   }
1104a7dea167SDimitry Andric   DelayedTypos.clear();
11050b57cec5SDimitry Andric }
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric /// ActOnEndOfTranslationUnit - This is called at the very end of the
11080b57cec5SDimitry Andric /// translation unit when EOF is reached and all but the top-level scope is
11090b57cec5SDimitry Andric /// popped.
11100b57cec5SDimitry Andric void Sema::ActOnEndOfTranslationUnit() {
11110b57cec5SDimitry Andric   assert(DelayedDiagnostics.getCurrentPool() == nullptr
11120b57cec5SDimitry Andric          && "reached end of translation unit with a pool attached?");
11130b57cec5SDimitry Andric 
11140b57cec5SDimitry Andric   // If code completion is enabled, don't perform any end-of-translation-unit
11150b57cec5SDimitry Andric   // work.
11160b57cec5SDimitry Andric   if (PP.isCodeCompletionEnabled())
11170b57cec5SDimitry Andric     return;
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric   // Complete translation units and modules define vtables and perform implicit
11200b57cec5SDimitry Andric   // instantiations. PCH files do not.
11210b57cec5SDimitry Andric   if (TUKind != TU_Prefix) {
11220b57cec5SDimitry Andric     DiagnoseUseOfUnimplementedSelectors();
11230b57cec5SDimitry Andric 
11240b57cec5SDimitry Andric     ActOnEndOfTranslationUnitFragment(
11250b57cec5SDimitry Andric         !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
11260b57cec5SDimitry Andric                                      Module::PrivateModuleFragment
11270b57cec5SDimitry Andric             ? TUFragmentKind::Private
11280b57cec5SDimitry Andric             : TUFragmentKind::Normal);
11290b57cec5SDimitry Andric 
11300b57cec5SDimitry Andric     if (LateTemplateParserCleanup)
11310b57cec5SDimitry Andric       LateTemplateParserCleanup(OpaqueParser);
11320b57cec5SDimitry Andric 
11330b57cec5SDimitry Andric     CheckDelayedMemberExceptionSpecs();
11340b57cec5SDimitry Andric   } else {
11350b57cec5SDimitry Andric     // If we are building a TU prefix for serialization, it is safe to transfer
11360b57cec5SDimitry Andric     // these over, even though they are not parsed. The end of the TU should be
11370b57cec5SDimitry Andric     // outside of any eager template instantiation scope, so when this AST is
11380b57cec5SDimitry Andric     // deserialized, these templates will not be parsed until the end of the
11390b57cec5SDimitry Andric     // combined TU.
11400b57cec5SDimitry Andric     PendingInstantiations.insert(PendingInstantiations.end(),
11410b57cec5SDimitry Andric                                  LateParsedInstantiations.begin(),
11420b57cec5SDimitry Andric                                  LateParsedInstantiations.end());
11430b57cec5SDimitry Andric     LateParsedInstantiations.clear();
11445ffd83dbSDimitry Andric 
11455ffd83dbSDimitry Andric     if (LangOpts.PCHInstantiateTemplates) {
11465ffd83dbSDimitry Andric       llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
11475ffd83dbSDimitry Andric       PerformPendingInstantiations();
11485ffd83dbSDimitry Andric     }
11490b57cec5SDimitry Andric   }
11500b57cec5SDimitry Andric 
1151e8d8bef9SDimitry Andric   DiagnoseUnterminatedPragmaAlignPack();
11520b57cec5SDimitry Andric   DiagnoseUnterminatedPragmaAttribute();
115381ad6265SDimitry Andric   DiagnoseUnterminatedOpenMPDeclareTarget();
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric   // All delayed member exception specs should be checked or we end up accepting
11560b57cec5SDimitry Andric   // incompatible declarations.
11570b57cec5SDimitry Andric   assert(DelayedOverridingExceptionSpecChecks.empty());
11580b57cec5SDimitry Andric   assert(DelayedEquivalentExceptionSpecChecks.empty());
11590b57cec5SDimitry Andric 
11600b57cec5SDimitry Andric   // All dllexport classes should have been processed already.
11610b57cec5SDimitry Andric   assert(DelayedDllExportClasses.empty());
11620b57cec5SDimitry Andric   assert(DelayedDllExportMemberFunctions.empty());
11630b57cec5SDimitry Andric 
11640b57cec5SDimitry Andric   // Remove file scoped decls that turned out to be used.
11650b57cec5SDimitry Andric   UnusedFileScopedDecls.erase(
11660b57cec5SDimitry Andric       std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
11670b57cec5SDimitry Andric                      UnusedFileScopedDecls.end(),
11680b57cec5SDimitry Andric                      [this](const DeclaratorDecl *DD) {
11690b57cec5SDimitry Andric                        return ShouldRemoveFromUnused(this, DD);
11700b57cec5SDimitry Andric                      }),
11710b57cec5SDimitry Andric       UnusedFileScopedDecls.end());
11720b57cec5SDimitry Andric 
11730b57cec5SDimitry Andric   if (TUKind == TU_Prefix) {
11740b57cec5SDimitry Andric     // Translation unit prefixes don't need any of the checking below.
11750b57cec5SDimitry Andric     if (!PP.isIncrementalProcessingEnabled())
11760b57cec5SDimitry Andric       TUScope = nullptr;
11770b57cec5SDimitry Andric     return;
11780b57cec5SDimitry Andric   }
11790b57cec5SDimitry Andric 
11800b57cec5SDimitry Andric   // Check for #pragma weak identifiers that were never declared
11810b57cec5SDimitry Andric   LoadExternalWeakUndeclaredIdentifiers();
118281ad6265SDimitry Andric   for (const auto &WeakIDs : WeakUndeclaredIdentifiers) {
118381ad6265SDimitry Andric     if (WeakIDs.second.empty())
11840b57cec5SDimitry Andric       continue;
11850b57cec5SDimitry Andric 
118681ad6265SDimitry Andric     Decl *PrevDecl = LookupSingleName(TUScope, WeakIDs.first, SourceLocation(),
11870b57cec5SDimitry Andric                                       LookupOrdinaryName);
11880b57cec5SDimitry Andric     if (PrevDecl != nullptr &&
11890b57cec5SDimitry Andric         !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
119081ad6265SDimitry Andric       for (const auto &WI : WeakIDs.second)
119181ad6265SDimitry Andric         Diag(WI.getLocation(), diag::warn_attribute_wrong_decl_type)
119206c3fb27SDimitry Andric             << "'weak'" << /*isRegularKeyword=*/0 << ExpectedVariableOrFunction;
11930b57cec5SDimitry Andric     else
119481ad6265SDimitry Andric       for (const auto &WI : WeakIDs.second)
119581ad6265SDimitry Andric         Diag(WI.getLocation(), diag::warn_weak_identifier_undeclared)
119681ad6265SDimitry Andric             << WeakIDs.first;
11970b57cec5SDimitry Andric   }
11980b57cec5SDimitry Andric 
11990b57cec5SDimitry Andric   if (LangOpts.CPlusPlus11 &&
12000b57cec5SDimitry Andric       !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
12010b57cec5SDimitry Andric     CheckDelegatingCtorCycles();
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric   if (!Diags.hasErrorOccurred()) {
12040b57cec5SDimitry Andric     if (ExternalSource)
12050b57cec5SDimitry Andric       ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
12060b57cec5SDimitry Andric     checkUndefinedButUsed(*this);
12070b57cec5SDimitry Andric   }
12080b57cec5SDimitry Andric 
12090b57cec5SDimitry Andric   // A global-module-fragment is only permitted within a module unit.
12100b57cec5SDimitry Andric   bool DiagnosedMissingModuleDeclaration = false;
121106c3fb27SDimitry Andric   if (!ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
121206c3fb27SDimitry Andric                                    Module::ExplicitGlobalModuleFragment) {
12130b57cec5SDimitry Andric     Diag(ModuleScopes.back().BeginLoc,
12140b57cec5SDimitry Andric          diag::err_module_declaration_missing_after_global_module_introducer);
12150b57cec5SDimitry Andric     DiagnosedMissingModuleDeclaration = true;
12160b57cec5SDimitry Andric   }
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric   if (TUKind == TU_Module) {
12190b57cec5SDimitry Andric     // If we are building a module interface unit, we need to have seen the
12200b57cec5SDimitry Andric     // module declaration by now.
12210b57cec5SDimitry Andric     if (getLangOpts().getCompilingModule() ==
12220b57cec5SDimitry Andric             LangOptions::CMK_ModuleInterface &&
1223bdd1243dSDimitry Andric         !isCurrentModulePurview() && !DiagnosedMissingModuleDeclaration) {
12240b57cec5SDimitry Andric       // FIXME: Make a better guess as to where to put the module declaration.
12250b57cec5SDimitry Andric       Diag(getSourceManager().getLocForStartOfFile(
12260b57cec5SDimitry Andric                getSourceManager().getMainFileID()),
12270b57cec5SDimitry Andric            diag::err_module_declaration_missing);
12280b57cec5SDimitry Andric     }
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric     // If we are building a module, resolve all of the exported declarations
12310b57cec5SDimitry Andric     // now.
12320b57cec5SDimitry Andric     if (Module *CurrentModule = PP.getCurrentModule()) {
12330b57cec5SDimitry Andric       ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric       SmallVector<Module *, 2> Stack;
12360b57cec5SDimitry Andric       Stack.push_back(CurrentModule);
12370b57cec5SDimitry Andric       while (!Stack.empty()) {
12380b57cec5SDimitry Andric         Module *Mod = Stack.pop_back_val();
12390b57cec5SDimitry Andric 
12400b57cec5SDimitry Andric         // Resolve the exported declarations and conflicts.
12410b57cec5SDimitry Andric         // FIXME: Actually complain, once we figure out how to teach the
12420b57cec5SDimitry Andric         // diagnostic client to deal with complaints in the module map at this
12430b57cec5SDimitry Andric         // point.
12440b57cec5SDimitry Andric         ModMap.resolveExports(Mod, /*Complain=*/false);
12450b57cec5SDimitry Andric         ModMap.resolveUses(Mod, /*Complain=*/false);
12460b57cec5SDimitry Andric         ModMap.resolveConflicts(Mod, /*Complain=*/false);
12470b57cec5SDimitry Andric 
12480b57cec5SDimitry Andric         // Queue the submodules, so their exports will also be resolved.
124906c3fb27SDimitry Andric         auto SubmodulesRange = Mod->submodules();
125006c3fb27SDimitry Andric         Stack.append(SubmodulesRange.begin(), SubmodulesRange.end());
12510b57cec5SDimitry Andric       }
12520b57cec5SDimitry Andric     }
12530b57cec5SDimitry Andric 
1254*5f757f3fSDimitry Andric     // Now we can decide whether the modules we're building need an initializer.
1255*5f757f3fSDimitry Andric     if (Module *CurrentModule = getCurrentModule();
1256*5f757f3fSDimitry Andric         CurrentModule && CurrentModule->isInterfaceOrPartition()) {
1257*5f757f3fSDimitry Andric       auto DoesModNeedInit = [this](Module *M) {
1258*5f757f3fSDimitry Andric         if (!getASTContext().getModuleInitializers(M).empty())
1259*5f757f3fSDimitry Andric           return true;
1260*5f757f3fSDimitry Andric         for (auto [Exported, _] : M->Exports)
1261*5f757f3fSDimitry Andric           if (Exported->isNamedModuleInterfaceHasInit())
1262*5f757f3fSDimitry Andric             return true;
1263*5f757f3fSDimitry Andric         for (Module *I : M->Imports)
1264*5f757f3fSDimitry Andric           if (I->isNamedModuleInterfaceHasInit())
1265*5f757f3fSDimitry Andric             return true;
1266*5f757f3fSDimitry Andric 
1267*5f757f3fSDimitry Andric         return false;
1268*5f757f3fSDimitry Andric       };
1269*5f757f3fSDimitry Andric 
1270*5f757f3fSDimitry Andric       CurrentModule->NamedModuleHasInit =
1271*5f757f3fSDimitry Andric           DoesModNeedInit(CurrentModule) ||
1272*5f757f3fSDimitry Andric           llvm::any_of(CurrentModule->submodules(),
1273*5f757f3fSDimitry Andric                        [&](auto *SubM) { return DoesModNeedInit(SubM); });
1274*5f757f3fSDimitry Andric     }
1275*5f757f3fSDimitry Andric 
12760b57cec5SDimitry Andric     // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
12770b57cec5SDimitry Andric     // modules when they are built, not every time they are used.
12780b57cec5SDimitry Andric     emitAndClearUnusedLocalTypedefWarnings();
12790b57cec5SDimitry Andric   }
12800b57cec5SDimitry Andric 
1281bdd1243dSDimitry Andric   // C++ standard modules. Diagnose cases where a function is declared inline
1282bdd1243dSDimitry Andric   // in the module purview but has no definition before the end of the TU or
1283bdd1243dSDimitry Andric   // the start of a Private Module Fragment (if one is present).
1284bdd1243dSDimitry Andric   if (!PendingInlineFuncDecls.empty()) {
1285bdd1243dSDimitry Andric     for (auto *D : PendingInlineFuncDecls) {
1286bdd1243dSDimitry Andric       if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1287bdd1243dSDimitry Andric         bool DefInPMF = false;
1288bdd1243dSDimitry Andric         if (auto *FDD = FD->getDefinition()) {
1289bdd1243dSDimitry Andric           DefInPMF = FDD->getOwningModule()->isPrivateModule();
1290bdd1243dSDimitry Andric           if (!DefInPMF)
1291bdd1243dSDimitry Andric             continue;
1292bdd1243dSDimitry Andric         }
1293bdd1243dSDimitry Andric         Diag(FD->getLocation(), diag::err_export_inline_not_defined)
1294bdd1243dSDimitry Andric             << DefInPMF;
1295bdd1243dSDimitry Andric         // If we have a PMF it should be at the end of the ModuleScopes.
1296bdd1243dSDimitry Andric         if (DefInPMF &&
1297bdd1243dSDimitry Andric             ModuleScopes.back().Module->Kind == Module::PrivateModuleFragment) {
1298bdd1243dSDimitry Andric           Diag(ModuleScopes.back().BeginLoc,
1299bdd1243dSDimitry Andric                diag::note_private_module_fragment);
1300bdd1243dSDimitry Andric         }
1301bdd1243dSDimitry Andric       }
1302bdd1243dSDimitry Andric     }
1303bdd1243dSDimitry Andric     PendingInlineFuncDecls.clear();
1304bdd1243dSDimitry Andric   }
1305bdd1243dSDimitry Andric 
13060b57cec5SDimitry Andric   // C99 6.9.2p2:
13070b57cec5SDimitry Andric   //   A declaration of an identifier for an object that has file
13080b57cec5SDimitry Andric   //   scope without an initializer, and without a storage-class
13090b57cec5SDimitry Andric   //   specifier or with the storage-class specifier static,
13100b57cec5SDimitry Andric   //   constitutes a tentative definition. If a translation unit
13110b57cec5SDimitry Andric   //   contains one or more tentative definitions for an identifier,
13120b57cec5SDimitry Andric   //   and the translation unit contains no external definition for
13130b57cec5SDimitry Andric   //   that identifier, then the behavior is exactly as if the
13140b57cec5SDimitry Andric   //   translation unit contains a file scope declaration of that
13150b57cec5SDimitry Andric   //   identifier, with the composite type as of the end of the
13160b57cec5SDimitry Andric   //   translation unit, with an initializer equal to 0.
13170b57cec5SDimitry Andric   llvm::SmallSet<VarDecl *, 32> Seen;
13180b57cec5SDimitry Andric   for (TentativeDefinitionsType::iterator
1319bdd1243dSDimitry Andric            T = TentativeDefinitions.begin(ExternalSource.get()),
13200b57cec5SDimitry Andric            TEnd = TentativeDefinitions.end();
13210b57cec5SDimitry Andric        T != TEnd; ++T) {
13220b57cec5SDimitry Andric     VarDecl *VD = (*T)->getActingDefinition();
13230b57cec5SDimitry Andric 
13240b57cec5SDimitry Andric     // If the tentative definition was completed, getActingDefinition() returns
13250b57cec5SDimitry Andric     // null. If we've already seen this variable before, insert()'s second
13260b57cec5SDimitry Andric     // return value is false.
13270b57cec5SDimitry Andric     if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
13280b57cec5SDimitry Andric       continue;
13290b57cec5SDimitry Andric 
13300b57cec5SDimitry Andric     if (const IncompleteArrayType *ArrayT
13310b57cec5SDimitry Andric         = Context.getAsIncompleteArrayType(VD->getType())) {
13320b57cec5SDimitry Andric       // Set the length of the array to 1 (C99 6.9.2p5).
13330b57cec5SDimitry Andric       Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
13340b57cec5SDimitry Andric       llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
1335*5f757f3fSDimitry Andric       QualType T = Context.getConstantArrayType(
1336*5f757f3fSDimitry Andric           ArrayT->getElementType(), One, nullptr, ArraySizeModifier::Normal, 0);
13370b57cec5SDimitry Andric       VD->setType(T);
13380b57cec5SDimitry Andric     } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
13390b57cec5SDimitry Andric                                    diag::err_tentative_def_incomplete_type))
13400b57cec5SDimitry Andric       VD->setInvalidDecl();
13410b57cec5SDimitry Andric 
13420b57cec5SDimitry Andric     // No initialization is performed for a tentative definition.
13430b57cec5SDimitry Andric     CheckCompleteVariableDeclaration(VD);
13440b57cec5SDimitry Andric 
13450b57cec5SDimitry Andric     // Notify the consumer that we've completed a tentative definition.
13460b57cec5SDimitry Andric     if (!VD->isInvalidDecl())
13470b57cec5SDimitry Andric       Consumer.CompleteTentativeDefinition(VD);
13480b57cec5SDimitry Andric   }
13490b57cec5SDimitry Andric 
1350bdd1243dSDimitry Andric   for (auto *D : ExternalDeclarations) {
1351480093f4SDimitry Andric     if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())
1352480093f4SDimitry Andric       continue;
1353480093f4SDimitry Andric 
1354480093f4SDimitry Andric     Consumer.CompleteExternalDeclaration(D);
1355480093f4SDimitry Andric   }
1356480093f4SDimitry Andric 
13570b57cec5SDimitry Andric   // If there were errors, disable 'unused' warnings since they will mostly be
13580b57cec5SDimitry Andric   // noise. Don't warn for a use from a module: either we should warn on all
13590b57cec5SDimitry Andric   // file-scope declarations in modules or not at all, but whether the
13600b57cec5SDimitry Andric   // declaration is used is immaterial.
13610b57cec5SDimitry Andric   if (!Diags.hasErrorOccurred() && TUKind != TU_Module) {
13620b57cec5SDimitry Andric     // Output warning for unused file scoped decls.
13630b57cec5SDimitry Andric     for (UnusedFileScopedDeclsType::iterator
1364bdd1243dSDimitry Andric              I = UnusedFileScopedDecls.begin(ExternalSource.get()),
1365bdd1243dSDimitry Andric              E = UnusedFileScopedDecls.end();
1366bdd1243dSDimitry Andric          I != E; ++I) {
13670b57cec5SDimitry Andric       if (ShouldRemoveFromUnused(this, *I))
13680b57cec5SDimitry Andric         continue;
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
13710b57cec5SDimitry Andric         const FunctionDecl *DiagD;
13720b57cec5SDimitry Andric         if (!FD->hasBody(DiagD))
13730b57cec5SDimitry Andric           DiagD = FD;
13740b57cec5SDimitry Andric         if (DiagD->isDeleted())
13750b57cec5SDimitry Andric           continue; // Deleted functions are supposed to be unused.
137606c3fb27SDimitry Andric         SourceRange DiagRange = DiagD->getLocation();
137706c3fb27SDimitry Andric         if (const ASTTemplateArgumentListInfo *ASTTAL =
137806c3fb27SDimitry Andric                 DiagD->getTemplateSpecializationArgsAsWritten())
137906c3fb27SDimitry Andric           DiagRange.setEnd(ASTTAL->RAngleLoc);
13800b57cec5SDimitry Andric         if (DiagD->isReferenced()) {
13810b57cec5SDimitry Andric           if (isa<CXXMethodDecl>(DiagD))
13820b57cec5SDimitry Andric             Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
138306c3fb27SDimitry Andric                 << DiagD << DiagRange;
13840b57cec5SDimitry Andric           else {
13850b57cec5SDimitry Andric             if (FD->getStorageClass() == SC_Static &&
13860b57cec5SDimitry Andric                 !FD->isInlineSpecified() &&
13870b57cec5SDimitry Andric                 !SourceMgr.isInMainFile(
13880b57cec5SDimitry Andric                    SourceMgr.getExpansionLoc(FD->getLocation())))
13890b57cec5SDimitry Andric               Diag(DiagD->getLocation(),
13900b57cec5SDimitry Andric                    diag::warn_unneeded_static_internal_decl)
139106c3fb27SDimitry Andric                   << DiagD << DiagRange;
13920b57cec5SDimitry Andric             else
13930b57cec5SDimitry Andric               Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
139406c3fb27SDimitry Andric                   << /*function=*/0 << DiagD << DiagRange;
13950b57cec5SDimitry Andric           }
13960b57cec5SDimitry Andric         } else {
13970b57cec5SDimitry Andric           if (FD->getDescribedFunctionTemplate())
13980b57cec5SDimitry Andric             Diag(DiagD->getLocation(), diag::warn_unused_template)
139906c3fb27SDimitry Andric                 << /*function=*/0 << DiagD << DiagRange;
14000b57cec5SDimitry Andric           else
1401e8d8bef9SDimitry Andric             Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)
1402e8d8bef9SDimitry Andric                                            ? diag::warn_unused_member_function
14030b57cec5SDimitry Andric                                            : diag::warn_unused_function)
140406c3fb27SDimitry Andric                 << DiagD << DiagRange;
14050b57cec5SDimitry Andric         }
14060b57cec5SDimitry Andric       } else {
14070b57cec5SDimitry Andric         const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
14080b57cec5SDimitry Andric         if (!DiagD)
14090b57cec5SDimitry Andric           DiagD = cast<VarDecl>(*I);
141006c3fb27SDimitry Andric         SourceRange DiagRange = DiagD->getLocation();
141106c3fb27SDimitry Andric         if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(DiagD)) {
141206c3fb27SDimitry Andric           if (const ASTTemplateArgumentListInfo *ASTTAL =
141306c3fb27SDimitry Andric                   VTSD->getTemplateArgsInfo())
141406c3fb27SDimitry Andric             DiagRange.setEnd(ASTTAL->RAngleLoc);
141506c3fb27SDimitry Andric         }
14160b57cec5SDimitry Andric         if (DiagD->isReferenced()) {
14170b57cec5SDimitry Andric           Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
141806c3fb27SDimitry Andric               << /*variable=*/1 << DiagD << DiagRange;
141906c3fb27SDimitry Andric         } else if (DiagD->getDescribedVarTemplate()) {
142006c3fb27SDimitry Andric           Diag(DiagD->getLocation(), diag::warn_unused_template)
142106c3fb27SDimitry Andric               << /*variable=*/1 << DiagD << DiagRange;
14220b57cec5SDimitry Andric         } else if (DiagD->getType().isConstQualified()) {
14230b57cec5SDimitry Andric           const SourceManager &SM = SourceMgr;
14240b57cec5SDimitry Andric           if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
14250b57cec5SDimitry Andric               !PP.getLangOpts().IsHeaderFile)
14260b57cec5SDimitry Andric             Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
142706c3fb27SDimitry Andric                 << DiagD << DiagRange;
14280b57cec5SDimitry Andric         } else {
142906c3fb27SDimitry Andric           Diag(DiagD->getLocation(), diag::warn_unused_variable)
143006c3fb27SDimitry Andric               << DiagD << DiagRange;
14310b57cec5SDimitry Andric         }
14320b57cec5SDimitry Andric       }
14330b57cec5SDimitry Andric     }
14340b57cec5SDimitry Andric 
14350b57cec5SDimitry Andric     emitAndClearUnusedLocalTypedefWarnings();
14360b57cec5SDimitry Andric   }
14370b57cec5SDimitry Andric 
14380b57cec5SDimitry Andric   if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
14390b57cec5SDimitry Andric     // FIXME: Load additional unused private field candidates from the external
14400b57cec5SDimitry Andric     // source.
14410b57cec5SDimitry Andric     RecordCompleteMap RecordsComplete;
14420b57cec5SDimitry Andric     RecordCompleteMap MNCComplete;
144306c3fb27SDimitry Andric     for (const NamedDecl *D : UnusedPrivateFields) {
14440b57cec5SDimitry Andric       const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
14450b57cec5SDimitry Andric       if (RD && !RD->isUnion() &&
14460b57cec5SDimitry Andric           IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
14470b57cec5SDimitry Andric         Diag(D->getLocation(), diag::warn_unused_private_field)
14480b57cec5SDimitry Andric               << D->getDeclName();
14490b57cec5SDimitry Andric       }
14500b57cec5SDimitry Andric     }
14510b57cec5SDimitry Andric   }
14520b57cec5SDimitry Andric 
14530b57cec5SDimitry Andric   if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
14540b57cec5SDimitry Andric     if (ExternalSource)
14550b57cec5SDimitry Andric       ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
14560b57cec5SDimitry Andric     for (const auto &DeletedFieldInfo : DeleteExprs) {
14570b57cec5SDimitry Andric       for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
14580b57cec5SDimitry Andric         AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
14590b57cec5SDimitry Andric                                   DeleteExprLoc.second);
14600b57cec5SDimitry Andric       }
14610b57cec5SDimitry Andric     }
14620b57cec5SDimitry Andric   }
14630b57cec5SDimitry Andric 
146406c3fb27SDimitry Andric   AnalysisWarnings.IssueWarnings(Context.getTranslationUnitDecl());
146506c3fb27SDimitry Andric 
14660b57cec5SDimitry Andric   // Check we've noticed that we're no longer parsing the initializer for every
14670b57cec5SDimitry Andric   // variable. If we miss cases, then at best we have a performance issue and
14680b57cec5SDimitry Andric   // at worst a rejects-valid bug.
14690b57cec5SDimitry Andric   assert(ParsingInitForAutoVars.empty() &&
14700b57cec5SDimitry Andric          "Didn't unmark var as having its initializer parsed");
14710b57cec5SDimitry Andric 
14720b57cec5SDimitry Andric   if (!PP.isIncrementalProcessingEnabled())
14730b57cec5SDimitry Andric     TUScope = nullptr;
14740b57cec5SDimitry Andric }
14750b57cec5SDimitry Andric 
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
14780b57cec5SDimitry Andric // Helper functions.
14790b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
14800b57cec5SDimitry Andric 
148106c3fb27SDimitry Andric DeclContext *Sema::getFunctionLevelDeclContext(bool AllowLambda) const {
14820b57cec5SDimitry Andric   DeclContext *DC = CurContext;
14830b57cec5SDimitry Andric 
14840b57cec5SDimitry Andric   while (true) {
148555e4f9d5SDimitry Andric     if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) ||
148655e4f9d5SDimitry Andric         isa<RequiresExprBodyDecl>(DC)) {
14870b57cec5SDimitry Andric       DC = DC->getParent();
148881ad6265SDimitry Andric     } else if (!AllowLambda && isa<CXXMethodDecl>(DC) &&
14890b57cec5SDimitry Andric                cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
14900b57cec5SDimitry Andric                cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
14910b57cec5SDimitry Andric       DC = DC->getParent()->getParent();
149281ad6265SDimitry Andric     } else break;
14930b57cec5SDimitry Andric   }
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric   return DC;
14960b57cec5SDimitry Andric }
14970b57cec5SDimitry Andric 
14980b57cec5SDimitry Andric /// getCurFunctionDecl - If inside of a function body, this returns a pointer
14990b57cec5SDimitry Andric /// to the function decl for the function being parsed.  If we're currently
15000b57cec5SDimitry Andric /// in a 'block', this returns the containing context.
150106c3fb27SDimitry Andric FunctionDecl *Sema::getCurFunctionDecl(bool AllowLambda) const {
150281ad6265SDimitry Andric   DeclContext *DC = getFunctionLevelDeclContext(AllowLambda);
15030b57cec5SDimitry Andric   return dyn_cast<FunctionDecl>(DC);
15040b57cec5SDimitry Andric }
15050b57cec5SDimitry Andric 
15060b57cec5SDimitry Andric ObjCMethodDecl *Sema::getCurMethodDecl() {
15070b57cec5SDimitry Andric   DeclContext *DC = getFunctionLevelDeclContext();
15080b57cec5SDimitry Andric   while (isa<RecordDecl>(DC))
15090b57cec5SDimitry Andric     DC = DC->getParent();
15100b57cec5SDimitry Andric   return dyn_cast<ObjCMethodDecl>(DC);
15110b57cec5SDimitry Andric }
15120b57cec5SDimitry Andric 
151306c3fb27SDimitry Andric NamedDecl *Sema::getCurFunctionOrMethodDecl() const {
15140b57cec5SDimitry Andric   DeclContext *DC = getFunctionLevelDeclContext();
15150b57cec5SDimitry Andric   if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
15160b57cec5SDimitry Andric     return cast<NamedDecl>(DC);
15170b57cec5SDimitry Andric   return nullptr;
15180b57cec5SDimitry Andric }
15190b57cec5SDimitry Andric 
1520480093f4SDimitry Andric LangAS Sema::getDefaultCXXMethodAddrSpace() const {
1521480093f4SDimitry Andric   if (getLangOpts().OpenCL)
1522349cc55cSDimitry Andric     return getASTContext().getDefaultOpenCLPointeeAddrSpace();
1523480093f4SDimitry Andric   return LangAS::Default;
1524480093f4SDimitry Andric }
1525480093f4SDimitry Andric 
15260b57cec5SDimitry Andric void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
15270b57cec5SDimitry Andric   // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
15280b57cec5SDimitry Andric   // and yet we also use the current diag ID on the DiagnosticsEngine. This has
15290b57cec5SDimitry Andric   // been made more painfully obvious by the refactor that introduced this
15300b57cec5SDimitry Andric   // function, but it is possible that the incoming argument can be
15310b57cec5SDimitry Andric   // eliminated. If it truly cannot be (for example, there is some reentrancy
15320b57cec5SDimitry Andric   // issue I am not seeing yet), then there should at least be a clarifying
15330b57cec5SDimitry Andric   // comment somewhere.
1534bdd1243dSDimitry Andric   if (std::optional<TemplateDeductionInfo *> Info = isSFINAEContext()) {
15350b57cec5SDimitry Andric     switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
15360b57cec5SDimitry Andric               Diags.getCurrentDiagID())) {
15370b57cec5SDimitry Andric     case DiagnosticIDs::SFINAE_Report:
15380b57cec5SDimitry Andric       // We'll report the diagnostic below.
15390b57cec5SDimitry Andric       break;
15400b57cec5SDimitry Andric 
15410b57cec5SDimitry Andric     case DiagnosticIDs::SFINAE_SubstitutionFailure:
15420b57cec5SDimitry Andric       // Count this failure so that we know that template argument deduction
15430b57cec5SDimitry Andric       // has failed.
15440b57cec5SDimitry Andric       ++NumSFINAEErrors;
15450b57cec5SDimitry Andric 
15460b57cec5SDimitry Andric       // Make a copy of this suppressed diagnostic and store it with the
15470b57cec5SDimitry Andric       // template-deduction information.
15480b57cec5SDimitry Andric       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
15490b57cec5SDimitry Andric         Diagnostic DiagInfo(&Diags);
15500b57cec5SDimitry Andric         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
15510b57cec5SDimitry Andric                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
15520b57cec5SDimitry Andric       }
15530b57cec5SDimitry Andric 
1554a7dea167SDimitry Andric       Diags.setLastDiagnosticIgnored(true);
15550b57cec5SDimitry Andric       Diags.Clear();
15560b57cec5SDimitry Andric       return;
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric     case DiagnosticIDs::SFINAE_AccessControl: {
15590b57cec5SDimitry Andric       // Per C++ Core Issue 1170, access control is part of SFINAE.
15600b57cec5SDimitry Andric       // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
15610b57cec5SDimitry Andric       // make access control a part of SFINAE for the purposes of checking
15620b57cec5SDimitry Andric       // type traits.
15630b57cec5SDimitry Andric       if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
15640b57cec5SDimitry Andric         break;
15650b57cec5SDimitry Andric 
15660b57cec5SDimitry Andric       SourceLocation Loc = Diags.getCurrentDiagLoc();
15670b57cec5SDimitry Andric 
15680b57cec5SDimitry Andric       // Suppress this diagnostic.
15690b57cec5SDimitry Andric       ++NumSFINAEErrors;
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric       // Make a copy of this suppressed diagnostic and store it with the
15720b57cec5SDimitry Andric       // template-deduction information.
15730b57cec5SDimitry Andric       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
15740b57cec5SDimitry Andric         Diagnostic DiagInfo(&Diags);
15750b57cec5SDimitry Andric         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
15760b57cec5SDimitry Andric                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
15770b57cec5SDimitry Andric       }
15780b57cec5SDimitry Andric 
1579a7dea167SDimitry Andric       Diags.setLastDiagnosticIgnored(true);
15800b57cec5SDimitry Andric       Diags.Clear();
15810b57cec5SDimitry Andric 
15820b57cec5SDimitry Andric       // Now the diagnostic state is clear, produce a C++98 compatibility
15830b57cec5SDimitry Andric       // warning.
15840b57cec5SDimitry Andric       Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
15850b57cec5SDimitry Andric 
15860b57cec5SDimitry Andric       // The last diagnostic which Sema produced was ignored. Suppress any
15870b57cec5SDimitry Andric       // notes attached to it.
1588a7dea167SDimitry Andric       Diags.setLastDiagnosticIgnored(true);
15890b57cec5SDimitry Andric       return;
15900b57cec5SDimitry Andric     }
15910b57cec5SDimitry Andric 
15920b57cec5SDimitry Andric     case DiagnosticIDs::SFINAE_Suppress:
15930b57cec5SDimitry Andric       // Make a copy of this suppressed diagnostic and store it with the
15940b57cec5SDimitry Andric       // template-deduction information;
15950b57cec5SDimitry Andric       if (*Info) {
15960b57cec5SDimitry Andric         Diagnostic DiagInfo(&Diags);
15970b57cec5SDimitry Andric         (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
15980b57cec5SDimitry Andric                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
15990b57cec5SDimitry Andric       }
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric       // Suppress this diagnostic.
1602a7dea167SDimitry Andric       Diags.setLastDiagnosticIgnored(true);
16030b57cec5SDimitry Andric       Diags.Clear();
16040b57cec5SDimitry Andric       return;
16050b57cec5SDimitry Andric     }
16060b57cec5SDimitry Andric   }
16070b57cec5SDimitry Andric 
16080b57cec5SDimitry Andric   // Copy the diagnostic printing policy over the ASTContext printing policy.
16090b57cec5SDimitry Andric   // TODO: Stop doing that.  See: https://reviews.llvm.org/D45093#1090292
16100b57cec5SDimitry Andric   Context.setPrintingPolicy(getPrintingPolicy());
16110b57cec5SDimitry Andric 
16120b57cec5SDimitry Andric   // Emit the diagnostic.
16130b57cec5SDimitry Andric   if (!Diags.EmitCurrentDiagnostic())
16140b57cec5SDimitry Andric     return;
16150b57cec5SDimitry Andric 
16160b57cec5SDimitry Andric   // If this is not a note, and we're in a template instantiation
16170b57cec5SDimitry Andric   // that is different from the last template instantiation where
16180b57cec5SDimitry Andric   // we emitted an error, print a template instantiation
16190b57cec5SDimitry Andric   // backtrace.
16200b57cec5SDimitry Andric   if (!DiagnosticIDs::isBuiltinNote(DiagID))
16210b57cec5SDimitry Andric     PrintContextStack();
16220b57cec5SDimitry Andric }
16230b57cec5SDimitry Andric 
16240b57cec5SDimitry Andric Sema::SemaDiagnosticBuilder
1625e8d8bef9SDimitry Andric Sema::Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint) {
1626e8d8bef9SDimitry Andric   return Diag(Loc, PD.getDiagID(), DeferHint) << PD;
1627e8d8bef9SDimitry Andric }
16280b57cec5SDimitry Andric 
1629e8d8bef9SDimitry Andric bool Sema::hasUncompilableErrorOccurred() const {
1630e8d8bef9SDimitry Andric   if (getDiagnostics().hasUncompilableErrorOccurred())
1631e8d8bef9SDimitry Andric     return true;
1632e8d8bef9SDimitry Andric   auto *FD = dyn_cast<FunctionDecl>(CurContext);
1633e8d8bef9SDimitry Andric   if (!FD)
1634e8d8bef9SDimitry Andric     return false;
1635e8d8bef9SDimitry Andric   auto Loc = DeviceDeferredDiags.find(FD);
1636e8d8bef9SDimitry Andric   if (Loc == DeviceDeferredDiags.end())
1637e8d8bef9SDimitry Andric     return false;
1638e8d8bef9SDimitry Andric   for (auto PDAt : Loc->second) {
1639e8d8bef9SDimitry Andric     if (DiagnosticIDs::isDefaultMappingAsError(PDAt.second.getDiagID()))
1640e8d8bef9SDimitry Andric       return true;
1641e8d8bef9SDimitry Andric   }
1642e8d8bef9SDimitry Andric   return false;
16430b57cec5SDimitry Andric }
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric // Print notes showing how we can reach FD starting from an a priori
16460b57cec5SDimitry Andric // known-callable function.
164706c3fb27SDimitry Andric static void emitCallStackNotes(Sema &S, const FunctionDecl *FD) {
16480b57cec5SDimitry Andric   auto FnIt = S.DeviceKnownEmittedFns.find(FD);
16490b57cec5SDimitry Andric   while (FnIt != S.DeviceKnownEmittedFns.end()) {
16505ffd83dbSDimitry Andric     // Respect error limit.
16515ffd83dbSDimitry Andric     if (S.Diags.hasFatalErrorOccurred())
16525ffd83dbSDimitry Andric       return;
16530b57cec5SDimitry Andric     DiagnosticBuilder Builder(
16540b57cec5SDimitry Andric         S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
16550b57cec5SDimitry Andric     Builder << FnIt->second.FD;
16560b57cec5SDimitry Andric     FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD);
16570b57cec5SDimitry Andric   }
16580b57cec5SDimitry Andric }
16590b57cec5SDimitry Andric 
16605ffd83dbSDimitry Andric namespace {
16615ffd83dbSDimitry Andric 
16625ffd83dbSDimitry Andric /// Helper class that emits deferred diagnostic messages if an entity directly
16635ffd83dbSDimitry Andric /// or indirectly using the function that causes the deferred diagnostic
16645ffd83dbSDimitry Andric /// messages is known to be emitted.
16655ffd83dbSDimitry Andric ///
16665ffd83dbSDimitry Andric /// During parsing of AST, certain diagnostic messages are recorded as deferred
16675ffd83dbSDimitry Andric /// diagnostics since it is unknown whether the functions containing such
16685ffd83dbSDimitry Andric /// diagnostics will be emitted. A list of potentially emitted functions and
16695ffd83dbSDimitry Andric /// variables that may potentially trigger emission of functions are also
16705ffd83dbSDimitry Andric /// recorded. DeferredDiagnosticsEmitter recursively visits used functions
16715ffd83dbSDimitry Andric /// by each function to emit deferred diagnostics.
16725ffd83dbSDimitry Andric ///
16735ffd83dbSDimitry Andric /// During the visit, certain OpenMP directives or initializer of variables
16745ffd83dbSDimitry Andric /// with certain OpenMP attributes will cause subsequent visiting of any
16755ffd83dbSDimitry Andric /// functions enter a state which is called OpenMP device context in this
16765ffd83dbSDimitry Andric /// implementation. The state is exited when the directive or initializer is
16775ffd83dbSDimitry Andric /// exited. This state can change the emission states of subsequent uses
16785ffd83dbSDimitry Andric /// of functions.
16795ffd83dbSDimitry Andric ///
16805ffd83dbSDimitry Andric /// Conceptually the functions or variables to be visited form a use graph
16815ffd83dbSDimitry Andric /// where the parent node uses the child node. At any point of the visit,
16825ffd83dbSDimitry Andric /// the tree nodes traversed from the tree root to the current node form a use
16835ffd83dbSDimitry Andric /// stack. The emission state of the current node depends on two factors:
16845ffd83dbSDimitry Andric ///    1. the emission state of the root node
16855ffd83dbSDimitry Andric ///    2. whether the current node is in OpenMP device context
16865ffd83dbSDimitry Andric /// If the function is decided to be emitted, its contained deferred diagnostics
16875ffd83dbSDimitry Andric /// are emitted, together with the information about the use stack.
16885ffd83dbSDimitry Andric ///
16895ffd83dbSDimitry Andric class DeferredDiagnosticsEmitter
16905ffd83dbSDimitry Andric     : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
16915ffd83dbSDimitry Andric public:
16925ffd83dbSDimitry Andric   typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited;
16935ffd83dbSDimitry Andric 
16945ffd83dbSDimitry Andric   // Whether the function is already in the current use-path.
1695e8d8bef9SDimitry Andric   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath;
16965ffd83dbSDimitry Andric 
16975ffd83dbSDimitry Andric   // The current use-path.
16985ffd83dbSDimitry Andric   llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath;
16995ffd83dbSDimitry Andric 
17005ffd83dbSDimitry Andric   // Whether the visiting of the function has been done. Done[0] is for the
17015ffd83dbSDimitry Andric   // case not in OpenMP device context. Done[1] is for the case in OpenMP
17025ffd83dbSDimitry Andric   // device context. We need two sets because diagnostics emission may be
17035ffd83dbSDimitry Andric   // different depending on whether it is in OpenMP device context.
1704e8d8bef9SDimitry Andric   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2];
17055ffd83dbSDimitry Andric 
17065ffd83dbSDimitry Andric   // Emission state of the root node of the current use graph.
17075ffd83dbSDimitry Andric   bool ShouldEmitRootNode;
17085ffd83dbSDimitry Andric 
17095ffd83dbSDimitry Andric   // Current OpenMP device context level. It is initialized to 0 and each
17105ffd83dbSDimitry Andric   // entering of device context increases it by 1 and each exit decreases
17115ffd83dbSDimitry Andric   // it by 1. Non-zero value indicates it is currently in device context.
17125ffd83dbSDimitry Andric   unsigned InOMPDeviceContext;
17135ffd83dbSDimitry Andric 
17145ffd83dbSDimitry Andric   DeferredDiagnosticsEmitter(Sema &S)
17155ffd83dbSDimitry Andric       : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
17165ffd83dbSDimitry Andric 
1717fe6060f1SDimitry Andric   bool shouldVisitDiscardedStmt() const { return false; }
1718fe6060f1SDimitry Andric 
17195ffd83dbSDimitry Andric   void VisitOMPTargetDirective(OMPTargetDirective *Node) {
17205ffd83dbSDimitry Andric     ++InOMPDeviceContext;
17215ffd83dbSDimitry Andric     Inherited::VisitOMPTargetDirective(Node);
17225ffd83dbSDimitry Andric     --InOMPDeviceContext;
17235ffd83dbSDimitry Andric   }
17245ffd83dbSDimitry Andric 
17255ffd83dbSDimitry Andric   void visitUsedDecl(SourceLocation Loc, Decl *D) {
17265ffd83dbSDimitry Andric     if (isa<VarDecl>(D))
17275ffd83dbSDimitry Andric       return;
17285ffd83dbSDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D))
17295ffd83dbSDimitry Andric       checkFunc(Loc, FD);
17305ffd83dbSDimitry Andric     else
17315ffd83dbSDimitry Andric       Inherited::visitUsedDecl(Loc, D);
17325ffd83dbSDimitry Andric   }
17335ffd83dbSDimitry Andric 
17345ffd83dbSDimitry Andric   void checkVar(VarDecl *VD) {
17355ffd83dbSDimitry Andric     assert(VD->isFileVarDecl() &&
17365ffd83dbSDimitry Andric            "Should only check file-scope variables");
17375ffd83dbSDimitry Andric     if (auto *Init = VD->getInit()) {
17385ffd83dbSDimitry Andric       auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
17395ffd83dbSDimitry Andric       bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
17405ffd83dbSDimitry Andric                              *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
17415ffd83dbSDimitry Andric       if (IsDev)
17425ffd83dbSDimitry Andric         ++InOMPDeviceContext;
17435ffd83dbSDimitry Andric       this->Visit(Init);
17445ffd83dbSDimitry Andric       if (IsDev)
17455ffd83dbSDimitry Andric         --InOMPDeviceContext;
17465ffd83dbSDimitry Andric     }
17475ffd83dbSDimitry Andric   }
17485ffd83dbSDimitry Andric 
17495ffd83dbSDimitry Andric   void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
17505ffd83dbSDimitry Andric     auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];
17515ffd83dbSDimitry Andric     FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back();
17525ffd83dbSDimitry Andric     if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||
17535ffd83dbSDimitry Andric         S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD))
17545ffd83dbSDimitry Andric       return;
17555ffd83dbSDimitry Andric     // Finalize analysis of OpenMP-specific constructs.
1756e8d8bef9SDimitry Andric     if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 &&
1757e8d8bef9SDimitry Andric         (ShouldEmitRootNode || InOMPDeviceContext))
17585ffd83dbSDimitry Andric       S.finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
17595ffd83dbSDimitry Andric     if (Caller)
17605ffd83dbSDimitry Andric       S.DeviceKnownEmittedFns[FD] = {Caller, Loc};
17615ffd83dbSDimitry Andric     // Always emit deferred diagnostics for the direct users. This does not
17625ffd83dbSDimitry Andric     // lead to explosion of diagnostics since each user is visited at most
17635ffd83dbSDimitry Andric     // twice.
17645ffd83dbSDimitry Andric     if (ShouldEmitRootNode || InOMPDeviceContext)
17655ffd83dbSDimitry Andric       emitDeferredDiags(FD, Caller);
17665ffd83dbSDimitry Andric     // Do not revisit a function if the function body has been completely
17675ffd83dbSDimitry Andric     // visited before.
17685ffd83dbSDimitry Andric     if (!Done.insert(FD).second)
17695ffd83dbSDimitry Andric       return;
17705ffd83dbSDimitry Andric     InUsePath.insert(FD);
17715ffd83dbSDimitry Andric     UsePath.push_back(FD);
17725ffd83dbSDimitry Andric     if (auto *S = FD->getBody()) {
17735ffd83dbSDimitry Andric       this->Visit(S);
17745ffd83dbSDimitry Andric     }
17755ffd83dbSDimitry Andric     UsePath.pop_back();
17765ffd83dbSDimitry Andric     InUsePath.erase(FD);
17775ffd83dbSDimitry Andric   }
17785ffd83dbSDimitry Andric 
17795ffd83dbSDimitry Andric   void checkRecordedDecl(Decl *D) {
17805ffd83dbSDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
17815ffd83dbSDimitry Andric       ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
17825ffd83dbSDimitry Andric                            Sema::FunctionEmissionStatus::Emitted;
17835ffd83dbSDimitry Andric       checkFunc(SourceLocation(), FD);
17845ffd83dbSDimitry Andric     } else
17855ffd83dbSDimitry Andric       checkVar(cast<VarDecl>(D));
17865ffd83dbSDimitry Andric   }
17875ffd83dbSDimitry Andric 
17885ffd83dbSDimitry Andric   // Emit any deferred diagnostics for FD
17895ffd83dbSDimitry Andric   void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) {
17900b57cec5SDimitry Andric     auto It = S.DeviceDeferredDiags.find(FD);
17910b57cec5SDimitry Andric     if (It == S.DeviceDeferredDiags.end())
17920b57cec5SDimitry Andric       return;
17930b57cec5SDimitry Andric     bool HasWarningOrError = false;
17945ffd83dbSDimitry Andric     bool FirstDiag = true;
17950b57cec5SDimitry Andric     for (PartialDiagnosticAt &PDAt : It->second) {
17965ffd83dbSDimitry Andric       // Respect error limit.
17975ffd83dbSDimitry Andric       if (S.Diags.hasFatalErrorOccurred())
17985ffd83dbSDimitry Andric         return;
17990b57cec5SDimitry Andric       const SourceLocation &Loc = PDAt.first;
18000b57cec5SDimitry Andric       const PartialDiagnostic &PD = PDAt.second;
18015ffd83dbSDimitry Andric       HasWarningOrError |=
18025ffd83dbSDimitry Andric           S.getDiagnostics().getDiagnosticLevel(PD.getDiagID(), Loc) >=
18035ffd83dbSDimitry Andric           DiagnosticsEngine::Warning;
18045ffd83dbSDimitry Andric       {
18050b57cec5SDimitry Andric         DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
18060b57cec5SDimitry Andric         PD.Emit(Builder);
18070b57cec5SDimitry Andric       }
18085ffd83dbSDimitry Andric       // Emit the note on the first diagnostic in case too many diagnostics
18095ffd83dbSDimitry Andric       // cause the note not emitted.
18105ffd83dbSDimitry Andric       if (FirstDiag && HasWarningOrError && ShowCallStack) {
18110b57cec5SDimitry Andric         emitCallStackNotes(S, FD);
18125ffd83dbSDimitry Andric         FirstDiag = false;
18135ffd83dbSDimitry Andric       }
18145ffd83dbSDimitry Andric     }
18155ffd83dbSDimitry Andric   }
18165ffd83dbSDimitry Andric };
18175ffd83dbSDimitry Andric } // namespace
18185ffd83dbSDimitry Andric 
18195ffd83dbSDimitry Andric void Sema::emitDeferredDiags() {
18205ffd83dbSDimitry Andric   if (ExternalSource)
18215ffd83dbSDimitry Andric     ExternalSource->ReadDeclsToCheckForDeferredDiags(
18225ffd83dbSDimitry Andric         DeclsToCheckForDeferredDiags);
18235ffd83dbSDimitry Andric 
18245ffd83dbSDimitry Andric   if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||
18255ffd83dbSDimitry Andric       DeclsToCheckForDeferredDiags.empty())
18265ffd83dbSDimitry Andric     return;
18275ffd83dbSDimitry Andric 
18285ffd83dbSDimitry Andric   DeferredDiagnosticsEmitter DDE(*this);
1829bdd1243dSDimitry Andric   for (auto *D : DeclsToCheckForDeferredDiags)
18305ffd83dbSDimitry Andric     DDE.checkRecordedDecl(D);
18310b57cec5SDimitry Andric }
18320b57cec5SDimitry Andric 
18330b57cec5SDimitry Andric // In CUDA, there are some constructs which may appear in semantically-valid
18340b57cec5SDimitry Andric // code, but trigger errors if we ever generate code for the function in which
18350b57cec5SDimitry Andric // they appear.  Essentially every construct you're not allowed to use on the
18360b57cec5SDimitry Andric // device falls into this category, because you are allowed to use these
18370b57cec5SDimitry Andric // constructs in a __host__ __device__ function, but only if that function is
18380b57cec5SDimitry Andric // never codegen'ed on the device.
18390b57cec5SDimitry Andric //
18400b57cec5SDimitry Andric // To handle semantic checking for these constructs, we keep track of the set of
18410b57cec5SDimitry Andric // functions we know will be emitted, either because we could tell a priori that
18420b57cec5SDimitry Andric // they would be emitted, or because they were transitively called by a
18430b57cec5SDimitry Andric // known-emitted function.
18440b57cec5SDimitry Andric //
18450b57cec5SDimitry Andric // We also keep a partial call graph of which not-known-emitted functions call
18460b57cec5SDimitry Andric // which other not-known-emitted functions.
18470b57cec5SDimitry Andric //
18480b57cec5SDimitry Andric // When we see something which is illegal if the current function is emitted
18490b57cec5SDimitry Andric // (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
18500b57cec5SDimitry Andric // CheckCUDACall), we first check if the current function is known-emitted.  If
18510b57cec5SDimitry Andric // so, we immediately output the diagnostic.
18520b57cec5SDimitry Andric //
18530b57cec5SDimitry Andric // Otherwise, we "defer" the diagnostic.  It sits in Sema::DeviceDeferredDiags
18540b57cec5SDimitry Andric // until we discover that the function is known-emitted, at which point we take
18550b57cec5SDimitry Andric // it out of this map and emit the diagnostic.
18560b57cec5SDimitry Andric 
1857e8d8bef9SDimitry Andric Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc,
1858e8d8bef9SDimitry Andric                                                    unsigned DiagID,
185906c3fb27SDimitry Andric                                                    const FunctionDecl *Fn,
186006c3fb27SDimitry Andric                                                    Sema &S)
18610b57cec5SDimitry Andric     : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
18620b57cec5SDimitry Andric       ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
18630b57cec5SDimitry Andric   switch (K) {
18640b57cec5SDimitry Andric   case K_Nop:
18650b57cec5SDimitry Andric     break;
18660b57cec5SDimitry Andric   case K_Immediate:
18670b57cec5SDimitry Andric   case K_ImmediateWithCallStack:
1868e8d8bef9SDimitry Andric     ImmediateDiag.emplace(
1869e8d8bef9SDimitry Andric         ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));
18700b57cec5SDimitry Andric     break;
18710b57cec5SDimitry Andric   case K_Deferred:
18720b57cec5SDimitry Andric     assert(Fn && "Must have a function to attach the deferred diag to.");
18730b57cec5SDimitry Andric     auto &Diags = S.DeviceDeferredDiags[Fn];
18740b57cec5SDimitry Andric     PartialDiagId.emplace(Diags.size());
18750b57cec5SDimitry Andric     Diags.emplace_back(Loc, S.PDiag(DiagID));
18760b57cec5SDimitry Andric     break;
18770b57cec5SDimitry Andric   }
18780b57cec5SDimitry Andric }
18790b57cec5SDimitry Andric 
1880e8d8bef9SDimitry Andric Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D)
18810b57cec5SDimitry Andric     : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
18820b57cec5SDimitry Andric       ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
18830b57cec5SDimitry Andric       PartialDiagId(D.PartialDiagId) {
18840b57cec5SDimitry Andric   // Clean the previous diagnostics.
18850b57cec5SDimitry Andric   D.ShowCallStack = false;
18860b57cec5SDimitry Andric   D.ImmediateDiag.reset();
18870b57cec5SDimitry Andric   D.PartialDiagId.reset();
18880b57cec5SDimitry Andric }
18890b57cec5SDimitry Andric 
1890e8d8bef9SDimitry Andric Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
18910b57cec5SDimitry Andric   if (ImmediateDiag) {
18920b57cec5SDimitry Andric     // Emit our diagnostic and, if it was a warning or error, output a callstack
18930b57cec5SDimitry Andric     // if Fn isn't a priori known-emitted.
18940b57cec5SDimitry Andric     bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
18950b57cec5SDimitry Andric                                 DiagID, Loc) >= DiagnosticsEngine::Warning;
18960b57cec5SDimitry Andric     ImmediateDiag.reset(); // Emit the immediate diag.
18970b57cec5SDimitry Andric     if (IsWarningOrError && ShowCallStack)
18980b57cec5SDimitry Andric       emitCallStackNotes(S, Fn);
18990b57cec5SDimitry Andric   } else {
19000b57cec5SDimitry Andric     assert((!PartialDiagId || ShowCallStack) &&
19010b57cec5SDimitry Andric            "Must always show call stack for deferred diags.");
19020b57cec5SDimitry Andric   }
19030b57cec5SDimitry Andric }
19040b57cec5SDimitry Andric 
1905d409305fSDimitry Andric Sema::SemaDiagnosticBuilder
190606c3fb27SDimitry Andric Sema::targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD) {
1907d409305fSDimitry Andric   FD = FD ? FD : getCurFunctionDecl();
1908a7dea167SDimitry Andric   if (LangOpts.OpenMP)
190906c3fb27SDimitry Andric     return LangOpts.OpenMPIsTargetDevice
191006c3fb27SDimitry Andric                ? diagIfOpenMPDeviceCode(Loc, DiagID, FD)
1911d409305fSDimitry Andric                : diagIfOpenMPHostCode(Loc, DiagID, FD);
19120b57cec5SDimitry Andric   if (getLangOpts().CUDA)
19130b57cec5SDimitry Andric     return getLangOpts().CUDAIsDevice ? CUDADiagIfDeviceCode(Loc, DiagID)
19140b57cec5SDimitry Andric                                       : CUDADiagIfHostCode(Loc, DiagID);
19155ffd83dbSDimitry Andric 
19165ffd83dbSDimitry Andric   if (getLangOpts().SYCLIsDevice)
19175ffd83dbSDimitry Andric     return SYCLDiagIfDeviceCode(Loc, DiagID);
19185ffd83dbSDimitry Andric 
1919e8d8bef9SDimitry Andric   return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, DiagID,
1920d409305fSDimitry Andric                                FD, *this);
19210b57cec5SDimitry Andric }
19220b57cec5SDimitry Andric 
1923e8d8bef9SDimitry Andric Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID,
1924e8d8bef9SDimitry Andric                                        bool DeferHint) {
1925e8d8bef9SDimitry Andric   bool IsError = Diags.getDiagnosticIDs()->isDefaultMappingAsError(DiagID);
1926e8d8bef9SDimitry Andric   bool ShouldDefer = getLangOpts().CUDA && LangOpts.GPUDeferDiag &&
1927e8d8bef9SDimitry Andric                      DiagnosticIDs::isDeferrable(DiagID) &&
1928fe6060f1SDimitry Andric                      (DeferHint || DeferDiags || !IsError);
1929e8d8bef9SDimitry Andric   auto SetIsLastErrorImmediate = [&](bool Flag) {
1930e8d8bef9SDimitry Andric     if (IsError)
1931e8d8bef9SDimitry Andric       IsLastErrorImmediate = Flag;
1932e8d8bef9SDimitry Andric   };
1933e8d8bef9SDimitry Andric   if (!ShouldDefer) {
1934e8d8bef9SDimitry Andric     SetIsLastErrorImmediate(true);
1935e8d8bef9SDimitry Andric     return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc,
1936e8d8bef9SDimitry Andric                                  DiagID, getCurFunctionDecl(), *this);
1937e8d8bef9SDimitry Andric   }
1938e8d8bef9SDimitry Andric 
1939d409305fSDimitry Andric   SemaDiagnosticBuilder DB = getLangOpts().CUDAIsDevice
1940e8d8bef9SDimitry Andric                                  ? CUDADiagIfDeviceCode(Loc, DiagID)
1941e8d8bef9SDimitry Andric                                  : CUDADiagIfHostCode(Loc, DiagID);
1942e8d8bef9SDimitry Andric   SetIsLastErrorImmediate(DB.isImmediate());
1943e8d8bef9SDimitry Andric   return DB;
1944e8d8bef9SDimitry Andric }
1945e8d8bef9SDimitry Andric 
1946349cc55cSDimitry Andric void Sema::checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D) {
1947349cc55cSDimitry Andric   if (isUnevaluatedContext() || Ty.isNull())
19485ffd83dbSDimitry Andric     return;
19495ffd83dbSDimitry Andric 
195004eeddc0SDimitry Andric   // The original idea behind checkTypeSupport function is that unused
195104eeddc0SDimitry Andric   // declarations can be replaced with an array of bytes of the same size during
195204eeddc0SDimitry Andric   // codegen, such replacement doesn't seem to be possible for types without
195304eeddc0SDimitry Andric   // constant byte size like zero length arrays. So, do a deep check for SYCL.
195404eeddc0SDimitry Andric   if (D && LangOpts.SYCLIsDevice) {
195504eeddc0SDimitry Andric     llvm::DenseSet<QualType> Visited;
195604eeddc0SDimitry Andric     deepTypeCheckForSYCLDevice(Loc, Visited, D);
195704eeddc0SDimitry Andric   }
195804eeddc0SDimitry Andric 
19595ffd83dbSDimitry Andric   Decl *C = cast<Decl>(getCurLexicalContext());
19605ffd83dbSDimitry Andric 
19615ffd83dbSDimitry Andric   // Memcpy operations for structs containing a member with unsupported type
19625ffd83dbSDimitry Andric   // are ok, though.
19635ffd83dbSDimitry Andric   if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
19645ffd83dbSDimitry Andric     if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
19655ffd83dbSDimitry Andric         MD->isTrivial())
19665ffd83dbSDimitry Andric       return;
19675ffd83dbSDimitry Andric 
19685ffd83dbSDimitry Andric     if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
19695ffd83dbSDimitry Andric       if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())
19705ffd83dbSDimitry Andric         return;
19715ffd83dbSDimitry Andric   }
19725ffd83dbSDimitry Andric 
1973d409305fSDimitry Andric   // Try to associate errors with the lexical context, if that is a function, or
1974d409305fSDimitry Andric   // the value declaration otherwise.
197506c3fb27SDimitry Andric   const FunctionDecl *FD = isa<FunctionDecl>(C)
197606c3fb27SDimitry Andric                                ? cast<FunctionDecl>(C)
1977349cc55cSDimitry Andric                                : dyn_cast_or_null<FunctionDecl>(D);
1978349cc55cSDimitry Andric 
1979349cc55cSDimitry Andric   auto CheckDeviceType = [&](QualType Ty) {
19805ffd83dbSDimitry Andric     if (Ty->isDependentType())
19815ffd83dbSDimitry Andric       return;
19825ffd83dbSDimitry Andric 
19830eae32dcSDimitry Andric     if (Ty->isBitIntType()) {
19840eae32dcSDimitry Andric       if (!Context.getTargetInfo().hasBitIntType()) {
1985349cc55cSDimitry Andric         PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
1986349cc55cSDimitry Andric         if (D)
1987349cc55cSDimitry Andric           PD << D;
1988349cc55cSDimitry Andric         else
1989349cc55cSDimitry Andric           PD << "expression";
1990349cc55cSDimitry Andric         targetDiag(Loc, PD, FD)
1991349cc55cSDimitry Andric             << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/
1992e8d8bef9SDimitry Andric             << Ty << Context.getTargetInfo().getTriple().str();
1993e8d8bef9SDimitry Andric       }
1994e8d8bef9SDimitry Andric       return;
1995e8d8bef9SDimitry Andric     }
1996e8d8bef9SDimitry Andric 
1997349cc55cSDimitry Andric     // Check if we are dealing with two 'long double' but with different
1998349cc55cSDimitry Andric     // semantics.
1999349cc55cSDimitry Andric     bool LongDoubleMismatched = false;
2000349cc55cSDimitry Andric     if (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128) {
2001349cc55cSDimitry Andric       const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(Ty);
2002349cc55cSDimitry Andric       if ((&Sem != &llvm::APFloat::PPCDoubleDouble() &&
20035ffd83dbSDimitry Andric            !Context.getTargetInfo().hasFloat128Type()) ||
2004349cc55cSDimitry Andric           (&Sem == &llvm::APFloat::PPCDoubleDouble() &&
2005349cc55cSDimitry Andric            !Context.getTargetInfo().hasIbm128Type()))
2006349cc55cSDimitry Andric         LongDoubleMismatched = true;
2007349cc55cSDimitry Andric     }
2008349cc55cSDimitry Andric 
2009349cc55cSDimitry Andric     if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
2010349cc55cSDimitry Andric         (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
2011349cc55cSDimitry Andric         (Ty->isIbm128Type() && !Context.getTargetInfo().hasIbm128Type()) ||
20125ffd83dbSDimitry Andric         (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
2013349cc55cSDimitry Andric          !Context.getTargetInfo().hasInt128Type()) ||
201406c3fb27SDimitry Andric         (Ty->isBFloat16Type() && !Context.getTargetInfo().hasBFloat16Type() &&
201506c3fb27SDimitry Andric          !LangOpts.CUDAIsDevice) ||
2016349cc55cSDimitry Andric         LongDoubleMismatched) {
2017349cc55cSDimitry Andric       PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2018349cc55cSDimitry Andric       if (D)
2019349cc55cSDimitry Andric         PD << D;
2020349cc55cSDimitry Andric       else
2021349cc55cSDimitry Andric         PD << "expression";
2022349cc55cSDimitry Andric 
2023349cc55cSDimitry Andric       if (targetDiag(Loc, PD, FD)
2024349cc55cSDimitry Andric           << true /*show bit size*/
2025e8d8bef9SDimitry Andric           << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
2026349cc55cSDimitry Andric           << false /*return*/ << Context.getTargetInfo().getTriple().str()) {
2027349cc55cSDimitry Andric         if (D)
2028d409305fSDimitry Andric           D->setInvalidDecl();
2029349cc55cSDimitry Andric       }
2030349cc55cSDimitry Andric       if (D)
2031d409305fSDimitry Andric         targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
20325ffd83dbSDimitry Andric     }
20335ffd83dbSDimitry Andric   };
20345ffd83dbSDimitry Andric 
2035349cc55cSDimitry Andric   auto CheckType = [&](QualType Ty, bool IsRetTy = false) {
203606c3fb27SDimitry Andric     if (LangOpts.SYCLIsDevice ||
203706c3fb27SDimitry Andric         (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice) ||
203804eeddc0SDimitry Andric         LangOpts.CUDAIsDevice)
2039349cc55cSDimitry Andric       CheckDeviceType(Ty);
20405ffd83dbSDimitry Andric 
2041349cc55cSDimitry Andric     QualType UnqualTy = Ty.getCanonicalType().getUnqualifiedType();
2042349cc55cSDimitry Andric     const TargetInfo &TI = Context.getTargetInfo();
2043349cc55cSDimitry Andric     if (!TI.hasLongDoubleType() && UnqualTy == Context.LongDoubleTy) {
2044349cc55cSDimitry Andric       PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2045349cc55cSDimitry Andric       if (D)
2046349cc55cSDimitry Andric         PD << D;
2047349cc55cSDimitry Andric       else
2048349cc55cSDimitry Andric         PD << "expression";
2049349cc55cSDimitry Andric 
2050349cc55cSDimitry Andric       if (Diag(Loc, PD, FD)
2051349cc55cSDimitry Andric           << false /*show bit size*/ << 0 << Ty << false /*return*/
205206c3fb27SDimitry Andric           << TI.getTriple().str()) {
2053349cc55cSDimitry Andric         if (D)
2054349cc55cSDimitry Andric           D->setInvalidDecl();
2055349cc55cSDimitry Andric       }
2056349cc55cSDimitry Andric       if (D)
2057349cc55cSDimitry Andric         targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2058349cc55cSDimitry Andric     }
2059349cc55cSDimitry Andric 
2060349cc55cSDimitry Andric     bool IsDouble = UnqualTy == Context.DoubleTy;
2061349cc55cSDimitry Andric     bool IsFloat = UnqualTy == Context.FloatTy;
2062349cc55cSDimitry Andric     if (IsRetTy && !TI.hasFPReturn() && (IsDouble || IsFloat)) {
2063349cc55cSDimitry Andric       PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2064349cc55cSDimitry Andric       if (D)
2065349cc55cSDimitry Andric         PD << D;
2066349cc55cSDimitry Andric       else
2067349cc55cSDimitry Andric         PD << "expression";
2068349cc55cSDimitry Andric 
2069349cc55cSDimitry Andric       if (Diag(Loc, PD, FD)
2070349cc55cSDimitry Andric           << false /*show bit size*/ << 0 << Ty << true /*return*/
207106c3fb27SDimitry Andric           << TI.getTriple().str()) {
2072349cc55cSDimitry Andric         if (D)
2073349cc55cSDimitry Andric           D->setInvalidDecl();
2074349cc55cSDimitry Andric       }
2075349cc55cSDimitry Andric       if (D)
2076349cc55cSDimitry Andric         targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2077349cc55cSDimitry Andric     }
2078bdd1243dSDimitry Andric 
2079*5f757f3fSDimitry Andric     if (TI.hasRISCVVTypes() && Ty->isRVVSizelessBuiltinType())
208006c3fb27SDimitry Andric       checkRVVTypeSupport(Ty, Loc, D);
208106c3fb27SDimitry Andric 
2082bdd1243dSDimitry Andric     // Don't allow SVE types in functions without a SVE target.
2083bdd1243dSDimitry Andric     if (Ty->isSVESizelessBuiltinType() && FD && FD->hasBody()) {
2084bdd1243dSDimitry Andric       llvm::StringMap<bool> CallerFeatureMap;
2085bdd1243dSDimitry Andric       Context.getFunctionFeatureMap(CallerFeatureMap, FD);
2086*5f757f3fSDimitry Andric       if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap) &&
2087*5f757f3fSDimitry Andric           !Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap))
2088bdd1243dSDimitry Andric         Diag(D->getLocation(), diag::err_sve_vector_in_non_sve_target) << Ty;
2089bdd1243dSDimitry Andric     }
2090349cc55cSDimitry Andric   };
2091349cc55cSDimitry Andric 
2092349cc55cSDimitry Andric   CheckType(Ty);
20935ffd83dbSDimitry Andric   if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
20945ffd83dbSDimitry Andric     for (const auto &ParamTy : FPTy->param_types())
20955ffd83dbSDimitry Andric       CheckType(ParamTy);
2096349cc55cSDimitry Andric     CheckType(FPTy->getReturnType(), /*IsRetTy=*/true);
20975ffd83dbSDimitry Andric   }
2098d409305fSDimitry Andric   if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty))
2099349cc55cSDimitry Andric     CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true);
21005ffd83dbSDimitry Andric }
21015ffd83dbSDimitry Andric 
21020b57cec5SDimitry Andric /// Looks through the macro-expansion chain for the given
21030b57cec5SDimitry Andric /// location, looking for a macro expansion with the given name.
21040b57cec5SDimitry Andric /// If one is found, returns true and sets the location to that
21050b57cec5SDimitry Andric /// expansion loc.
21060b57cec5SDimitry Andric bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
21070b57cec5SDimitry Andric   SourceLocation loc = locref;
21080b57cec5SDimitry Andric   if (!loc.isMacroID()) return false;
21090b57cec5SDimitry Andric 
21100b57cec5SDimitry Andric   // There's no good way right now to look at the intermediate
21110b57cec5SDimitry Andric   // expansions, so just jump to the expansion location.
21120b57cec5SDimitry Andric   loc = getSourceManager().getExpansionLoc(loc);
21130b57cec5SDimitry Andric 
21140b57cec5SDimitry Andric   // If that's written with the name, stop here.
2115e8d8bef9SDimitry Andric   SmallString<16> buffer;
21160b57cec5SDimitry Andric   if (getPreprocessor().getSpelling(loc, buffer) == name) {
21170b57cec5SDimitry Andric     locref = loc;
21180b57cec5SDimitry Andric     return true;
21190b57cec5SDimitry Andric   }
21200b57cec5SDimitry Andric   return false;
21210b57cec5SDimitry Andric }
21220b57cec5SDimitry Andric 
21230b57cec5SDimitry Andric /// Determines the active Scope associated with the given declaration
21240b57cec5SDimitry Andric /// context.
21250b57cec5SDimitry Andric ///
21260b57cec5SDimitry Andric /// This routine maps a declaration context to the active Scope object that
21270b57cec5SDimitry Andric /// represents that declaration context in the parser. It is typically used
21280b57cec5SDimitry Andric /// from "scope-less" code (e.g., template instantiation, lazy creation of
21290b57cec5SDimitry Andric /// declarations) that injects a name for name-lookup purposes and, therefore,
21300b57cec5SDimitry Andric /// must update the Scope.
21310b57cec5SDimitry Andric ///
21320b57cec5SDimitry Andric /// \returns The scope corresponding to the given declaraion context, or NULL
21330b57cec5SDimitry Andric /// if no such scope is open.
21340b57cec5SDimitry Andric Scope *Sema::getScopeForContext(DeclContext *Ctx) {
21350b57cec5SDimitry Andric 
21360b57cec5SDimitry Andric   if (!Ctx)
21370b57cec5SDimitry Andric     return nullptr;
21380b57cec5SDimitry Andric 
21390b57cec5SDimitry Andric   Ctx = Ctx->getPrimaryContext();
21400b57cec5SDimitry Andric   for (Scope *S = getCurScope(); S; S = S->getParent()) {
21410b57cec5SDimitry Andric     // Ignore scopes that cannot have declarations. This is important for
21420b57cec5SDimitry Andric     // out-of-line definitions of static class members.
21430b57cec5SDimitry Andric     if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
21440b57cec5SDimitry Andric       if (DeclContext *Entity = S->getEntity())
21450b57cec5SDimitry Andric         if (Ctx == Entity->getPrimaryContext())
21460b57cec5SDimitry Andric           return S;
21470b57cec5SDimitry Andric   }
21480b57cec5SDimitry Andric 
21490b57cec5SDimitry Andric   return nullptr;
21500b57cec5SDimitry Andric }
21510b57cec5SDimitry Andric 
21520b57cec5SDimitry Andric /// Enter a new function scope
21530b57cec5SDimitry Andric void Sema::PushFunctionScope() {
21540b57cec5SDimitry Andric   if (FunctionScopes.empty() && CachedFunctionScope) {
21550b57cec5SDimitry Andric     // Use CachedFunctionScope to avoid allocating memory when possible.
21560b57cec5SDimitry Andric     CachedFunctionScope->Clear();
21570b57cec5SDimitry Andric     FunctionScopes.push_back(CachedFunctionScope.release());
21580b57cec5SDimitry Andric   } else {
21590b57cec5SDimitry Andric     FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
21600b57cec5SDimitry Andric   }
21610b57cec5SDimitry Andric   if (LangOpts.OpenMP)
21620b57cec5SDimitry Andric     pushOpenMPFunctionRegion();
21630b57cec5SDimitry Andric }
21640b57cec5SDimitry Andric 
21650b57cec5SDimitry Andric void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
21660b57cec5SDimitry Andric   FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
21670b57cec5SDimitry Andric                                               BlockScope, Block));
216806c3fb27SDimitry Andric   CapturingFunctionScopes++;
21690b57cec5SDimitry Andric }
21700b57cec5SDimitry Andric 
21710b57cec5SDimitry Andric LambdaScopeInfo *Sema::PushLambdaScope() {
21720b57cec5SDimitry Andric   LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
21730b57cec5SDimitry Andric   FunctionScopes.push_back(LSI);
217406c3fb27SDimitry Andric   CapturingFunctionScopes++;
21750b57cec5SDimitry Andric   return LSI;
21760b57cec5SDimitry Andric }
21770b57cec5SDimitry Andric 
21780b57cec5SDimitry Andric void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
21790b57cec5SDimitry Andric   if (LambdaScopeInfo *const LSI = getCurLambda()) {
21800b57cec5SDimitry Andric     LSI->AutoTemplateParameterDepth = Depth;
21810b57cec5SDimitry Andric     return;
21820b57cec5SDimitry Andric   }
21830b57cec5SDimitry Andric   llvm_unreachable(
21840b57cec5SDimitry Andric       "Remove assertion if intentionally called in a non-lambda context.");
21850b57cec5SDimitry Andric }
21860b57cec5SDimitry Andric 
21870b57cec5SDimitry Andric // Check that the type of the VarDecl has an accessible copy constructor and
21880b57cec5SDimitry Andric // resolve its destructor's exception specification.
2189fe6060f1SDimitry Andric // This also performs initialization of block variables when they are moved
2190fe6060f1SDimitry Andric // to the heap. It uses the same rules as applicable for implicit moves
2191fe6060f1SDimitry Andric // according to the C++ standard in effect ([class.copy.elision]p3).
21920b57cec5SDimitry Andric static void checkEscapingByref(VarDecl *VD, Sema &S) {
21930b57cec5SDimitry Andric   QualType T = VD->getType();
21940b57cec5SDimitry Andric   EnterExpressionEvaluationContext scope(
21950b57cec5SDimitry Andric       S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
21960b57cec5SDimitry Andric   SourceLocation Loc = VD->getLocation();
21970b57cec5SDimitry Andric   Expr *VarRef =
21980b57cec5SDimitry Andric       new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
2199fe6060f1SDimitry Andric   ExprResult Result;
220028a41182SDimitry Andric   auto IE = InitializedEntity::InitializeBlock(Loc, T);
220106c3fb27SDimitry Andric   if (S.getLangOpts().CPlusPlus23) {
2202fe6060f1SDimitry Andric     auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr,
2203fe6060f1SDimitry Andric                                        VK_XValue, FPOptionsOverride());
2204fe6060f1SDimitry Andric     Result = S.PerformCopyInitialization(IE, SourceLocation(), E);
2205fe6060f1SDimitry Andric   } else {
2206fe6060f1SDimitry Andric     Result = S.PerformMoveOrCopyInitialization(
2207fe6060f1SDimitry Andric         IE, Sema::NamedReturnInfo{VD, Sema::NamedReturnInfo::MoveEligible},
2208fe6060f1SDimitry Andric         VarRef);
2209fe6060f1SDimitry Andric   }
2210fe6060f1SDimitry Andric 
22110b57cec5SDimitry Andric   if (!Result.isInvalid()) {
22120b57cec5SDimitry Andric     Result = S.MaybeCreateExprWithCleanups(Result);
22130b57cec5SDimitry Andric     Expr *Init = Result.getAs<Expr>();
22140b57cec5SDimitry Andric     S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));
22150b57cec5SDimitry Andric   }
22160b57cec5SDimitry Andric 
22170b57cec5SDimitry Andric   // The destructor's exception specification is needed when IRGen generates
22180b57cec5SDimitry Andric   // block copy/destroy functions. Resolve it here.
22190b57cec5SDimitry Andric   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
22200b57cec5SDimitry Andric     if (CXXDestructorDecl *DD = RD->getDestructor()) {
22210b57cec5SDimitry Andric       auto *FPT = DD->getType()->getAs<FunctionProtoType>();
22220b57cec5SDimitry Andric       S.ResolveExceptionSpec(Loc, FPT);
22230b57cec5SDimitry Andric     }
22240b57cec5SDimitry Andric }
22250b57cec5SDimitry Andric 
22260b57cec5SDimitry Andric static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
22270b57cec5SDimitry Andric   // Set the EscapingByref flag of __block variables captured by
22280b57cec5SDimitry Andric   // escaping blocks.
22290b57cec5SDimitry Andric   for (const BlockDecl *BD : FSI.Blocks) {
22300b57cec5SDimitry Andric     for (const BlockDecl::Capture &BC : BD->captures()) {
22310b57cec5SDimitry Andric       VarDecl *VD = BC.getVariable();
22320b57cec5SDimitry Andric       if (VD->hasAttr<BlocksAttr>()) {
22330b57cec5SDimitry Andric         // Nothing to do if this is a __block variable captured by a
22340b57cec5SDimitry Andric         // non-escaping block.
22350b57cec5SDimitry Andric         if (BD->doesNotEscape())
22360b57cec5SDimitry Andric           continue;
22370b57cec5SDimitry Andric         VD->setEscapingByref();
22380b57cec5SDimitry Andric       }
22390b57cec5SDimitry Andric       // Check whether the captured variable is or contains an object of
22400b57cec5SDimitry Andric       // non-trivial C union type.
22410b57cec5SDimitry Andric       QualType CapType = BC.getVariable()->getType();
22420b57cec5SDimitry Andric       if (CapType.hasNonTrivialToPrimitiveDestructCUnion() ||
22430b57cec5SDimitry Andric           CapType.hasNonTrivialToPrimitiveCopyCUnion())
22440b57cec5SDimitry Andric         S.checkNonTrivialCUnion(BC.getVariable()->getType(),
22450b57cec5SDimitry Andric                                 BD->getCaretLocation(),
22460b57cec5SDimitry Andric                                 Sema::NTCUC_BlockCapture,
22470b57cec5SDimitry Andric                                 Sema::NTCUK_Destruct|Sema::NTCUK_Copy);
22480b57cec5SDimitry Andric     }
22490b57cec5SDimitry Andric   }
22500b57cec5SDimitry Andric 
22510b57cec5SDimitry Andric   for (VarDecl *VD : FSI.ByrefBlockVars) {
22520b57cec5SDimitry Andric     // __block variables might require us to capture a copy-initializer.
22530b57cec5SDimitry Andric     if (!VD->isEscapingByref())
22540b57cec5SDimitry Andric       continue;
22550b57cec5SDimitry Andric     // It's currently invalid to ever have a __block variable with an
22560b57cec5SDimitry Andric     // array type; should we diagnose that here?
22570b57cec5SDimitry Andric     // Regardless, we don't want to ignore array nesting when
22580b57cec5SDimitry Andric     // constructing this copy.
22590b57cec5SDimitry Andric     if (VD->getType()->isStructureOrClassType())
22600b57cec5SDimitry Andric       checkEscapingByref(VD, S);
22610b57cec5SDimitry Andric   }
22620b57cec5SDimitry Andric }
22630b57cec5SDimitry Andric 
22640b57cec5SDimitry Andric /// Pop a function (or block or lambda or captured region) scope from the stack.
22650b57cec5SDimitry Andric ///
22660b57cec5SDimitry Andric /// \param WP The warning policy to use for CFG-based warnings, or null if such
22670b57cec5SDimitry Andric ///        warnings should not be produced.
22680b57cec5SDimitry Andric /// \param D The declaration corresponding to this function scope, if producing
22690b57cec5SDimitry Andric ///        CFG-based warnings.
22700b57cec5SDimitry Andric /// \param BlockType The type of the block expression, if D is a BlockDecl.
22710b57cec5SDimitry Andric Sema::PoppedFunctionScopePtr
22720b57cec5SDimitry Andric Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
22730b57cec5SDimitry Andric                            const Decl *D, QualType BlockType) {
22740b57cec5SDimitry Andric   assert(!FunctionScopes.empty() && "mismatched push/pop!");
22750b57cec5SDimitry Andric 
22760b57cec5SDimitry Andric   markEscapingByrefs(*FunctionScopes.back(), *this);
22770b57cec5SDimitry Andric 
22780b57cec5SDimitry Andric   PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
22790b57cec5SDimitry Andric                                PoppedFunctionScopeDeleter(this));
22800b57cec5SDimitry Andric 
22810b57cec5SDimitry Andric   if (LangOpts.OpenMP)
22820b57cec5SDimitry Andric     popOpenMPFunctionRegion(Scope.get());
22830b57cec5SDimitry Andric 
22840b57cec5SDimitry Andric   // Issue any analysis-based warnings.
22850b57cec5SDimitry Andric   if (WP && D)
22860b57cec5SDimitry Andric     AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
22870b57cec5SDimitry Andric   else
22880b57cec5SDimitry Andric     for (const auto &PUD : Scope->PossiblyUnreachableDiags)
22890b57cec5SDimitry Andric       Diag(PUD.Loc, PUD.PD);
22900b57cec5SDimitry Andric 
22910b57cec5SDimitry Andric   return Scope;
22920b57cec5SDimitry Andric }
22930b57cec5SDimitry Andric 
22940b57cec5SDimitry Andric void Sema::PoppedFunctionScopeDeleter::
22950b57cec5SDimitry Andric operator()(sema::FunctionScopeInfo *Scope) const {
229606c3fb27SDimitry Andric   if (!Scope->isPlainFunction())
229706c3fb27SDimitry Andric     Self->CapturingFunctionScopes--;
22980b57cec5SDimitry Andric   // Stash the function scope for later reuse if it's for a normal function.
22990b57cec5SDimitry Andric   if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
23000b57cec5SDimitry Andric     Self->CachedFunctionScope.reset(Scope);
23010b57cec5SDimitry Andric   else
23020b57cec5SDimitry Andric     delete Scope;
23030b57cec5SDimitry Andric }
23040b57cec5SDimitry Andric 
23050b57cec5SDimitry Andric void Sema::PushCompoundScope(bool IsStmtExpr) {
230681ad6265SDimitry Andric   getCurFunction()->CompoundScopes.push_back(
230781ad6265SDimitry Andric       CompoundScopeInfo(IsStmtExpr, getCurFPFeatures()));
23080b57cec5SDimitry Andric }
23090b57cec5SDimitry Andric 
23100b57cec5SDimitry Andric void Sema::PopCompoundScope() {
23110b57cec5SDimitry Andric   FunctionScopeInfo *CurFunction = getCurFunction();
23120b57cec5SDimitry Andric   assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
23130b57cec5SDimitry Andric 
23140b57cec5SDimitry Andric   CurFunction->CompoundScopes.pop_back();
23150b57cec5SDimitry Andric }
23160b57cec5SDimitry Andric 
23170b57cec5SDimitry Andric /// Determine whether any errors occurred within this function/method/
23180b57cec5SDimitry Andric /// block.
23190b57cec5SDimitry Andric bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
23205ffd83dbSDimitry Andric   return getCurFunction()->hasUnrecoverableErrorOccurred();
23210b57cec5SDimitry Andric }
23220b57cec5SDimitry Andric 
23230b57cec5SDimitry Andric void Sema::setFunctionHasBranchIntoScope() {
23240b57cec5SDimitry Andric   if (!FunctionScopes.empty())
23250b57cec5SDimitry Andric     FunctionScopes.back()->setHasBranchIntoScope();
23260b57cec5SDimitry Andric }
23270b57cec5SDimitry Andric 
23280b57cec5SDimitry Andric void Sema::setFunctionHasBranchProtectedScope() {
23290b57cec5SDimitry Andric   if (!FunctionScopes.empty())
23300b57cec5SDimitry Andric     FunctionScopes.back()->setHasBranchProtectedScope();
23310b57cec5SDimitry Andric }
23320b57cec5SDimitry Andric 
23330b57cec5SDimitry Andric void Sema::setFunctionHasIndirectGoto() {
23340b57cec5SDimitry Andric   if (!FunctionScopes.empty())
23350b57cec5SDimitry Andric     FunctionScopes.back()->setHasIndirectGoto();
23360b57cec5SDimitry Andric }
23370b57cec5SDimitry Andric 
2338fe6060f1SDimitry Andric void Sema::setFunctionHasMustTail() {
2339fe6060f1SDimitry Andric   if (!FunctionScopes.empty())
2340fe6060f1SDimitry Andric     FunctionScopes.back()->setHasMustTail();
2341fe6060f1SDimitry Andric }
2342fe6060f1SDimitry Andric 
23430b57cec5SDimitry Andric BlockScopeInfo *Sema::getCurBlock() {
23440b57cec5SDimitry Andric   if (FunctionScopes.empty())
23450b57cec5SDimitry Andric     return nullptr;
23460b57cec5SDimitry Andric 
23470b57cec5SDimitry Andric   auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
23480b57cec5SDimitry Andric   if (CurBSI && CurBSI->TheDecl &&
23490b57cec5SDimitry Andric       !CurBSI->TheDecl->Encloses(CurContext)) {
23500b57cec5SDimitry Andric     // We have switched contexts due to template instantiation.
23510b57cec5SDimitry Andric     assert(!CodeSynthesisContexts.empty());
23520b57cec5SDimitry Andric     return nullptr;
23530b57cec5SDimitry Andric   }
23540b57cec5SDimitry Andric 
23550b57cec5SDimitry Andric   return CurBSI;
23560b57cec5SDimitry Andric }
23570b57cec5SDimitry Andric 
23580b57cec5SDimitry Andric FunctionScopeInfo *Sema::getEnclosingFunction() const {
23590b57cec5SDimitry Andric   if (FunctionScopes.empty())
23600b57cec5SDimitry Andric     return nullptr;
23610b57cec5SDimitry Andric 
23620b57cec5SDimitry Andric   for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
23630b57cec5SDimitry Andric     if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
23640b57cec5SDimitry Andric       continue;
23650b57cec5SDimitry Andric     return FunctionScopes[e];
23660b57cec5SDimitry Andric   }
23670b57cec5SDimitry Andric   return nullptr;
23680b57cec5SDimitry Andric }
23690b57cec5SDimitry Andric 
2370a7dea167SDimitry Andric LambdaScopeInfo *Sema::getEnclosingLambda() const {
2371a7dea167SDimitry Andric   for (auto *Scope : llvm::reverse(FunctionScopes)) {
2372a7dea167SDimitry Andric     if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) {
237306c3fb27SDimitry Andric       if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&
237406c3fb27SDimitry Andric           LSI->AfterParameterList) {
2375a7dea167SDimitry Andric         // We have switched contexts due to template instantiation.
2376a7dea167SDimitry Andric         // FIXME: We should swap out the FunctionScopes during code synthesis
2377a7dea167SDimitry Andric         // so that we don't need to check for this.
2378a7dea167SDimitry Andric         assert(!CodeSynthesisContexts.empty());
2379a7dea167SDimitry Andric         return nullptr;
2380a7dea167SDimitry Andric       }
2381a7dea167SDimitry Andric       return LSI;
2382a7dea167SDimitry Andric     }
2383a7dea167SDimitry Andric   }
2384a7dea167SDimitry Andric   return nullptr;
2385a7dea167SDimitry Andric }
2386a7dea167SDimitry Andric 
23870b57cec5SDimitry Andric LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
23880b57cec5SDimitry Andric   if (FunctionScopes.empty())
23890b57cec5SDimitry Andric     return nullptr;
23900b57cec5SDimitry Andric 
23910b57cec5SDimitry Andric   auto I = FunctionScopes.rbegin();
23920b57cec5SDimitry Andric   if (IgnoreNonLambdaCapturingScope) {
23930b57cec5SDimitry Andric     auto E = FunctionScopes.rend();
23940b57cec5SDimitry Andric     while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
23950b57cec5SDimitry Andric       ++I;
23960b57cec5SDimitry Andric     if (I == E)
23970b57cec5SDimitry Andric       return nullptr;
23980b57cec5SDimitry Andric   }
23990b57cec5SDimitry Andric   auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
240006c3fb27SDimitry Andric   if (CurLSI && CurLSI->Lambda && CurLSI->CallOperator &&
240106c3fb27SDimitry Andric       !CurLSI->Lambda->Encloses(CurContext) && CurLSI->AfterParameterList) {
24020b57cec5SDimitry Andric     // We have switched contexts due to template instantiation.
24030b57cec5SDimitry Andric     assert(!CodeSynthesisContexts.empty());
24040b57cec5SDimitry Andric     return nullptr;
24050b57cec5SDimitry Andric   }
24060b57cec5SDimitry Andric 
24070b57cec5SDimitry Andric   return CurLSI;
24080b57cec5SDimitry Andric }
2409a7dea167SDimitry Andric 
24100b57cec5SDimitry Andric // We have a generic lambda if we parsed auto parameters, or we have
24110b57cec5SDimitry Andric // an associated template parameter list.
24120b57cec5SDimitry Andric LambdaScopeInfo *Sema::getCurGenericLambda() {
24130b57cec5SDimitry Andric   if (LambdaScopeInfo *LSI =  getCurLambda()) {
24140b57cec5SDimitry Andric     return (LSI->TemplateParams.size() ||
24150b57cec5SDimitry Andric                     LSI->GLTemplateParameterList) ? LSI : nullptr;
24160b57cec5SDimitry Andric   }
24170b57cec5SDimitry Andric   return nullptr;
24180b57cec5SDimitry Andric }
24190b57cec5SDimitry Andric 
24200b57cec5SDimitry Andric 
24210b57cec5SDimitry Andric void Sema::ActOnComment(SourceRange Comment) {
24220b57cec5SDimitry Andric   if (!LangOpts.RetainCommentsFromSystemHeaders &&
24230b57cec5SDimitry Andric       SourceMgr.isInSystemHeader(Comment.getBegin()))
24240b57cec5SDimitry Andric     return;
24250b57cec5SDimitry Andric   RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
242606c3fb27SDimitry Andric   if (RC.isAlmostTrailingComment() || RC.hasUnsupportedSplice(SourceMgr)) {
24270b57cec5SDimitry Andric     SourceRange MagicMarkerRange(Comment.getBegin(),
24280b57cec5SDimitry Andric                                  Comment.getBegin().getLocWithOffset(3));
24290b57cec5SDimitry Andric     StringRef MagicMarkerText;
24300b57cec5SDimitry Andric     switch (RC.getKind()) {
24310b57cec5SDimitry Andric     case RawComment::RCK_OrdinaryBCPL:
24320b57cec5SDimitry Andric       MagicMarkerText = "///<";
24330b57cec5SDimitry Andric       break;
24340b57cec5SDimitry Andric     case RawComment::RCK_OrdinaryC:
24350b57cec5SDimitry Andric       MagicMarkerText = "/**<";
24360b57cec5SDimitry Andric       break;
243706c3fb27SDimitry Andric     case RawComment::RCK_Invalid:
243806c3fb27SDimitry Andric       // FIXME: are there other scenarios that could produce an invalid
243906c3fb27SDimitry Andric       // raw comment here?
244006c3fb27SDimitry Andric       Diag(Comment.getBegin(), diag::warn_splice_in_doxygen_comment);
244106c3fb27SDimitry Andric       return;
24420b57cec5SDimitry Andric     default:
24430b57cec5SDimitry Andric       llvm_unreachable("if this is an almost Doxygen comment, "
24440b57cec5SDimitry Andric                        "it should be ordinary");
24450b57cec5SDimitry Andric     }
24460b57cec5SDimitry Andric     Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
24470b57cec5SDimitry Andric       FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
24480b57cec5SDimitry Andric   }
24490b57cec5SDimitry Andric   Context.addComment(RC);
24500b57cec5SDimitry Andric }
24510b57cec5SDimitry Andric 
24520b57cec5SDimitry Andric // Pin this vtable to this file.
24530b57cec5SDimitry Andric ExternalSemaSource::~ExternalSemaSource() {}
2454480093f4SDimitry Andric char ExternalSemaSource::ID;
24550b57cec5SDimitry Andric 
24560b57cec5SDimitry Andric void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
24570b57cec5SDimitry Andric void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
24580b57cec5SDimitry Andric 
24590b57cec5SDimitry Andric void ExternalSemaSource::ReadKnownNamespaces(
24600b57cec5SDimitry Andric                            SmallVectorImpl<NamespaceDecl *> &Namespaces) {
24610b57cec5SDimitry Andric }
24620b57cec5SDimitry Andric 
24630b57cec5SDimitry Andric void ExternalSemaSource::ReadUndefinedButUsed(
24640b57cec5SDimitry Andric     llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
24650b57cec5SDimitry Andric 
24660b57cec5SDimitry Andric void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
24670b57cec5SDimitry Andric     FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
24680b57cec5SDimitry Andric 
24690b57cec5SDimitry Andric /// Figure out if an expression could be turned into a call.
24700b57cec5SDimitry Andric ///
24710b57cec5SDimitry Andric /// Use this when trying to recover from an error where the programmer may have
24720b57cec5SDimitry Andric /// written just the name of a function instead of actually calling it.
24730b57cec5SDimitry Andric ///
24740b57cec5SDimitry Andric /// \param E - The expression to examine.
24750b57cec5SDimitry Andric /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
24760b57cec5SDimitry Andric ///  with no arguments, this parameter is set to the type returned by such a
24770b57cec5SDimitry Andric ///  call; otherwise, it is set to an empty QualType.
24780b57cec5SDimitry Andric /// \param OverloadSet - If the expression is an overloaded function
24790b57cec5SDimitry Andric ///  name, this parameter is populated with the decls of the various overloads.
24800b57cec5SDimitry Andric bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
24810b57cec5SDimitry Andric                          UnresolvedSetImpl &OverloadSet) {
24820b57cec5SDimitry Andric   ZeroArgCallReturnTy = QualType();
24830b57cec5SDimitry Andric   OverloadSet.clear();
24840b57cec5SDimitry Andric 
24850b57cec5SDimitry Andric   const OverloadExpr *Overloads = nullptr;
24860b57cec5SDimitry Andric   bool IsMemExpr = false;
24870b57cec5SDimitry Andric   if (E.getType() == Context.OverloadTy) {
24880b57cec5SDimitry Andric     OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
24890b57cec5SDimitry Andric 
24900b57cec5SDimitry Andric     // Ignore overloads that are pointer-to-member constants.
24910b57cec5SDimitry Andric     if (FR.HasFormOfMemberPointer)
24920b57cec5SDimitry Andric       return false;
24930b57cec5SDimitry Andric 
24940b57cec5SDimitry Andric     Overloads = FR.Expression;
24950b57cec5SDimitry Andric   } else if (E.getType() == Context.BoundMemberTy) {
24960b57cec5SDimitry Andric     Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
24970b57cec5SDimitry Andric     IsMemExpr = true;
24980b57cec5SDimitry Andric   }
24990b57cec5SDimitry Andric 
25000b57cec5SDimitry Andric   bool Ambiguous = false;
25010b57cec5SDimitry Andric   bool IsMV = false;
25020b57cec5SDimitry Andric 
25030b57cec5SDimitry Andric   if (Overloads) {
25040b57cec5SDimitry Andric     for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
25050b57cec5SDimitry Andric          DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
25060b57cec5SDimitry Andric       OverloadSet.addDecl(*it);
25070b57cec5SDimitry Andric 
25080b57cec5SDimitry Andric       // Check whether the function is a non-template, non-member which takes no
25090b57cec5SDimitry Andric       // arguments.
25100b57cec5SDimitry Andric       if (IsMemExpr)
25110b57cec5SDimitry Andric         continue;
25120b57cec5SDimitry Andric       if (const FunctionDecl *OverloadDecl
25130b57cec5SDimitry Andric             = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
25140b57cec5SDimitry Andric         if (OverloadDecl->getMinRequiredArguments() == 0) {
25150b57cec5SDimitry Andric           if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
25160b57cec5SDimitry Andric               (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
25170b57cec5SDimitry Andric                           OverloadDecl->isCPUSpecificMultiVersion()))) {
25180b57cec5SDimitry Andric             ZeroArgCallReturnTy = QualType();
25190b57cec5SDimitry Andric             Ambiguous = true;
25200b57cec5SDimitry Andric           } else {
25210b57cec5SDimitry Andric             ZeroArgCallReturnTy = OverloadDecl->getReturnType();
25220b57cec5SDimitry Andric             IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
25230b57cec5SDimitry Andric                    OverloadDecl->isCPUSpecificMultiVersion();
25240b57cec5SDimitry Andric           }
25250b57cec5SDimitry Andric         }
25260b57cec5SDimitry Andric       }
25270b57cec5SDimitry Andric     }
25280b57cec5SDimitry Andric 
25290b57cec5SDimitry Andric     // If it's not a member, use better machinery to try to resolve the call
25300b57cec5SDimitry Andric     if (!IsMemExpr)
25310b57cec5SDimitry Andric       return !ZeroArgCallReturnTy.isNull();
25320b57cec5SDimitry Andric   }
25330b57cec5SDimitry Andric 
25340b57cec5SDimitry Andric   // Attempt to call the member with no arguments - this will correctly handle
25350b57cec5SDimitry Andric   // member templates with defaults/deduction of template arguments, overloads
25360b57cec5SDimitry Andric   // with default arguments, etc.
25370b57cec5SDimitry Andric   if (IsMemExpr && !E.isTypeDependent()) {
2538a7dea167SDimitry Andric     Sema::TentativeAnalysisScope Trap(*this);
25390b57cec5SDimitry Andric     ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
2540bdd1243dSDimitry Andric                                              std::nullopt, SourceLocation());
25410b57cec5SDimitry Andric     if (R.isUsable()) {
25420b57cec5SDimitry Andric       ZeroArgCallReturnTy = R.get()->getType();
25430b57cec5SDimitry Andric       return true;
25440b57cec5SDimitry Andric     }
25450b57cec5SDimitry Andric     return false;
25460b57cec5SDimitry Andric   }
25470b57cec5SDimitry Andric 
254806c3fb27SDimitry Andric   if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
254906c3fb27SDimitry Andric     if (const auto *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
25500b57cec5SDimitry Andric       if (Fun->getMinRequiredArguments() == 0)
25510b57cec5SDimitry Andric         ZeroArgCallReturnTy = Fun->getReturnType();
25520b57cec5SDimitry Andric       return true;
25530b57cec5SDimitry Andric     }
25540b57cec5SDimitry Andric   }
25550b57cec5SDimitry Andric 
25560b57cec5SDimitry Andric   // We don't have an expression that's convenient to get a FunctionDecl from,
25570b57cec5SDimitry Andric   // but we can at least check if the type is "function of 0 arguments".
25580b57cec5SDimitry Andric   QualType ExprTy = E.getType();
25590b57cec5SDimitry Andric   const FunctionType *FunTy = nullptr;
25600b57cec5SDimitry Andric   QualType PointeeTy = ExprTy->getPointeeType();
25610b57cec5SDimitry Andric   if (!PointeeTy.isNull())
25620b57cec5SDimitry Andric     FunTy = PointeeTy->getAs<FunctionType>();
25630b57cec5SDimitry Andric   if (!FunTy)
25640b57cec5SDimitry Andric     FunTy = ExprTy->getAs<FunctionType>();
25650b57cec5SDimitry Andric 
256606c3fb27SDimitry Andric   if (const auto *FPT = dyn_cast_if_present<FunctionProtoType>(FunTy)) {
25670b57cec5SDimitry Andric     if (FPT->getNumParams() == 0)
25680b57cec5SDimitry Andric       ZeroArgCallReturnTy = FunTy->getReturnType();
25690b57cec5SDimitry Andric     return true;
25700b57cec5SDimitry Andric   }
25710b57cec5SDimitry Andric   return false;
25720b57cec5SDimitry Andric }
25730b57cec5SDimitry Andric 
25740b57cec5SDimitry Andric /// Give notes for a set of overloads.
25750b57cec5SDimitry Andric ///
25760b57cec5SDimitry Andric /// A companion to tryExprAsCall. In cases when the name that the programmer
25770b57cec5SDimitry Andric /// wrote was an overloaded function, we may be able to make some guesses about
25780b57cec5SDimitry Andric /// plausible overloads based on their return types; such guesses can be handed
25790b57cec5SDimitry Andric /// off to this method to be emitted as notes.
25800b57cec5SDimitry Andric ///
25810b57cec5SDimitry Andric /// \param Overloads - The overloads to note.
25820b57cec5SDimitry Andric /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
25830b57cec5SDimitry Andric ///  -fshow-overloads=best, this is the location to attach to the note about too
25840b57cec5SDimitry Andric ///  many candidates. Typically this will be the location of the original
25850b57cec5SDimitry Andric ///  ill-formed expression.
25860b57cec5SDimitry Andric static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
25870b57cec5SDimitry Andric                           const SourceLocation FinalNoteLoc) {
2588fe6060f1SDimitry Andric   unsigned ShownOverloads = 0;
2589fe6060f1SDimitry Andric   unsigned SuppressedOverloads = 0;
25900b57cec5SDimitry Andric   for (UnresolvedSetImpl::iterator It = Overloads.begin(),
25910b57cec5SDimitry Andric        DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2592fe6060f1SDimitry Andric     if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) {
25930b57cec5SDimitry Andric       ++SuppressedOverloads;
25940b57cec5SDimitry Andric       continue;
25950b57cec5SDimitry Andric     }
25960b57cec5SDimitry Andric 
259706c3fb27SDimitry Andric     const NamedDecl *Fn = (*It)->getUnderlyingDecl();
25980b57cec5SDimitry Andric     // Don't print overloads for non-default multiversioned functions.
25990b57cec5SDimitry Andric     if (const auto *FD = Fn->getAsFunction()) {
26000b57cec5SDimitry Andric       if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
26010b57cec5SDimitry Andric           !FD->getAttr<TargetAttr>()->isDefaultVersion())
26020b57cec5SDimitry Andric         continue;
2603bdd1243dSDimitry Andric       if (FD->isMultiVersion() && FD->hasAttr<TargetVersionAttr>() &&
2604bdd1243dSDimitry Andric           !FD->getAttr<TargetVersionAttr>()->isDefaultVersion())
2605bdd1243dSDimitry Andric         continue;
26060b57cec5SDimitry Andric     }
26070b57cec5SDimitry Andric     S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
26080b57cec5SDimitry Andric     ++ShownOverloads;
26090b57cec5SDimitry Andric   }
26100b57cec5SDimitry Andric 
2611fe6060f1SDimitry Andric   S.Diags.overloadCandidatesShown(ShownOverloads);
2612fe6060f1SDimitry Andric 
26130b57cec5SDimitry Andric   if (SuppressedOverloads)
26140b57cec5SDimitry Andric     S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
26150b57cec5SDimitry Andric       << SuppressedOverloads;
26160b57cec5SDimitry Andric }
26170b57cec5SDimitry Andric 
26180b57cec5SDimitry Andric static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
26190b57cec5SDimitry Andric                                    const UnresolvedSetImpl &Overloads,
26200b57cec5SDimitry Andric                                    bool (*IsPlausibleResult)(QualType)) {
26210b57cec5SDimitry Andric   if (!IsPlausibleResult)
26220b57cec5SDimitry Andric     return noteOverloads(S, Overloads, Loc);
26230b57cec5SDimitry Andric 
26240b57cec5SDimitry Andric   UnresolvedSet<2> PlausibleOverloads;
26250b57cec5SDimitry Andric   for (OverloadExpr::decls_iterator It = Overloads.begin(),
26260b57cec5SDimitry Andric          DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
262706c3fb27SDimitry Andric     const auto *OverloadDecl = cast<FunctionDecl>(*It);
26280b57cec5SDimitry Andric     QualType OverloadResultTy = OverloadDecl->getReturnType();
26290b57cec5SDimitry Andric     if (IsPlausibleResult(OverloadResultTy))
26300b57cec5SDimitry Andric       PlausibleOverloads.addDecl(It.getDecl());
26310b57cec5SDimitry Andric   }
26320b57cec5SDimitry Andric   noteOverloads(S, PlausibleOverloads, Loc);
26330b57cec5SDimitry Andric }
26340b57cec5SDimitry Andric 
26350b57cec5SDimitry Andric /// Determine whether the given expression can be called by just
26360b57cec5SDimitry Andric /// putting parentheses after it.  Notably, expressions with unary
26370b57cec5SDimitry Andric /// operators can't be because the unary operator will start parsing
26380b57cec5SDimitry Andric /// outside the call.
263906c3fb27SDimitry Andric static bool IsCallableWithAppend(const Expr *E) {
26400b57cec5SDimitry Andric   E = E->IgnoreImplicit();
26410b57cec5SDimitry Andric   return (!isa<CStyleCastExpr>(E) &&
26420b57cec5SDimitry Andric           !isa<UnaryOperator>(E) &&
26430b57cec5SDimitry Andric           !isa<BinaryOperator>(E) &&
26440b57cec5SDimitry Andric           !isa<CXXOperatorCallExpr>(E));
26450b57cec5SDimitry Andric }
26460b57cec5SDimitry Andric 
26470b57cec5SDimitry Andric static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {
26480b57cec5SDimitry Andric   if (const auto *UO = dyn_cast<UnaryOperator>(E))
26490b57cec5SDimitry Andric     E = UO->getSubExpr();
26500b57cec5SDimitry Andric 
26510b57cec5SDimitry Andric   if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
26520b57cec5SDimitry Andric     if (ULE->getNumDecls() == 0)
26530b57cec5SDimitry Andric       return false;
26540b57cec5SDimitry Andric 
26550b57cec5SDimitry Andric     const NamedDecl *ND = *ULE->decls_begin();
26560b57cec5SDimitry Andric     if (const auto *FD = dyn_cast<FunctionDecl>(ND))
26570b57cec5SDimitry Andric       return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();
26580b57cec5SDimitry Andric   }
26590b57cec5SDimitry Andric   return false;
26600b57cec5SDimitry Andric }
26610b57cec5SDimitry Andric 
26620b57cec5SDimitry Andric bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
26630b57cec5SDimitry Andric                                 bool ForceComplain,
26640b57cec5SDimitry Andric                                 bool (*IsPlausibleResult)(QualType)) {
26650b57cec5SDimitry Andric   SourceLocation Loc = E.get()->getExprLoc();
26660b57cec5SDimitry Andric   SourceRange Range = E.get()->getSourceRange();
26670b57cec5SDimitry Andric   UnresolvedSet<4> Overloads;
26681fd87a68SDimitry Andric 
26691fd87a68SDimitry Andric   // If this is a SFINAE context, don't try anything that might trigger ADL
26701fd87a68SDimitry Andric   // prematurely.
26711fd87a68SDimitry Andric   if (!isSFINAEContext()) {
26721fd87a68SDimitry Andric     QualType ZeroArgCallTy;
26730b57cec5SDimitry Andric     if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
26740b57cec5SDimitry Andric         !ZeroArgCallTy.isNull() &&
26750b57cec5SDimitry Andric         (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
26760b57cec5SDimitry Andric       // At this point, we know E is potentially callable with 0
26770b57cec5SDimitry Andric       // arguments and that it returns something of a reasonable type,
26780b57cec5SDimitry Andric       // so we can emit a fixit and carry on pretending that E was
26790b57cec5SDimitry Andric       // actually a CallExpr.
26800b57cec5SDimitry Andric       SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
26810b57cec5SDimitry Andric       bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
26820b57cec5SDimitry Andric       Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
26830b57cec5SDimitry Andric                     << (IsCallableWithAppend(E.get())
26841fd87a68SDimitry Andric                             ? FixItHint::CreateInsertion(ParenInsertionLoc,
26851fd87a68SDimitry Andric                                                          "()")
26860b57cec5SDimitry Andric                             : FixItHint());
26870b57cec5SDimitry Andric       if (!IsMV)
26880b57cec5SDimitry Andric         notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
26890b57cec5SDimitry Andric 
26900b57cec5SDimitry Andric       // FIXME: Try this before emitting the fixit, and suppress diagnostics
26910b57cec5SDimitry Andric       // while doing so.
2692bdd1243dSDimitry Andric       E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), std::nullopt,
26930b57cec5SDimitry Andric                         Range.getEnd().getLocWithOffset(1));
26940b57cec5SDimitry Andric       return true;
26950b57cec5SDimitry Andric     }
26961fd87a68SDimitry Andric   }
26970b57cec5SDimitry Andric   if (!ForceComplain) return false;
26980b57cec5SDimitry Andric 
26990b57cec5SDimitry Andric   bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
27000b57cec5SDimitry Andric   Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
27010b57cec5SDimitry Andric   if (!IsMV)
27020b57cec5SDimitry Andric     notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
27030b57cec5SDimitry Andric   E = ExprError();
27040b57cec5SDimitry Andric   return true;
27050b57cec5SDimitry Andric }
27060b57cec5SDimitry Andric 
27070b57cec5SDimitry Andric IdentifierInfo *Sema::getSuperIdentifier() const {
27080b57cec5SDimitry Andric   if (!Ident_super)
27090b57cec5SDimitry Andric     Ident_super = &Context.Idents.get("super");
27100b57cec5SDimitry Andric   return Ident_super;
27110b57cec5SDimitry Andric }
27120b57cec5SDimitry Andric 
27130b57cec5SDimitry Andric void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
2714a7dea167SDimitry Andric                                    CapturedRegionKind K,
2715a7dea167SDimitry Andric                                    unsigned OpenMPCaptureLevel) {
2716a7dea167SDimitry Andric   auto *CSI = new CapturedRegionScopeInfo(
27170b57cec5SDimitry Andric       getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
2718a7dea167SDimitry Andric       (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0,
2719a7dea167SDimitry Andric       OpenMPCaptureLevel);
27200b57cec5SDimitry Andric   CSI->ReturnType = Context.VoidTy;
27210b57cec5SDimitry Andric   FunctionScopes.push_back(CSI);
272206c3fb27SDimitry Andric   CapturingFunctionScopes++;
27230b57cec5SDimitry Andric }
27240b57cec5SDimitry Andric 
27250b57cec5SDimitry Andric CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
27260b57cec5SDimitry Andric   if (FunctionScopes.empty())
27270b57cec5SDimitry Andric     return nullptr;
27280b57cec5SDimitry Andric 
27290b57cec5SDimitry Andric   return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
27300b57cec5SDimitry Andric }
27310b57cec5SDimitry Andric 
27320b57cec5SDimitry Andric const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
27330b57cec5SDimitry Andric Sema::getMismatchingDeleteExpressions() const {
27340b57cec5SDimitry Andric   return DeleteExprs;
27350b57cec5SDimitry Andric }
273681ad6265SDimitry Andric 
273781ad6265SDimitry Andric Sema::FPFeaturesStateRAII::FPFeaturesStateRAII(Sema &S)
273881ad6265SDimitry Andric     : S(S), OldFPFeaturesState(S.CurFPFeatures),
273981ad6265SDimitry Andric       OldOverrides(S.FpPragmaStack.CurrentValue),
274081ad6265SDimitry Andric       OldEvalMethod(S.PP.getCurrentFPEvalMethod()),
274181ad6265SDimitry Andric       OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {}
274281ad6265SDimitry Andric 
274381ad6265SDimitry Andric Sema::FPFeaturesStateRAII::~FPFeaturesStateRAII() {
274481ad6265SDimitry Andric   S.CurFPFeatures = OldFPFeaturesState;
274581ad6265SDimitry Andric   S.FpPragmaStack.CurrentValue = OldOverrides;
274681ad6265SDimitry Andric   S.PP.setCurrentFPEvalMethod(OldFPPragmaLocation, OldEvalMethod);
274781ad6265SDimitry Andric }
2748bdd1243dSDimitry Andric 
2749bdd1243dSDimitry Andric bool Sema::isDeclaratorFunctionLike(Declarator &D) {
2750bdd1243dSDimitry Andric   assert(D.getCXXScopeSpec().isSet() &&
2751bdd1243dSDimitry Andric          "can only be called for qualified names");
2752bdd1243dSDimitry Andric 
2753bdd1243dSDimitry Andric   auto LR = LookupResult(*this, D.getIdentifier(), D.getBeginLoc(),
2754bdd1243dSDimitry Andric                          LookupOrdinaryName, forRedeclarationInCurContext());
2755bdd1243dSDimitry Andric   DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(),
2756bdd1243dSDimitry Andric                                        !D.getDeclSpec().isFriendSpecified());
2757bdd1243dSDimitry Andric   if (!DC)
2758bdd1243dSDimitry Andric     return false;
2759bdd1243dSDimitry Andric 
2760bdd1243dSDimitry Andric   LookupQualifiedName(LR, DC);
2761bdd1243dSDimitry Andric   bool Result = std::all_of(LR.begin(), LR.end(), [](Decl *Dcl) {
2762bdd1243dSDimitry Andric     if (NamedDecl *ND = dyn_cast<NamedDecl>(Dcl)) {
2763bdd1243dSDimitry Andric       ND = ND->getUnderlyingDecl();
2764bdd1243dSDimitry Andric       return isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
2765bdd1243dSDimitry Andric              isa<UsingDecl>(ND);
2766bdd1243dSDimitry Andric     }
2767bdd1243dSDimitry Andric     return false;
2768bdd1243dSDimitry Andric   });
2769bdd1243dSDimitry Andric   return Result;
2770bdd1243dSDimitry Andric }
2771