xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Sema/Sema.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This file implements the actions class which performs semantic analysis and
107330f729Sjoerg // builds an AST out of a parse stream.
117330f729Sjoerg //
127330f729Sjoerg //===----------------------------------------------------------------------===//
137330f729Sjoerg 
14*e038c9c4Sjoerg #include "UsedDeclVisitor.h"
157330f729Sjoerg #include "clang/AST/ASTContext.h"
167330f729Sjoerg #include "clang/AST/ASTDiagnostic.h"
17*e038c9c4Sjoerg #include "clang/AST/Decl.h"
187330f729Sjoerg #include "clang/AST/DeclCXX.h"
197330f729Sjoerg #include "clang/AST/DeclFriend.h"
207330f729Sjoerg #include "clang/AST/DeclObjC.h"
217330f729Sjoerg #include "clang/AST/Expr.h"
227330f729Sjoerg #include "clang/AST/ExprCXX.h"
237330f729Sjoerg #include "clang/AST/PrettyDeclStackTrace.h"
247330f729Sjoerg #include "clang/AST/StmtCXX.h"
257330f729Sjoerg #include "clang/Basic/DiagnosticOptions.h"
267330f729Sjoerg #include "clang/Basic/PartialDiagnostic.h"
27*e038c9c4Sjoerg #include "clang/Basic/SourceManager.h"
287330f729Sjoerg #include "clang/Basic/Stack.h"
297330f729Sjoerg #include "clang/Basic/TargetInfo.h"
307330f729Sjoerg #include "clang/Lex/HeaderSearch.h"
317330f729Sjoerg #include "clang/Lex/Preprocessor.h"
327330f729Sjoerg #include "clang/Sema/CXXFieldCollector.h"
337330f729Sjoerg #include "clang/Sema/DelayedDiagnostic.h"
347330f729Sjoerg #include "clang/Sema/ExternalSemaSource.h"
357330f729Sjoerg #include "clang/Sema/Initialization.h"
367330f729Sjoerg #include "clang/Sema/MultiplexExternalSemaSource.h"
377330f729Sjoerg #include "clang/Sema/ObjCMethodList.h"
387330f729Sjoerg #include "clang/Sema/Scope.h"
397330f729Sjoerg #include "clang/Sema/ScopeInfo.h"
407330f729Sjoerg #include "clang/Sema/SemaConsumer.h"
417330f729Sjoerg #include "clang/Sema/SemaInternal.h"
427330f729Sjoerg #include "clang/Sema/TemplateDeduction.h"
437330f729Sjoerg #include "clang/Sema/TemplateInstCallback.h"
447330f729Sjoerg #include "clang/Sema/TypoCorrection.h"
457330f729Sjoerg #include "llvm/ADT/DenseMap.h"
46*e038c9c4Sjoerg #include "llvm/ADT/SmallPtrSet.h"
477330f729Sjoerg #include "llvm/Support/TimeProfiler.h"
487330f729Sjoerg 
497330f729Sjoerg using namespace clang;
507330f729Sjoerg using namespace sema;
517330f729Sjoerg 
getLocForEndOfToken(SourceLocation Loc,unsigned Offset)527330f729Sjoerg SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
537330f729Sjoerg   return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
547330f729Sjoerg }
557330f729Sjoerg 
getModuleLoader() const567330f729Sjoerg ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
577330f729Sjoerg 
58*e038c9c4Sjoerg IdentifierInfo *
InventAbbreviatedTemplateParameterTypeName(IdentifierInfo * ParamName,unsigned int Index)59*e038c9c4Sjoerg Sema::InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
60*e038c9c4Sjoerg                                                  unsigned int Index) {
61*e038c9c4Sjoerg   std::string InventedName;
62*e038c9c4Sjoerg   llvm::raw_string_ostream OS(InventedName);
63*e038c9c4Sjoerg 
64*e038c9c4Sjoerg   if (!ParamName)
65*e038c9c4Sjoerg     OS << "auto:" << Index + 1;
66*e038c9c4Sjoerg   else
67*e038c9c4Sjoerg     OS << ParamName->getName() << ":auto";
68*e038c9c4Sjoerg 
69*e038c9c4Sjoerg   OS.flush();
70*e038c9c4Sjoerg   return &Context.Idents.get(OS.str());
71*e038c9c4Sjoerg }
72*e038c9c4Sjoerg 
getPrintingPolicy(const ASTContext & Context,const Preprocessor & PP)737330f729Sjoerg PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
747330f729Sjoerg                                        const Preprocessor &PP) {
757330f729Sjoerg   PrintingPolicy Policy = Context.getPrintingPolicy();
767330f729Sjoerg   // In diagnostics, we print _Bool as bool if the latter is defined as the
777330f729Sjoerg   // former.
787330f729Sjoerg   Policy.Bool = Context.getLangOpts().Bool;
797330f729Sjoerg   if (!Policy.Bool) {
807330f729Sjoerg     if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
817330f729Sjoerg       Policy.Bool = BoolMacro->isObjectLike() &&
827330f729Sjoerg                     BoolMacro->getNumTokens() == 1 &&
837330f729Sjoerg                     BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
847330f729Sjoerg     }
857330f729Sjoerg   }
867330f729Sjoerg 
877330f729Sjoerg   return Policy;
887330f729Sjoerg }
897330f729Sjoerg 
ActOnTranslationUnitScope(Scope * S)907330f729Sjoerg void Sema::ActOnTranslationUnitScope(Scope *S) {
917330f729Sjoerg   TUScope = S;
927330f729Sjoerg   PushDeclContext(S, Context.getTranslationUnitDecl());
937330f729Sjoerg }
947330f729Sjoerg 
957330f729Sjoerg namespace clang {
967330f729Sjoerg namespace sema {
977330f729Sjoerg 
987330f729Sjoerg class SemaPPCallbacks : public PPCallbacks {
997330f729Sjoerg   Sema *S = nullptr;
1007330f729Sjoerg   llvm::SmallVector<SourceLocation, 8> IncludeStack;
1017330f729Sjoerg 
1027330f729Sjoerg public:
set(Sema & S)1037330f729Sjoerg   void set(Sema &S) { this->S = &S; }
1047330f729Sjoerg 
reset()1057330f729Sjoerg   void reset() { S = nullptr; }
1067330f729Sjoerg 
FileChanged(SourceLocation Loc,FileChangeReason Reason,SrcMgr::CharacteristicKind FileType,FileID PrevFID)1077330f729Sjoerg   virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
1087330f729Sjoerg                            SrcMgr::CharacteristicKind FileType,
1097330f729Sjoerg                            FileID PrevFID) override {
1107330f729Sjoerg     if (!S)
1117330f729Sjoerg       return;
1127330f729Sjoerg     switch (Reason) {
1137330f729Sjoerg     case EnterFile: {
1147330f729Sjoerg       SourceManager &SM = S->getSourceManager();
1157330f729Sjoerg       SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
1167330f729Sjoerg       if (IncludeLoc.isValid()) {
1177330f729Sjoerg         if (llvm::timeTraceProfilerEnabled()) {
1187330f729Sjoerg           const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
1197330f729Sjoerg           llvm::timeTraceProfilerBegin(
1207330f729Sjoerg               "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>"));
1217330f729Sjoerg         }
1227330f729Sjoerg 
1237330f729Sjoerg         IncludeStack.push_back(IncludeLoc);
124*e038c9c4Sjoerg         S->DiagnoseNonDefaultPragmaAlignPack(
125*e038c9c4Sjoerg             Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude,
126*e038c9c4Sjoerg             IncludeLoc);
1277330f729Sjoerg       }
1287330f729Sjoerg       break;
1297330f729Sjoerg     }
1307330f729Sjoerg     case ExitFile:
1317330f729Sjoerg       if (!IncludeStack.empty()) {
1327330f729Sjoerg         if (llvm::timeTraceProfilerEnabled())
1337330f729Sjoerg           llvm::timeTraceProfilerEnd();
1347330f729Sjoerg 
135*e038c9c4Sjoerg         S->DiagnoseNonDefaultPragmaAlignPack(
136*e038c9c4Sjoerg             Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit,
1377330f729Sjoerg             IncludeStack.pop_back_val());
1387330f729Sjoerg       }
1397330f729Sjoerg       break;
1407330f729Sjoerg     default:
1417330f729Sjoerg       break;
1427330f729Sjoerg     }
1437330f729Sjoerg   }
1447330f729Sjoerg };
1457330f729Sjoerg 
1467330f729Sjoerg } // end namespace sema
1477330f729Sjoerg } // end namespace clang
1487330f729Sjoerg 
149*e038c9c4Sjoerg const unsigned Sema::MaxAlignmentExponent;
150*e038c9c4Sjoerg const unsigned Sema::MaximumAlignment;
151*e038c9c4Sjoerg 
Sema(Preprocessor & pp,ASTContext & ctxt,ASTConsumer & consumer,TranslationUnitKind TUKind,CodeCompleteConsumer * CodeCompleter)1527330f729Sjoerg Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1537330f729Sjoerg            TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
1547330f729Sjoerg     : ExternalSource(nullptr), isMultiplexExternalSource(false),
155*e038c9c4Sjoerg       CurFPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
1567330f729Sjoerg       Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
1577330f729Sjoerg       SourceMgr(PP.getSourceManager()), CollectStats(false),
1587330f729Sjoerg       CodeCompleter(CodeCompleter), CurContext(nullptr),
1597330f729Sjoerg       OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
1607330f729Sjoerg       MSPointerToMemberRepresentationMethod(
1617330f729Sjoerg           LangOpts.getMSPointerToMemberRepresentationMethod()),
162*e038c9c4Sjoerg       VtorDispStack(LangOpts.getVtorDispMode()),
163*e038c9c4Sjoerg       AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)),
1647330f729Sjoerg       DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
165*e038c9c4Sjoerg       CodeSegStack(nullptr), FpPragmaStack(FPOptionsOverride()),
166*e038c9c4Sjoerg       CurInitSeg(nullptr), VisContext(nullptr),
1677330f729Sjoerg       PragmaAttributeCurrentTargetDecl(nullptr),
1687330f729Sjoerg       IsBuildingRecoveryCallExpr(false), Cleanup{}, LateTemplateParser(nullptr),
1697330f729Sjoerg       LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
1707330f729Sjoerg       StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
1717330f729Sjoerg       StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr),
1727330f729Sjoerg       MSVCGuidDecl(nullptr), NSNumberDecl(nullptr), NSValueDecl(nullptr),
1737330f729Sjoerg       NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
1747330f729Sjoerg       ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
1757330f729Sjoerg       ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
1767330f729Sjoerg       DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
1777330f729Sjoerg       TUKind(TUKind), NumSFINAEErrors(0),
1787330f729Sjoerg       FullyCheckedComparisonCategories(
1797330f729Sjoerg           static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
180*e038c9c4Sjoerg       SatisfactionCache(Context), AccessCheckingSFINAE(false),
181*e038c9c4Sjoerg       InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
182*e038c9c4Sjoerg       ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
183*e038c9c4Sjoerg       DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
1847330f729Sjoerg       ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
1857330f729Sjoerg       CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
1867330f729Sjoerg   TUScope = nullptr;
1877330f729Sjoerg   isConstantEvaluatedOverride = false;
1887330f729Sjoerg 
1897330f729Sjoerg   LoadedExternalKnownNamespaces = false;
1907330f729Sjoerg   for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
1917330f729Sjoerg     NSNumberLiteralMethods[I] = nullptr;
1927330f729Sjoerg 
1937330f729Sjoerg   if (getLangOpts().ObjC)
1947330f729Sjoerg     NSAPIObj.reset(new NSAPI(Context));
1957330f729Sjoerg 
1967330f729Sjoerg   if (getLangOpts().CPlusPlus)
1977330f729Sjoerg     FieldCollector.reset(new CXXFieldCollector());
1987330f729Sjoerg 
1997330f729Sjoerg   // Tell diagnostics how to render things from the AST library.
2007330f729Sjoerg   Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
2017330f729Sjoerg 
2027330f729Sjoerg   ExprEvalContexts.emplace_back(
2037330f729Sjoerg       ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
2047330f729Sjoerg       nullptr, ExpressionEvaluationContextRecord::EK_Other);
2057330f729Sjoerg 
2067330f729Sjoerg   // Initialization of data sharing attributes stack for OpenMP
2077330f729Sjoerg   InitDataSharingAttributesStack();
2087330f729Sjoerg 
2097330f729Sjoerg   std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
2107330f729Sjoerg       std::make_unique<sema::SemaPPCallbacks>();
2117330f729Sjoerg   SemaPPCallbackHandler = Callbacks.get();
2127330f729Sjoerg   PP.addPPCallbacks(std::move(Callbacks));
2137330f729Sjoerg   SemaPPCallbackHandler->set(*this);
2147330f729Sjoerg }
2157330f729Sjoerg 
216*e038c9c4Sjoerg // Anchor Sema's type info to this TU.
anchor()217*e038c9c4Sjoerg void Sema::anchor() {}
218*e038c9c4Sjoerg 
addImplicitTypedef(StringRef Name,QualType T)2197330f729Sjoerg void Sema::addImplicitTypedef(StringRef Name, QualType T) {
2207330f729Sjoerg   DeclarationName DN = &Context.Idents.get(Name);
2217330f729Sjoerg   if (IdResolver.begin(DN) == IdResolver.end())
2227330f729Sjoerg     PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
2237330f729Sjoerg }
2247330f729Sjoerg 
Initialize()2257330f729Sjoerg void Sema::Initialize() {
2267330f729Sjoerg   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
2277330f729Sjoerg     SC->InitializeSema(*this);
2287330f729Sjoerg 
2297330f729Sjoerg   // Tell the external Sema source about this Sema object.
2307330f729Sjoerg   if (ExternalSemaSource *ExternalSema
2317330f729Sjoerg       = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
2327330f729Sjoerg     ExternalSema->InitializeSema(*this);
2337330f729Sjoerg 
2347330f729Sjoerg   // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
2357330f729Sjoerg   // will not be able to merge any duplicate __va_list_tag decls correctly.
2367330f729Sjoerg   VAListTagName = PP.getIdentifierInfo("__va_list_tag");
2377330f729Sjoerg 
2387330f729Sjoerg   if (!TUScope)
2397330f729Sjoerg     return;
2407330f729Sjoerg 
2417330f729Sjoerg   // Initialize predefined 128-bit integer types, if needed.
242*e038c9c4Sjoerg   if (Context.getTargetInfo().hasInt128Type() ||
243*e038c9c4Sjoerg       (Context.getAuxTargetInfo() &&
244*e038c9c4Sjoerg        Context.getAuxTargetInfo()->hasInt128Type())) {
2457330f729Sjoerg     // If either of the 128-bit integer types are unavailable to name lookup,
2467330f729Sjoerg     // define them now.
2477330f729Sjoerg     DeclarationName Int128 = &Context.Idents.get("__int128_t");
2487330f729Sjoerg     if (IdResolver.begin(Int128) == IdResolver.end())
2497330f729Sjoerg       PushOnScopeChains(Context.getInt128Decl(), TUScope);
2507330f729Sjoerg 
2517330f729Sjoerg     DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
2527330f729Sjoerg     if (IdResolver.begin(UInt128) == IdResolver.end())
2537330f729Sjoerg       PushOnScopeChains(Context.getUInt128Decl(), TUScope);
2547330f729Sjoerg   }
2557330f729Sjoerg 
2567330f729Sjoerg 
2577330f729Sjoerg   // Initialize predefined Objective-C types:
2587330f729Sjoerg   if (getLangOpts().ObjC) {
2597330f729Sjoerg     // If 'SEL' does not yet refer to any declarations, make it refer to the
2607330f729Sjoerg     // predefined 'SEL'.
2617330f729Sjoerg     DeclarationName SEL = &Context.Idents.get("SEL");
2627330f729Sjoerg     if (IdResolver.begin(SEL) == IdResolver.end())
2637330f729Sjoerg       PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
2647330f729Sjoerg 
2657330f729Sjoerg     // If 'id' does not yet refer to any declarations, make it refer to the
2667330f729Sjoerg     // predefined 'id'.
2677330f729Sjoerg     DeclarationName Id = &Context.Idents.get("id");
2687330f729Sjoerg     if (IdResolver.begin(Id) == IdResolver.end())
2697330f729Sjoerg       PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
2707330f729Sjoerg 
2717330f729Sjoerg     // Create the built-in typedef for 'Class'.
2727330f729Sjoerg     DeclarationName Class = &Context.Idents.get("Class");
2737330f729Sjoerg     if (IdResolver.begin(Class) == IdResolver.end())
2747330f729Sjoerg       PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
2757330f729Sjoerg 
2767330f729Sjoerg     // Create the built-in forward declaratino for 'Protocol'.
2777330f729Sjoerg     DeclarationName Protocol = &Context.Idents.get("Protocol");
2787330f729Sjoerg     if (IdResolver.begin(Protocol) == IdResolver.end())
2797330f729Sjoerg       PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
2807330f729Sjoerg   }
2817330f729Sjoerg 
2827330f729Sjoerg   // Create the internal type for the *StringMakeConstantString builtins.
2837330f729Sjoerg   DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
2847330f729Sjoerg   if (IdResolver.begin(ConstantString) == IdResolver.end())
2857330f729Sjoerg     PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
2867330f729Sjoerg 
2877330f729Sjoerg   // Initialize Microsoft "predefined C++ types".
2887330f729Sjoerg   if (getLangOpts().MSVCCompat) {
2897330f729Sjoerg     if (getLangOpts().CPlusPlus &&
2907330f729Sjoerg         IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
2917330f729Sjoerg       PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
2927330f729Sjoerg                         TUScope);
2937330f729Sjoerg 
2947330f729Sjoerg     addImplicitTypedef("size_t", Context.getSizeType());
2957330f729Sjoerg   }
2967330f729Sjoerg 
2977330f729Sjoerg   // Initialize predefined OpenCL types and supported extensions and (optional)
2987330f729Sjoerg   // core features.
2997330f729Sjoerg   if (getLangOpts().OpenCL) {
3007330f729Sjoerg     getOpenCLOptions().addSupport(
301*e038c9c4Sjoerg         Context.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts());
3027330f729Sjoerg     addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
3037330f729Sjoerg     addImplicitTypedef("event_t", Context.OCLEventTy);
3047330f729Sjoerg     if (getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) {
3057330f729Sjoerg       addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
3067330f729Sjoerg       addImplicitTypedef("queue_t", Context.OCLQueueTy);
3077330f729Sjoerg       addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
3087330f729Sjoerg       addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
3097330f729Sjoerg       addImplicitTypedef("atomic_uint",
3107330f729Sjoerg                          Context.getAtomicType(Context.UnsignedIntTy));
3117330f729Sjoerg       addImplicitTypedef("atomic_float",
3127330f729Sjoerg                          Context.getAtomicType(Context.FloatTy));
3137330f729Sjoerg       // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
3147330f729Sjoerg       // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
3157330f729Sjoerg       addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
316*e038c9c4Sjoerg 
3177330f729Sjoerg 
3187330f729Sjoerg       // OpenCL v2.0 s6.13.11.6:
3197330f729Sjoerg       // - The atomic_long and atomic_ulong types are supported if the
3207330f729Sjoerg       //   cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
3217330f729Sjoerg       //   extensions are supported.
3227330f729Sjoerg       // - The atomic_double type is only supported if double precision
3237330f729Sjoerg       //   is supported and the cl_khr_int64_base_atomics and
3247330f729Sjoerg       //   cl_khr_int64_extended_atomics extensions are supported.
3257330f729Sjoerg       // - If the device address space is 64-bits, the data types
3267330f729Sjoerg       //   atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
3277330f729Sjoerg       //   atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
3287330f729Sjoerg       //   cl_khr_int64_extended_atomics extensions are supported.
329*e038c9c4Sjoerg 
330*e038c9c4Sjoerg       auto AddPointerSizeDependentTypes = [&]() {
331*e038c9c4Sjoerg         auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
332*e038c9c4Sjoerg         auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
333*e038c9c4Sjoerg         auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
334*e038c9c4Sjoerg         auto AtomicPtrDiffT =
335*e038c9c4Sjoerg             Context.getAtomicType(Context.getPointerDiffType());
336*e038c9c4Sjoerg         addImplicitTypedef("atomic_size_t", AtomicSizeT);
337*e038c9c4Sjoerg         addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
338*e038c9c4Sjoerg         addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
339*e038c9c4Sjoerg         addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
340*e038c9c4Sjoerg       };
341*e038c9c4Sjoerg 
342*e038c9c4Sjoerg       if (Context.getTypeSize(Context.getSizeType()) == 32) {
343*e038c9c4Sjoerg         AddPointerSizeDependentTypes();
344*e038c9c4Sjoerg       }
345*e038c9c4Sjoerg 
3467330f729Sjoerg       std::vector<QualType> Atomic64BitTypes;
347*e038c9c4Sjoerg       if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",
348*e038c9c4Sjoerg                                          getLangOpts()) &&
349*e038c9c4Sjoerg           getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",
350*e038c9c4Sjoerg                                          getLangOpts())) {
351*e038c9c4Sjoerg         if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {
352*e038c9c4Sjoerg           auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
353*e038c9c4Sjoerg           addImplicitTypedef("atomic_double", AtomicDoubleT);
3547330f729Sjoerg           Atomic64BitTypes.push_back(AtomicDoubleT);
3557330f729Sjoerg         }
356*e038c9c4Sjoerg         auto AtomicLongT = Context.getAtomicType(Context.LongTy);
357*e038c9c4Sjoerg         auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
358*e038c9c4Sjoerg         addImplicitTypedef("atomic_long", AtomicLongT);
359*e038c9c4Sjoerg         addImplicitTypedef("atomic_ulong", AtomicULongT);
3607330f729Sjoerg 
361*e038c9c4Sjoerg 
362*e038c9c4Sjoerg         if (Context.getTypeSize(Context.getSizeType()) == 64) {
363*e038c9c4Sjoerg           AddPointerSizeDependentTypes();
364*e038c9c4Sjoerg         }
365*e038c9c4Sjoerg       }
3667330f729Sjoerg     }
3677330f729Sjoerg 
3687330f729Sjoerg 
3697330f729Sjoerg #define EXT_OPAQUE_TYPE(ExtType, Id, Ext)                                      \
370*e038c9c4Sjoerg   if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) {                   \
3717330f729Sjoerg     addImplicitTypedef(#ExtType, Context.Id##Ty);                              \
372*e038c9c4Sjoerg   }
3737330f729Sjoerg #include "clang/Basic/OpenCLExtensionTypes.def"
3747330f729Sjoerg   }
3757330f729Sjoerg 
3767330f729Sjoerg   if (Context.getTargetInfo().hasAArch64SVETypes()) {
3777330f729Sjoerg #define SVE_TYPE(Name, Id, SingletonId) \
3787330f729Sjoerg     addImplicitTypedef(Name, Context.SingletonId);
3797330f729Sjoerg #include "clang/Basic/AArch64SVEACLETypes.def"
3807330f729Sjoerg   }
3817330f729Sjoerg 
382*e038c9c4Sjoerg   if (Context.getTargetInfo().getTriple().isPPC64() &&
383*e038c9c4Sjoerg       Context.getTargetInfo().hasFeature("paired-vector-memops")) {
384*e038c9c4Sjoerg     if (Context.getTargetInfo().hasFeature("mma")) {
385*e038c9c4Sjoerg #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
386*e038c9c4Sjoerg       addImplicitTypedef(#Name, Context.Id##Ty);
387*e038c9c4Sjoerg #include "clang/Basic/PPCTypes.def"
388*e038c9c4Sjoerg     }
389*e038c9c4Sjoerg #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
390*e038c9c4Sjoerg     addImplicitTypedef(#Name, Context.Id##Ty);
391*e038c9c4Sjoerg #include "clang/Basic/PPCTypes.def"
392*e038c9c4Sjoerg   }
393*e038c9c4Sjoerg 
394*e038c9c4Sjoerg   if (Context.getTargetInfo().hasRISCVVTypes()) {
395*e038c9c4Sjoerg #define RVV_TYPE(Name, Id, SingletonId)                                        \
396*e038c9c4Sjoerg   addImplicitTypedef(Name, Context.SingletonId);
397*e038c9c4Sjoerg #include "clang/Basic/RISCVVTypes.def"
398*e038c9c4Sjoerg   }
399*e038c9c4Sjoerg 
4007330f729Sjoerg   if (Context.getTargetInfo().hasBuiltinMSVaList()) {
4017330f729Sjoerg     DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
4027330f729Sjoerg     if (IdResolver.begin(MSVaList) == IdResolver.end())
4037330f729Sjoerg       PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
4047330f729Sjoerg   }
4057330f729Sjoerg 
4067330f729Sjoerg   DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
4077330f729Sjoerg   if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
4087330f729Sjoerg     PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
4097330f729Sjoerg }
4107330f729Sjoerg 
~Sema()4117330f729Sjoerg Sema::~Sema() {
412*e038c9c4Sjoerg   assert(InstantiatingSpecializations.empty() &&
413*e038c9c4Sjoerg          "failed to clean up an InstantiatingTemplate?");
414*e038c9c4Sjoerg 
4157330f729Sjoerg   if (VisContext) FreeVisContext();
4167330f729Sjoerg 
4177330f729Sjoerg   // Kill all the active scopes.
4187330f729Sjoerg   for (sema::FunctionScopeInfo *FSI : FunctionScopes)
4197330f729Sjoerg     delete FSI;
4207330f729Sjoerg 
4217330f729Sjoerg   // Tell the SemaConsumer to forget about us; we're going out of scope.
4227330f729Sjoerg   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
4237330f729Sjoerg     SC->ForgetSema();
4247330f729Sjoerg 
4257330f729Sjoerg   // Detach from the external Sema source.
4267330f729Sjoerg   if (ExternalSemaSource *ExternalSema
4277330f729Sjoerg         = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
4287330f729Sjoerg     ExternalSema->ForgetSema();
4297330f729Sjoerg 
4307330f729Sjoerg   // If Sema's ExternalSource is the multiplexer - we own it.
4317330f729Sjoerg   if (isMultiplexExternalSource)
4327330f729Sjoerg     delete ExternalSource;
4337330f729Sjoerg 
434*e038c9c4Sjoerg   // Delete cached satisfactions.
435*e038c9c4Sjoerg   std::vector<ConstraintSatisfaction *> Satisfactions;
436*e038c9c4Sjoerg   Satisfactions.reserve(Satisfactions.size());
437*e038c9c4Sjoerg   for (auto &Node : SatisfactionCache)
438*e038c9c4Sjoerg     Satisfactions.push_back(&Node);
439*e038c9c4Sjoerg   for (auto *Node : Satisfactions)
440*e038c9c4Sjoerg     delete Node;
441*e038c9c4Sjoerg 
4427330f729Sjoerg   threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
4437330f729Sjoerg 
4447330f729Sjoerg   // Destroys data sharing attributes stack for OpenMP
4457330f729Sjoerg   DestroyDataSharingAttributesStack();
4467330f729Sjoerg 
4477330f729Sjoerg   // Detach from the PP callback handler which outlives Sema since it's owned
4487330f729Sjoerg   // by the preprocessor.
4497330f729Sjoerg   SemaPPCallbackHandler->reset();
4507330f729Sjoerg }
4517330f729Sjoerg 
warnStackExhausted(SourceLocation Loc)4527330f729Sjoerg void Sema::warnStackExhausted(SourceLocation Loc) {
4537330f729Sjoerg   // Only warn about this once.
4547330f729Sjoerg   if (!WarnedStackExhausted) {
4557330f729Sjoerg     Diag(Loc, diag::warn_stack_exhausted);
4567330f729Sjoerg     WarnedStackExhausted = true;
4577330f729Sjoerg   }
4587330f729Sjoerg }
4597330f729Sjoerg 
runWithSufficientStackSpace(SourceLocation Loc,llvm::function_ref<void ()> Fn)4607330f729Sjoerg void Sema::runWithSufficientStackSpace(SourceLocation Loc,
4617330f729Sjoerg                                        llvm::function_ref<void()> Fn) {
4627330f729Sjoerg   clang::runWithSufficientStackSpace([&] { warnStackExhausted(Loc); }, Fn);
4637330f729Sjoerg }
4647330f729Sjoerg 
4657330f729Sjoerg /// makeUnavailableInSystemHeader - There is an error in the current
4667330f729Sjoerg /// context.  If we're still in a system header, and we can plausibly
4677330f729Sjoerg /// make the relevant declaration unavailable instead of erroring, do
4687330f729Sjoerg /// so and return true.
makeUnavailableInSystemHeader(SourceLocation loc,UnavailableAttr::ImplicitReason reason)4697330f729Sjoerg bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
4707330f729Sjoerg                                       UnavailableAttr::ImplicitReason reason) {
4717330f729Sjoerg   // If we're not in a function, it's an error.
4727330f729Sjoerg   FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
4737330f729Sjoerg   if (!fn) return false;
4747330f729Sjoerg 
4757330f729Sjoerg   // If we're in template instantiation, it's an error.
4767330f729Sjoerg   if (inTemplateInstantiation())
4777330f729Sjoerg     return false;
4787330f729Sjoerg 
4797330f729Sjoerg   // If that function's not in a system header, it's an error.
4807330f729Sjoerg   if (!Context.getSourceManager().isInSystemHeader(loc))
4817330f729Sjoerg     return false;
4827330f729Sjoerg 
4837330f729Sjoerg   // If the function is already unavailable, it's not an error.
4847330f729Sjoerg   if (fn->hasAttr<UnavailableAttr>()) return true;
4857330f729Sjoerg 
4867330f729Sjoerg   fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
4877330f729Sjoerg   return true;
4887330f729Sjoerg }
4897330f729Sjoerg 
getASTMutationListener() const4907330f729Sjoerg ASTMutationListener *Sema::getASTMutationListener() const {
4917330f729Sjoerg   return getASTConsumer().GetASTMutationListener();
4927330f729Sjoerg }
4937330f729Sjoerg 
4947330f729Sjoerg ///Registers an external source. If an external source already exists,
4957330f729Sjoerg /// creates a multiplex external source and appends to it.
4967330f729Sjoerg ///
4977330f729Sjoerg ///\param[in] E - A non-null external sema source.
4987330f729Sjoerg ///
addExternalSource(ExternalSemaSource * E)4997330f729Sjoerg void Sema::addExternalSource(ExternalSemaSource *E) {
5007330f729Sjoerg   assert(E && "Cannot use with NULL ptr");
5017330f729Sjoerg 
5027330f729Sjoerg   if (!ExternalSource) {
5037330f729Sjoerg     ExternalSource = E;
5047330f729Sjoerg     return;
5057330f729Sjoerg   }
5067330f729Sjoerg 
5077330f729Sjoerg   if (isMultiplexExternalSource)
5087330f729Sjoerg     static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
5097330f729Sjoerg   else {
5107330f729Sjoerg     ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
5117330f729Sjoerg     isMultiplexExternalSource = true;
5127330f729Sjoerg   }
5137330f729Sjoerg }
5147330f729Sjoerg 
5157330f729Sjoerg /// Print out statistics about the semantic analysis.
PrintStats() const5167330f729Sjoerg void Sema::PrintStats() const {
5177330f729Sjoerg   llvm::errs() << "\n*** Semantic Analysis Stats:\n";
5187330f729Sjoerg   llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
5197330f729Sjoerg 
5207330f729Sjoerg   BumpAlloc.PrintStats();
5217330f729Sjoerg   AnalysisWarnings.PrintStats();
5227330f729Sjoerg }
5237330f729Sjoerg 
diagnoseNullableToNonnullConversion(QualType DstType,QualType SrcType,SourceLocation Loc)5247330f729Sjoerg void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
5257330f729Sjoerg                                                QualType SrcType,
5267330f729Sjoerg                                                SourceLocation Loc) {
5277330f729Sjoerg   Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
528*e038c9c4Sjoerg   if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable &&
529*e038c9c4Sjoerg                            *ExprNullability != NullabilityKind::NullableResult))
5307330f729Sjoerg     return;
5317330f729Sjoerg 
5327330f729Sjoerg   Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
5337330f729Sjoerg   if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
5347330f729Sjoerg     return;
5357330f729Sjoerg 
5367330f729Sjoerg   Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
5377330f729Sjoerg }
5387330f729Sjoerg 
diagnoseZeroToNullptrConversion(CastKind Kind,const Expr * E)5397330f729Sjoerg void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) {
5407330f729Sjoerg   if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
5417330f729Sjoerg                       E->getBeginLoc()))
5427330f729Sjoerg     return;
5437330f729Sjoerg   // nullptr only exists from C++11 on, so don't warn on its absence earlier.
5447330f729Sjoerg   if (!getLangOpts().CPlusPlus11)
5457330f729Sjoerg     return;
5467330f729Sjoerg 
5477330f729Sjoerg   if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
5487330f729Sjoerg     return;
5497330f729Sjoerg   if (E->IgnoreParenImpCasts()->getType()->isNullPtrType())
5507330f729Sjoerg     return;
5517330f729Sjoerg 
552*e038c9c4Sjoerg   // Don't diagnose the conversion from a 0 literal to a null pointer argument
553*e038c9c4Sjoerg   // in a synthesized call to operator<=>.
554*e038c9c4Sjoerg   if (!CodeSynthesisContexts.empty() &&
555*e038c9c4Sjoerg       CodeSynthesisContexts.back().Kind ==
556*e038c9c4Sjoerg           CodeSynthesisContext::RewritingOperatorAsSpaceship)
557*e038c9c4Sjoerg     return;
558*e038c9c4Sjoerg 
5597330f729Sjoerg   // If it is a macro from system header, and if the macro name is not "NULL",
5607330f729Sjoerg   // do not warn.
5617330f729Sjoerg   SourceLocation MaybeMacroLoc = E->getBeginLoc();
5627330f729Sjoerg   if (Diags.getSuppressSystemWarnings() &&
5637330f729Sjoerg       SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
5647330f729Sjoerg       !findMacroSpelling(MaybeMacroLoc, "NULL"))
5657330f729Sjoerg     return;
5667330f729Sjoerg 
5677330f729Sjoerg   Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
5687330f729Sjoerg       << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
5697330f729Sjoerg }
5707330f729Sjoerg 
5717330f729Sjoerg /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
5727330f729Sjoerg /// If there is already an implicit cast, merge into the existing one.
5737330f729Sjoerg /// The result is of the given category.
ImpCastExprToType(Expr * E,QualType Ty,CastKind Kind,ExprValueKind VK,const CXXCastPath * BasePath,CheckedConversionKind CCK)5747330f729Sjoerg ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
5757330f729Sjoerg                                    CastKind Kind, ExprValueKind VK,
5767330f729Sjoerg                                    const CXXCastPath *BasePath,
5777330f729Sjoerg                                    CheckedConversionKind CCK) {
5787330f729Sjoerg #ifndef NDEBUG
5797330f729Sjoerg   if (VK == VK_RValue && !E->isRValue()) {
5807330f729Sjoerg     switch (Kind) {
5817330f729Sjoerg     default:
582*e038c9c4Sjoerg       llvm_unreachable(("can't implicitly cast lvalue to rvalue with this cast "
583*e038c9c4Sjoerg                         "kind: " +
584*e038c9c4Sjoerg                         std::string(CastExpr::getCastKindName(Kind)))
585*e038c9c4Sjoerg                            .c_str());
5867330f729Sjoerg     case CK_Dependent:
5877330f729Sjoerg     case CK_LValueToRValue:
5887330f729Sjoerg     case CK_ArrayToPointerDecay:
5897330f729Sjoerg     case CK_FunctionToPointerDecay:
5907330f729Sjoerg     case CK_ToVoid:
5917330f729Sjoerg     case CK_NonAtomicToAtomic:
5927330f729Sjoerg       break;
5937330f729Sjoerg     }
5947330f729Sjoerg   }
5957330f729Sjoerg   assert((VK == VK_RValue || Kind == CK_Dependent || !E->isRValue()) &&
5967330f729Sjoerg          "can't cast rvalue to lvalue");
5977330f729Sjoerg #endif
5987330f729Sjoerg 
5997330f729Sjoerg   diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc());
6007330f729Sjoerg   diagnoseZeroToNullptrConversion(Kind, E);
6017330f729Sjoerg 
6027330f729Sjoerg   QualType ExprTy = Context.getCanonicalType(E->getType());
6037330f729Sjoerg   QualType TypeTy = Context.getCanonicalType(Ty);
6047330f729Sjoerg 
6057330f729Sjoerg   if (ExprTy == TypeTy)
6067330f729Sjoerg     return E;
6077330f729Sjoerg 
6087330f729Sjoerg   // C++1z [conv.array]: The temporary materialization conversion is applied.
6097330f729Sjoerg   // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
6107330f729Sjoerg   if (Kind == CK_ArrayToPointerDecay && getLangOpts().CPlusPlus &&
6117330f729Sjoerg       E->getValueKind() == VK_RValue) {
6127330f729Sjoerg     // The temporary is an lvalue in C++98 and an xvalue otherwise.
6137330f729Sjoerg     ExprResult Materialized = CreateMaterializeTemporaryExpr(
6147330f729Sjoerg         E->getType(), E, !getLangOpts().CPlusPlus11);
6157330f729Sjoerg     if (Materialized.isInvalid())
6167330f729Sjoerg       return ExprError();
6177330f729Sjoerg     E = Materialized.get();
6187330f729Sjoerg   }
6197330f729Sjoerg 
6207330f729Sjoerg   if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
6217330f729Sjoerg     if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
6227330f729Sjoerg       ImpCast->setType(Ty);
6237330f729Sjoerg       ImpCast->setValueKind(VK);
6247330f729Sjoerg       return E;
6257330f729Sjoerg     }
6267330f729Sjoerg   }
6277330f729Sjoerg 
628*e038c9c4Sjoerg   return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
629*e038c9c4Sjoerg                                   CurFPFeatureOverrides());
6307330f729Sjoerg }
6317330f729Sjoerg 
6327330f729Sjoerg /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
6337330f729Sjoerg /// to the conversion from scalar type ScalarTy to the Boolean type.
ScalarTypeToBooleanCastKind(QualType ScalarTy)6347330f729Sjoerg CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
6357330f729Sjoerg   switch (ScalarTy->getScalarTypeKind()) {
6367330f729Sjoerg   case Type::STK_Bool: return CK_NoOp;
6377330f729Sjoerg   case Type::STK_CPointer: return CK_PointerToBoolean;
6387330f729Sjoerg   case Type::STK_BlockPointer: return CK_PointerToBoolean;
6397330f729Sjoerg   case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
6407330f729Sjoerg   case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
6417330f729Sjoerg   case Type::STK_Integral: return CK_IntegralToBoolean;
6427330f729Sjoerg   case Type::STK_Floating: return CK_FloatingToBoolean;
6437330f729Sjoerg   case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
6447330f729Sjoerg   case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
6457330f729Sjoerg   case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
6467330f729Sjoerg   }
6477330f729Sjoerg   llvm_unreachable("unknown scalar type kind");
6487330f729Sjoerg }
6497330f729Sjoerg 
6507330f729Sjoerg /// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
ShouldRemoveFromUnused(Sema * SemaRef,const DeclaratorDecl * D)6517330f729Sjoerg static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
6527330f729Sjoerg   if (D->getMostRecentDecl()->isUsed())
6537330f729Sjoerg     return true;
6547330f729Sjoerg 
6557330f729Sjoerg   if (D->isExternallyVisible())
6567330f729Sjoerg     return true;
6577330f729Sjoerg 
6587330f729Sjoerg   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6597330f729Sjoerg     // If this is a function template and none of its specializations is used,
6607330f729Sjoerg     // we should warn.
6617330f729Sjoerg     if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
6627330f729Sjoerg       for (const auto *Spec : Template->specializations())
6637330f729Sjoerg         if (ShouldRemoveFromUnused(SemaRef, Spec))
6647330f729Sjoerg           return true;
6657330f729Sjoerg 
6667330f729Sjoerg     // UnusedFileScopedDecls stores the first declaration.
6677330f729Sjoerg     // The declaration may have become definition so check again.
6687330f729Sjoerg     const FunctionDecl *DeclToCheck;
6697330f729Sjoerg     if (FD->hasBody(DeclToCheck))
6707330f729Sjoerg       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
6717330f729Sjoerg 
6727330f729Sjoerg     // Later redecls may add new information resulting in not having to warn,
6737330f729Sjoerg     // so check again.
6747330f729Sjoerg     DeclToCheck = FD->getMostRecentDecl();
6757330f729Sjoerg     if (DeclToCheck != FD)
6767330f729Sjoerg       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
6777330f729Sjoerg   }
6787330f729Sjoerg 
6797330f729Sjoerg   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6807330f729Sjoerg     // If a variable usable in constant expressions is referenced,
6817330f729Sjoerg     // don't warn if it isn't used: if the value of a variable is required
6827330f729Sjoerg     // for the computation of a constant expression, it doesn't make sense to
6837330f729Sjoerg     // warn even if the variable isn't odr-used.  (isReferenced doesn't
6847330f729Sjoerg     // precisely reflect that, but it's a decent approximation.)
6857330f729Sjoerg     if (VD->isReferenced() &&
6867330f729Sjoerg         VD->mightBeUsableInConstantExpressions(SemaRef->Context))
6877330f729Sjoerg       return true;
6887330f729Sjoerg 
6897330f729Sjoerg     if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
6907330f729Sjoerg       // If this is a variable template and none of its specializations is used,
6917330f729Sjoerg       // we should warn.
6927330f729Sjoerg       for (const auto *Spec : Template->specializations())
6937330f729Sjoerg         if (ShouldRemoveFromUnused(SemaRef, Spec))
6947330f729Sjoerg           return true;
6957330f729Sjoerg 
6967330f729Sjoerg     // UnusedFileScopedDecls stores the first declaration.
6977330f729Sjoerg     // The declaration may have become definition so check again.
6987330f729Sjoerg     const VarDecl *DeclToCheck = VD->getDefinition();
6997330f729Sjoerg     if (DeclToCheck)
7007330f729Sjoerg       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
7017330f729Sjoerg 
7027330f729Sjoerg     // Later redecls may add new information resulting in not having to warn,
7037330f729Sjoerg     // so check again.
7047330f729Sjoerg     DeclToCheck = VD->getMostRecentDecl();
7057330f729Sjoerg     if (DeclToCheck != VD)
7067330f729Sjoerg       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
7077330f729Sjoerg   }
7087330f729Sjoerg 
7097330f729Sjoerg   return false;
7107330f729Sjoerg }
7117330f729Sjoerg 
isFunctionOrVarDeclExternC(NamedDecl * ND)7127330f729Sjoerg static bool isFunctionOrVarDeclExternC(NamedDecl *ND) {
7137330f729Sjoerg   if (auto *FD = dyn_cast<FunctionDecl>(ND))
7147330f729Sjoerg     return FD->isExternC();
7157330f729Sjoerg   return cast<VarDecl>(ND)->isExternC();
7167330f729Sjoerg }
7177330f729Sjoerg 
7187330f729Sjoerg /// Determine whether ND is an external-linkage function or variable whose
7197330f729Sjoerg /// type has no linkage.
isExternalWithNoLinkageType(ValueDecl * VD)7207330f729Sjoerg bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) {
7217330f729Sjoerg   // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
7227330f729Sjoerg   // because we also want to catch the case where its type has VisibleNoLinkage,
7237330f729Sjoerg   // which does not affect the linkage of VD.
7247330f729Sjoerg   return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
7257330f729Sjoerg          !isExternalFormalLinkage(VD->getType()->getLinkage()) &&
7267330f729Sjoerg          !isFunctionOrVarDeclExternC(VD);
7277330f729Sjoerg }
7287330f729Sjoerg 
7297330f729Sjoerg /// Obtains a sorted list of functions and variables that are undefined but
7307330f729Sjoerg /// ODR-used.
getUndefinedButUsed(SmallVectorImpl<std::pair<NamedDecl *,SourceLocation>> & Undefined)7317330f729Sjoerg void Sema::getUndefinedButUsed(
7327330f729Sjoerg     SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
7337330f729Sjoerg   for (const auto &UndefinedUse : UndefinedButUsed) {
7347330f729Sjoerg     NamedDecl *ND = UndefinedUse.first;
7357330f729Sjoerg 
7367330f729Sjoerg     // Ignore attributes that have become invalid.
7377330f729Sjoerg     if (ND->isInvalidDecl()) continue;
7387330f729Sjoerg 
7397330f729Sjoerg     // __attribute__((weakref)) is basically a definition.
7407330f729Sjoerg     if (ND->hasAttr<WeakRefAttr>()) continue;
7417330f729Sjoerg 
7427330f729Sjoerg     if (isa<CXXDeductionGuideDecl>(ND))
7437330f729Sjoerg       continue;
7447330f729Sjoerg 
7457330f729Sjoerg     if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
7467330f729Sjoerg       // An exported function will always be emitted when defined, so even if
7477330f729Sjoerg       // the function is inline, it doesn't have to be emitted in this TU. An
7487330f729Sjoerg       // imported function implies that it has been exported somewhere else.
7497330f729Sjoerg       continue;
7507330f729Sjoerg     }
7517330f729Sjoerg 
7527330f729Sjoerg     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
7537330f729Sjoerg       if (FD->isDefined())
7547330f729Sjoerg         continue;
7557330f729Sjoerg       if (FD->isExternallyVisible() &&
7567330f729Sjoerg           !isExternalWithNoLinkageType(FD) &&
7577330f729Sjoerg           !FD->getMostRecentDecl()->isInlined() &&
7587330f729Sjoerg           !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
7597330f729Sjoerg         continue;
7607330f729Sjoerg       if (FD->getBuiltinID())
7617330f729Sjoerg         continue;
7627330f729Sjoerg     } else {
7637330f729Sjoerg       auto *VD = cast<VarDecl>(ND);
7647330f729Sjoerg       if (VD->hasDefinition() != VarDecl::DeclarationOnly)
7657330f729Sjoerg         continue;
7667330f729Sjoerg       if (VD->isExternallyVisible() &&
7677330f729Sjoerg           !isExternalWithNoLinkageType(VD) &&
7687330f729Sjoerg           !VD->getMostRecentDecl()->isInline() &&
7697330f729Sjoerg           !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
7707330f729Sjoerg         continue;
7717330f729Sjoerg 
7727330f729Sjoerg       // Skip VarDecls that lack formal definitions but which we know are in
7737330f729Sjoerg       // fact defined somewhere.
7747330f729Sjoerg       if (VD->isKnownToBeDefined())
7757330f729Sjoerg         continue;
7767330f729Sjoerg     }
7777330f729Sjoerg 
7787330f729Sjoerg     Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
7797330f729Sjoerg   }
7807330f729Sjoerg }
7817330f729Sjoerg 
7827330f729Sjoerg /// checkUndefinedButUsed - Check for undefined objects with internal linkage
7837330f729Sjoerg /// or that are inline.
checkUndefinedButUsed(Sema & S)7847330f729Sjoerg static void checkUndefinedButUsed(Sema &S) {
7857330f729Sjoerg   if (S.UndefinedButUsed.empty()) return;
7867330f729Sjoerg 
7877330f729Sjoerg   // Collect all the still-undefined entities with internal linkage.
7887330f729Sjoerg   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
7897330f729Sjoerg   S.getUndefinedButUsed(Undefined);
7907330f729Sjoerg   if (Undefined.empty()) return;
7917330f729Sjoerg 
7927330f729Sjoerg   for (auto Undef : Undefined) {
7937330f729Sjoerg     ValueDecl *VD = cast<ValueDecl>(Undef.first);
7947330f729Sjoerg     SourceLocation UseLoc = Undef.second;
7957330f729Sjoerg 
7967330f729Sjoerg     if (S.isExternalWithNoLinkageType(VD)) {
7977330f729Sjoerg       // C++ [basic.link]p8:
7987330f729Sjoerg       //   A type without linkage shall not be used as the type of a variable
7997330f729Sjoerg       //   or function with external linkage unless
8007330f729Sjoerg       //    -- the entity has C language linkage
8017330f729Sjoerg       //    -- the entity is not odr-used or is defined in the same TU
8027330f729Sjoerg       //
8037330f729Sjoerg       // As an extension, accept this in cases where the type is externally
8047330f729Sjoerg       // visible, since the function or variable actually can be defined in
8057330f729Sjoerg       // another translation unit in that case.
8067330f729Sjoerg       S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
8077330f729Sjoerg                                     ? diag::ext_undefined_internal_type
8087330f729Sjoerg                                     : diag::err_undefined_internal_type)
8097330f729Sjoerg         << isa<VarDecl>(VD) << VD;
8107330f729Sjoerg     } else if (!VD->isExternallyVisible()) {
8117330f729Sjoerg       // FIXME: We can promote this to an error. The function or variable can't
8127330f729Sjoerg       // be defined anywhere else, so the program must necessarily violate the
8137330f729Sjoerg       // one definition rule.
8147330f729Sjoerg       S.Diag(VD->getLocation(), diag::warn_undefined_internal)
8157330f729Sjoerg         << isa<VarDecl>(VD) << VD;
8167330f729Sjoerg     } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
8177330f729Sjoerg       (void)FD;
8187330f729Sjoerg       assert(FD->getMostRecentDecl()->isInlined() &&
8197330f729Sjoerg              "used object requires definition but isn't inline or internal?");
8207330f729Sjoerg       // FIXME: This is ill-formed; we should reject.
8217330f729Sjoerg       S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
8227330f729Sjoerg     } else {
8237330f729Sjoerg       assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
8247330f729Sjoerg              "used var requires definition but isn't inline or internal?");
8257330f729Sjoerg       S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
8267330f729Sjoerg     }
8277330f729Sjoerg     if (UseLoc.isValid())
8287330f729Sjoerg       S.Diag(UseLoc, diag::note_used_here);
8297330f729Sjoerg   }
8307330f729Sjoerg 
8317330f729Sjoerg   S.UndefinedButUsed.clear();
8327330f729Sjoerg }
8337330f729Sjoerg 
LoadExternalWeakUndeclaredIdentifiers()8347330f729Sjoerg void Sema::LoadExternalWeakUndeclaredIdentifiers() {
8357330f729Sjoerg   if (!ExternalSource)
8367330f729Sjoerg     return;
8377330f729Sjoerg 
8387330f729Sjoerg   SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
8397330f729Sjoerg   ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
8407330f729Sjoerg   for (auto &WeakID : WeakIDs)
8417330f729Sjoerg     WeakUndeclaredIdentifiers.insert(WeakID);
8427330f729Sjoerg }
8437330f729Sjoerg 
8447330f729Sjoerg 
8457330f729Sjoerg typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
8467330f729Sjoerg 
8477330f729Sjoerg /// Returns true, if all methods and nested classes of the given
8487330f729Sjoerg /// CXXRecordDecl are defined in this translation unit.
8497330f729Sjoerg ///
8507330f729Sjoerg /// Should only be called from ActOnEndOfTranslationUnit so that all
8517330f729Sjoerg /// definitions are actually read.
MethodsAndNestedClassesComplete(const CXXRecordDecl * RD,RecordCompleteMap & MNCComplete)8527330f729Sjoerg static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
8537330f729Sjoerg                                             RecordCompleteMap &MNCComplete) {
8547330f729Sjoerg   RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
8557330f729Sjoerg   if (Cache != MNCComplete.end())
8567330f729Sjoerg     return Cache->second;
8577330f729Sjoerg   if (!RD->isCompleteDefinition())
8587330f729Sjoerg     return false;
8597330f729Sjoerg   bool Complete = true;
8607330f729Sjoerg   for (DeclContext::decl_iterator I = RD->decls_begin(),
8617330f729Sjoerg                                   E = RD->decls_end();
8627330f729Sjoerg        I != E && Complete; ++I) {
8637330f729Sjoerg     if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
8647330f729Sjoerg       Complete = M->isDefined() || M->isDefaulted() ||
8657330f729Sjoerg                  (M->isPure() && !isa<CXXDestructorDecl>(M));
8667330f729Sjoerg     else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
8677330f729Sjoerg       // If the template function is marked as late template parsed at this
8687330f729Sjoerg       // point, it has not been instantiated and therefore we have not
8697330f729Sjoerg       // performed semantic analysis on it yet, so we cannot know if the type
8707330f729Sjoerg       // can be considered complete.
8717330f729Sjoerg       Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
8727330f729Sjoerg                   F->getTemplatedDecl()->isDefined();
8737330f729Sjoerg     else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
8747330f729Sjoerg       if (R->isInjectedClassName())
8757330f729Sjoerg         continue;
8767330f729Sjoerg       if (R->hasDefinition())
8777330f729Sjoerg         Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
8787330f729Sjoerg                                                    MNCComplete);
8797330f729Sjoerg       else
8807330f729Sjoerg         Complete = false;
8817330f729Sjoerg     }
8827330f729Sjoerg   }
8837330f729Sjoerg   MNCComplete[RD] = Complete;
8847330f729Sjoerg   return Complete;
8857330f729Sjoerg }
8867330f729Sjoerg 
8877330f729Sjoerg /// Returns true, if the given CXXRecordDecl is fully defined in this
8887330f729Sjoerg /// translation unit, i.e. all methods are defined or pure virtual and all
8897330f729Sjoerg /// friends, friend functions and nested classes are fully defined in this
8907330f729Sjoerg /// translation unit.
8917330f729Sjoerg ///
8927330f729Sjoerg /// Should only be called from ActOnEndOfTranslationUnit so that all
8937330f729Sjoerg /// definitions are actually read.
IsRecordFullyDefined(const CXXRecordDecl * RD,RecordCompleteMap & RecordsComplete,RecordCompleteMap & MNCComplete)8947330f729Sjoerg static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
8957330f729Sjoerg                                  RecordCompleteMap &RecordsComplete,
8967330f729Sjoerg                                  RecordCompleteMap &MNCComplete) {
8977330f729Sjoerg   RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
8987330f729Sjoerg   if (Cache != RecordsComplete.end())
8997330f729Sjoerg     return Cache->second;
9007330f729Sjoerg   bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
9017330f729Sjoerg   for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
9027330f729Sjoerg                                       E = RD->friend_end();
9037330f729Sjoerg        I != E && Complete; ++I) {
9047330f729Sjoerg     // Check if friend classes and methods are complete.
9057330f729Sjoerg     if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
9067330f729Sjoerg       // Friend classes are available as the TypeSourceInfo of the FriendDecl.
9077330f729Sjoerg       if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
9087330f729Sjoerg         Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
9097330f729Sjoerg       else
9107330f729Sjoerg         Complete = false;
9117330f729Sjoerg     } else {
9127330f729Sjoerg       // Friend functions are available through the NamedDecl of FriendDecl.
9137330f729Sjoerg       if (const FunctionDecl *FD =
9147330f729Sjoerg           dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
9157330f729Sjoerg         Complete = FD->isDefined();
9167330f729Sjoerg       else
9177330f729Sjoerg         // This is a template friend, give up.
9187330f729Sjoerg         Complete = false;
9197330f729Sjoerg     }
9207330f729Sjoerg   }
9217330f729Sjoerg   RecordsComplete[RD] = Complete;
9227330f729Sjoerg   return Complete;
9237330f729Sjoerg }
9247330f729Sjoerg 
emitAndClearUnusedLocalTypedefWarnings()9257330f729Sjoerg void Sema::emitAndClearUnusedLocalTypedefWarnings() {
9267330f729Sjoerg   if (ExternalSource)
9277330f729Sjoerg     ExternalSource->ReadUnusedLocalTypedefNameCandidates(
9287330f729Sjoerg         UnusedLocalTypedefNameCandidates);
9297330f729Sjoerg   for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
9307330f729Sjoerg     if (TD->isReferenced())
9317330f729Sjoerg       continue;
9327330f729Sjoerg     Diag(TD->getLocation(), diag::warn_unused_local_typedef)
9337330f729Sjoerg         << isa<TypeAliasDecl>(TD) << TD->getDeclName();
9347330f729Sjoerg   }
9357330f729Sjoerg   UnusedLocalTypedefNameCandidates.clear();
9367330f729Sjoerg }
9377330f729Sjoerg 
9387330f729Sjoerg /// This is called before the very first declaration in the translation unit
9397330f729Sjoerg /// is parsed. Note that the ASTContext may have already injected some
9407330f729Sjoerg /// declarations.
ActOnStartOfTranslationUnit()9417330f729Sjoerg void Sema::ActOnStartOfTranslationUnit() {
9427330f729Sjoerg   if (getLangOpts().ModulesTS &&
9437330f729Sjoerg       (getLangOpts().getCompilingModule() == LangOptions::CMK_ModuleInterface ||
9447330f729Sjoerg        getLangOpts().getCompilingModule() == LangOptions::CMK_None)) {
9457330f729Sjoerg     // We start in an implied global module fragment.
9467330f729Sjoerg     SourceLocation StartOfTU =
9477330f729Sjoerg         SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
9487330f729Sjoerg     ActOnGlobalModuleFragmentDecl(StartOfTU);
9497330f729Sjoerg     ModuleScopes.back().ImplicitGlobalModuleFragment = true;
9507330f729Sjoerg   }
9517330f729Sjoerg }
9527330f729Sjoerg 
ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind)9537330f729Sjoerg void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {
9547330f729Sjoerg   // No explicit actions are required at the end of the global module fragment.
9557330f729Sjoerg   if (Kind == TUFragmentKind::Global)
9567330f729Sjoerg     return;
9577330f729Sjoerg 
9587330f729Sjoerg   // Transfer late parsed template instantiations over to the pending template
9597330f729Sjoerg   // instantiation list. During normal compilation, the late template parser
9607330f729Sjoerg   // will be installed and instantiating these templates will succeed.
9617330f729Sjoerg   //
9627330f729Sjoerg   // If we are building a TU prefix for serialization, it is also safe to
9637330f729Sjoerg   // transfer these over, even though they are not parsed. The end of the TU
9647330f729Sjoerg   // should be outside of any eager template instantiation scope, so when this
9657330f729Sjoerg   // AST is deserialized, these templates will not be parsed until the end of
9667330f729Sjoerg   // the combined TU.
9677330f729Sjoerg   PendingInstantiations.insert(PendingInstantiations.end(),
9687330f729Sjoerg                                LateParsedInstantiations.begin(),
9697330f729Sjoerg                                LateParsedInstantiations.end());
9707330f729Sjoerg   LateParsedInstantiations.clear();
9717330f729Sjoerg 
9727330f729Sjoerg   // If DefinedUsedVTables ends up marking any virtual member functions it
9737330f729Sjoerg   // might lead to more pending template instantiations, which we then need
9747330f729Sjoerg   // to instantiate.
9757330f729Sjoerg   DefineUsedVTables();
9767330f729Sjoerg 
9777330f729Sjoerg   // C++: Perform implicit template instantiations.
9787330f729Sjoerg   //
9797330f729Sjoerg   // FIXME: When we perform these implicit instantiations, we do not
9807330f729Sjoerg   // carefully keep track of the point of instantiation (C++ [temp.point]).
9817330f729Sjoerg   // This means that name lookup that occurs within the template
9827330f729Sjoerg   // instantiation will always happen at the end of the translation unit,
9837330f729Sjoerg   // so it will find some names that are not required to be found. This is
9847330f729Sjoerg   // valid, but we could do better by diagnosing if an instantiation uses a
9857330f729Sjoerg   // name that was not visible at its first point of instantiation.
9867330f729Sjoerg   if (ExternalSource) {
9877330f729Sjoerg     // Load pending instantiations from the external source.
9887330f729Sjoerg     SmallVector<PendingImplicitInstantiation, 4> Pending;
9897330f729Sjoerg     ExternalSource->ReadPendingInstantiations(Pending);
9907330f729Sjoerg     for (auto PII : Pending)
9917330f729Sjoerg       if (auto Func = dyn_cast<FunctionDecl>(PII.first))
9927330f729Sjoerg         Func->setInstantiationIsPending(true);
9937330f729Sjoerg     PendingInstantiations.insert(PendingInstantiations.begin(),
9947330f729Sjoerg                                  Pending.begin(), Pending.end());
9957330f729Sjoerg   }
9967330f729Sjoerg 
9977330f729Sjoerg   {
998*e038c9c4Sjoerg     llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
9997330f729Sjoerg     PerformPendingInstantiations();
10007330f729Sjoerg   }
10017330f729Sjoerg 
1002*e038c9c4Sjoerg   emitDeferredDiags();
10037330f729Sjoerg 
10047330f729Sjoerg   assert(LateParsedInstantiations.empty() &&
10057330f729Sjoerg          "end of TU template instantiation should not create more "
10067330f729Sjoerg          "late-parsed templates");
10077330f729Sjoerg 
10087330f729Sjoerg   // Report diagnostics for uncorrected delayed typos. Ideally all of them
10097330f729Sjoerg   // should have been corrected by that time, but it is very hard to cover all
10107330f729Sjoerg   // cases in practice.
10117330f729Sjoerg   for (const auto &Typo : DelayedTypos) {
10127330f729Sjoerg     // We pass an empty TypoCorrection to indicate no correction was performed.
10137330f729Sjoerg     Typo.second.DiagHandler(TypoCorrection());
10147330f729Sjoerg   }
10157330f729Sjoerg   DelayedTypos.clear();
10167330f729Sjoerg }
10177330f729Sjoerg 
10187330f729Sjoerg /// ActOnEndOfTranslationUnit - This is called at the very end of the
10197330f729Sjoerg /// translation unit when EOF is reached and all but the top-level scope is
10207330f729Sjoerg /// popped.
ActOnEndOfTranslationUnit()10217330f729Sjoerg void Sema::ActOnEndOfTranslationUnit() {
10227330f729Sjoerg   assert(DelayedDiagnostics.getCurrentPool() == nullptr
10237330f729Sjoerg          && "reached end of translation unit with a pool attached?");
10247330f729Sjoerg 
10257330f729Sjoerg   // If code completion is enabled, don't perform any end-of-translation-unit
10267330f729Sjoerg   // work.
10277330f729Sjoerg   if (PP.isCodeCompletionEnabled())
10287330f729Sjoerg     return;
10297330f729Sjoerg 
10307330f729Sjoerg   // Complete translation units and modules define vtables and perform implicit
10317330f729Sjoerg   // instantiations. PCH files do not.
10327330f729Sjoerg   if (TUKind != TU_Prefix) {
10337330f729Sjoerg     DiagnoseUseOfUnimplementedSelectors();
10347330f729Sjoerg 
10357330f729Sjoerg     ActOnEndOfTranslationUnitFragment(
10367330f729Sjoerg         !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
10377330f729Sjoerg                                      Module::PrivateModuleFragment
10387330f729Sjoerg             ? TUFragmentKind::Private
10397330f729Sjoerg             : TUFragmentKind::Normal);
10407330f729Sjoerg 
10417330f729Sjoerg     if (LateTemplateParserCleanup)
10427330f729Sjoerg       LateTemplateParserCleanup(OpaqueParser);
10437330f729Sjoerg 
10447330f729Sjoerg     CheckDelayedMemberExceptionSpecs();
10457330f729Sjoerg   } else {
10467330f729Sjoerg     // If we are building a TU prefix for serialization, it is safe to transfer
10477330f729Sjoerg     // these over, even though they are not parsed. The end of the TU should be
10487330f729Sjoerg     // outside of any eager template instantiation scope, so when this AST is
10497330f729Sjoerg     // deserialized, these templates will not be parsed until the end of the
10507330f729Sjoerg     // combined TU.
10517330f729Sjoerg     PendingInstantiations.insert(PendingInstantiations.end(),
10527330f729Sjoerg                                  LateParsedInstantiations.begin(),
10537330f729Sjoerg                                  LateParsedInstantiations.end());
10547330f729Sjoerg     LateParsedInstantiations.clear();
1055*e038c9c4Sjoerg 
1056*e038c9c4Sjoerg     if (LangOpts.PCHInstantiateTemplates) {
1057*e038c9c4Sjoerg       llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1058*e038c9c4Sjoerg       PerformPendingInstantiations();
1059*e038c9c4Sjoerg     }
10607330f729Sjoerg   }
10617330f729Sjoerg 
1062*e038c9c4Sjoerg   DiagnoseUnterminatedPragmaAlignPack();
10637330f729Sjoerg   DiagnoseUnterminatedPragmaAttribute();
10647330f729Sjoerg 
10657330f729Sjoerg   // All delayed member exception specs should be checked or we end up accepting
10667330f729Sjoerg   // incompatible declarations.
10677330f729Sjoerg   assert(DelayedOverridingExceptionSpecChecks.empty());
10687330f729Sjoerg   assert(DelayedEquivalentExceptionSpecChecks.empty());
10697330f729Sjoerg 
10707330f729Sjoerg   // All dllexport classes should have been processed already.
10717330f729Sjoerg   assert(DelayedDllExportClasses.empty());
10727330f729Sjoerg   assert(DelayedDllExportMemberFunctions.empty());
10737330f729Sjoerg 
10747330f729Sjoerg   // Remove file scoped decls that turned out to be used.
10757330f729Sjoerg   UnusedFileScopedDecls.erase(
10767330f729Sjoerg       std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
10777330f729Sjoerg                      UnusedFileScopedDecls.end(),
10787330f729Sjoerg                      [this](const DeclaratorDecl *DD) {
10797330f729Sjoerg                        return ShouldRemoveFromUnused(this, DD);
10807330f729Sjoerg                      }),
10817330f729Sjoerg       UnusedFileScopedDecls.end());
10827330f729Sjoerg 
10837330f729Sjoerg   if (TUKind == TU_Prefix) {
10847330f729Sjoerg     // Translation unit prefixes don't need any of the checking below.
10857330f729Sjoerg     if (!PP.isIncrementalProcessingEnabled())
10867330f729Sjoerg       TUScope = nullptr;
10877330f729Sjoerg     return;
10887330f729Sjoerg   }
10897330f729Sjoerg 
10907330f729Sjoerg   // Check for #pragma weak identifiers that were never declared
10917330f729Sjoerg   LoadExternalWeakUndeclaredIdentifiers();
10927330f729Sjoerg   for (auto WeakID : WeakUndeclaredIdentifiers) {
10937330f729Sjoerg     if (WeakID.second.getUsed())
10947330f729Sjoerg       continue;
10957330f729Sjoerg 
10967330f729Sjoerg     Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
10977330f729Sjoerg                                       LookupOrdinaryName);
10987330f729Sjoerg     if (PrevDecl != nullptr &&
10997330f729Sjoerg         !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
11007330f729Sjoerg       Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
11017330f729Sjoerg           << "'weak'" << ExpectedVariableOrFunction;
11027330f729Sjoerg     else
11037330f729Sjoerg       Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
11047330f729Sjoerg           << WeakID.first;
11057330f729Sjoerg   }
11067330f729Sjoerg 
11077330f729Sjoerg   if (LangOpts.CPlusPlus11 &&
11087330f729Sjoerg       !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
11097330f729Sjoerg     CheckDelegatingCtorCycles();
11107330f729Sjoerg 
11117330f729Sjoerg   if (!Diags.hasErrorOccurred()) {
11127330f729Sjoerg     if (ExternalSource)
11137330f729Sjoerg       ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
11147330f729Sjoerg     checkUndefinedButUsed(*this);
11157330f729Sjoerg   }
11167330f729Sjoerg 
11177330f729Sjoerg   // A global-module-fragment is only permitted within a module unit.
11187330f729Sjoerg   bool DiagnosedMissingModuleDeclaration = false;
11197330f729Sjoerg   if (!ModuleScopes.empty() &&
11207330f729Sjoerg       ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment &&
11217330f729Sjoerg       !ModuleScopes.back().ImplicitGlobalModuleFragment) {
11227330f729Sjoerg     Diag(ModuleScopes.back().BeginLoc,
11237330f729Sjoerg          diag::err_module_declaration_missing_after_global_module_introducer);
11247330f729Sjoerg     DiagnosedMissingModuleDeclaration = true;
11257330f729Sjoerg   }
11267330f729Sjoerg 
11277330f729Sjoerg   if (TUKind == TU_Module) {
11287330f729Sjoerg     // If we are building a module interface unit, we need to have seen the
11297330f729Sjoerg     // module declaration by now.
11307330f729Sjoerg     if (getLangOpts().getCompilingModule() ==
11317330f729Sjoerg             LangOptions::CMK_ModuleInterface &&
11327330f729Sjoerg         (ModuleScopes.empty() ||
11337330f729Sjoerg          !ModuleScopes.back().Module->isModulePurview()) &&
11347330f729Sjoerg         !DiagnosedMissingModuleDeclaration) {
11357330f729Sjoerg       // FIXME: Make a better guess as to where to put the module declaration.
11367330f729Sjoerg       Diag(getSourceManager().getLocForStartOfFile(
11377330f729Sjoerg                getSourceManager().getMainFileID()),
11387330f729Sjoerg            diag::err_module_declaration_missing);
11397330f729Sjoerg     }
11407330f729Sjoerg 
11417330f729Sjoerg     // If we are building a module, resolve all of the exported declarations
11427330f729Sjoerg     // now.
11437330f729Sjoerg     if (Module *CurrentModule = PP.getCurrentModule()) {
11447330f729Sjoerg       ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
11457330f729Sjoerg 
11467330f729Sjoerg       SmallVector<Module *, 2> Stack;
11477330f729Sjoerg       Stack.push_back(CurrentModule);
11487330f729Sjoerg       while (!Stack.empty()) {
11497330f729Sjoerg         Module *Mod = Stack.pop_back_val();
11507330f729Sjoerg 
11517330f729Sjoerg         // Resolve the exported declarations and conflicts.
11527330f729Sjoerg         // FIXME: Actually complain, once we figure out how to teach the
11537330f729Sjoerg         // diagnostic client to deal with complaints in the module map at this
11547330f729Sjoerg         // point.
11557330f729Sjoerg         ModMap.resolveExports(Mod, /*Complain=*/false);
11567330f729Sjoerg         ModMap.resolveUses(Mod, /*Complain=*/false);
11577330f729Sjoerg         ModMap.resolveConflicts(Mod, /*Complain=*/false);
11587330f729Sjoerg 
11597330f729Sjoerg         // Queue the submodules, so their exports will also be resolved.
11607330f729Sjoerg         Stack.append(Mod->submodule_begin(), Mod->submodule_end());
11617330f729Sjoerg       }
11627330f729Sjoerg     }
11637330f729Sjoerg 
11647330f729Sjoerg     // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
11657330f729Sjoerg     // modules when they are built, not every time they are used.
11667330f729Sjoerg     emitAndClearUnusedLocalTypedefWarnings();
11677330f729Sjoerg   }
11687330f729Sjoerg 
11697330f729Sjoerg   // C99 6.9.2p2:
11707330f729Sjoerg   //   A declaration of an identifier for an object that has file
11717330f729Sjoerg   //   scope without an initializer, and without a storage-class
11727330f729Sjoerg   //   specifier or with the storage-class specifier static,
11737330f729Sjoerg   //   constitutes a tentative definition. If a translation unit
11747330f729Sjoerg   //   contains one or more tentative definitions for an identifier,
11757330f729Sjoerg   //   and the translation unit contains no external definition for
11767330f729Sjoerg   //   that identifier, then the behavior is exactly as if the
11777330f729Sjoerg   //   translation unit contains a file scope declaration of that
11787330f729Sjoerg   //   identifier, with the composite type as of the end of the
11797330f729Sjoerg   //   translation unit, with an initializer equal to 0.
11807330f729Sjoerg   llvm::SmallSet<VarDecl *, 32> Seen;
11817330f729Sjoerg   for (TentativeDefinitionsType::iterator
11827330f729Sjoerg             T = TentativeDefinitions.begin(ExternalSource),
11837330f729Sjoerg          TEnd = TentativeDefinitions.end();
11847330f729Sjoerg        T != TEnd; ++T) {
11857330f729Sjoerg     VarDecl *VD = (*T)->getActingDefinition();
11867330f729Sjoerg 
11877330f729Sjoerg     // If the tentative definition was completed, getActingDefinition() returns
11887330f729Sjoerg     // null. If we've already seen this variable before, insert()'s second
11897330f729Sjoerg     // return value is false.
11907330f729Sjoerg     if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
11917330f729Sjoerg       continue;
11927330f729Sjoerg 
11937330f729Sjoerg     if (const IncompleteArrayType *ArrayT
11947330f729Sjoerg         = Context.getAsIncompleteArrayType(VD->getType())) {
11957330f729Sjoerg       // Set the length of the array to 1 (C99 6.9.2p5).
11967330f729Sjoerg       Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
11977330f729Sjoerg       llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
11987330f729Sjoerg       QualType T = Context.getConstantArrayType(ArrayT->getElementType(), One,
11997330f729Sjoerg                                                 nullptr, ArrayType::Normal, 0);
12007330f729Sjoerg       VD->setType(T);
12017330f729Sjoerg     } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
12027330f729Sjoerg                                    diag::err_tentative_def_incomplete_type))
12037330f729Sjoerg       VD->setInvalidDecl();
12047330f729Sjoerg 
12057330f729Sjoerg     // No initialization is performed for a tentative definition.
12067330f729Sjoerg     CheckCompleteVariableDeclaration(VD);
12077330f729Sjoerg 
12087330f729Sjoerg     // Notify the consumer that we've completed a tentative definition.
12097330f729Sjoerg     if (!VD->isInvalidDecl())
12107330f729Sjoerg       Consumer.CompleteTentativeDefinition(VD);
12117330f729Sjoerg   }
12127330f729Sjoerg 
1213*e038c9c4Sjoerg   for (auto D : ExternalDeclarations) {
1214*e038c9c4Sjoerg     if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())
1215*e038c9c4Sjoerg       continue;
1216*e038c9c4Sjoerg 
1217*e038c9c4Sjoerg     Consumer.CompleteExternalDeclaration(D);
1218*e038c9c4Sjoerg   }
1219*e038c9c4Sjoerg 
12207330f729Sjoerg   // If there were errors, disable 'unused' warnings since they will mostly be
12217330f729Sjoerg   // noise. Don't warn for a use from a module: either we should warn on all
12227330f729Sjoerg   // file-scope declarations in modules or not at all, but whether the
12237330f729Sjoerg   // declaration is used is immaterial.
12247330f729Sjoerg   if (!Diags.hasErrorOccurred() && TUKind != TU_Module) {
12257330f729Sjoerg     // Output warning for unused file scoped decls.
12267330f729Sjoerg     for (UnusedFileScopedDeclsType::iterator
12277330f729Sjoerg            I = UnusedFileScopedDecls.begin(ExternalSource),
12287330f729Sjoerg            E = UnusedFileScopedDecls.end(); I != E; ++I) {
12297330f729Sjoerg       if (ShouldRemoveFromUnused(this, *I))
12307330f729Sjoerg         continue;
12317330f729Sjoerg 
12327330f729Sjoerg       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
12337330f729Sjoerg         const FunctionDecl *DiagD;
12347330f729Sjoerg         if (!FD->hasBody(DiagD))
12357330f729Sjoerg           DiagD = FD;
12367330f729Sjoerg         if (DiagD->isDeleted())
12377330f729Sjoerg           continue; // Deleted functions are supposed to be unused.
12387330f729Sjoerg         if (DiagD->isReferenced()) {
12397330f729Sjoerg           if (isa<CXXMethodDecl>(DiagD))
12407330f729Sjoerg             Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1241*e038c9c4Sjoerg                 << DiagD;
12427330f729Sjoerg           else {
12437330f729Sjoerg             if (FD->getStorageClass() == SC_Static &&
12447330f729Sjoerg                 !FD->isInlineSpecified() &&
12457330f729Sjoerg                 !SourceMgr.isInMainFile(
12467330f729Sjoerg                    SourceMgr.getExpansionLoc(FD->getLocation())))
12477330f729Sjoerg               Diag(DiagD->getLocation(),
12487330f729Sjoerg                    diag::warn_unneeded_static_internal_decl)
1249*e038c9c4Sjoerg                   << DiagD;
12507330f729Sjoerg             else
12517330f729Sjoerg               Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1252*e038c9c4Sjoerg                   << /*function*/ 0 << DiagD;
12537330f729Sjoerg           }
12547330f729Sjoerg         } else {
12557330f729Sjoerg           if (FD->getDescribedFunctionTemplate())
12567330f729Sjoerg             Diag(DiagD->getLocation(), diag::warn_unused_template)
1257*e038c9c4Sjoerg                 << /*function*/ 0 << DiagD;
12587330f729Sjoerg           else
1259*e038c9c4Sjoerg             Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)
1260*e038c9c4Sjoerg                                            ? diag::warn_unused_member_function
12617330f729Sjoerg                                            : diag::warn_unused_function)
1262*e038c9c4Sjoerg                 << DiagD;
12637330f729Sjoerg         }
12647330f729Sjoerg       } else {
12657330f729Sjoerg         const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
12667330f729Sjoerg         if (!DiagD)
12677330f729Sjoerg           DiagD = cast<VarDecl>(*I);
12687330f729Sjoerg         if (DiagD->isReferenced()) {
12697330f729Sjoerg           Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1270*e038c9c4Sjoerg               << /*variable*/ 1 << DiagD;
12717330f729Sjoerg         } else if (DiagD->getType().isConstQualified()) {
12727330f729Sjoerg           const SourceManager &SM = SourceMgr;
12737330f729Sjoerg           if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
12747330f729Sjoerg               !PP.getLangOpts().IsHeaderFile)
12757330f729Sjoerg             Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1276*e038c9c4Sjoerg                 << DiagD;
12777330f729Sjoerg         } else {
12787330f729Sjoerg           if (DiagD->getDescribedVarTemplate())
12797330f729Sjoerg             Diag(DiagD->getLocation(), diag::warn_unused_template)
1280*e038c9c4Sjoerg                 << /*variable*/ 1 << DiagD;
12817330f729Sjoerg           else
1282*e038c9c4Sjoerg             Diag(DiagD->getLocation(), diag::warn_unused_variable) << DiagD;
12837330f729Sjoerg         }
12847330f729Sjoerg       }
12857330f729Sjoerg     }
12867330f729Sjoerg 
12877330f729Sjoerg     emitAndClearUnusedLocalTypedefWarnings();
12887330f729Sjoerg   }
12897330f729Sjoerg 
12907330f729Sjoerg   if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
12917330f729Sjoerg     // FIXME: Load additional unused private field candidates from the external
12927330f729Sjoerg     // source.
12937330f729Sjoerg     RecordCompleteMap RecordsComplete;
12947330f729Sjoerg     RecordCompleteMap MNCComplete;
12957330f729Sjoerg     for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
12967330f729Sjoerg          E = UnusedPrivateFields.end(); I != E; ++I) {
12977330f729Sjoerg       const NamedDecl *D = *I;
12987330f729Sjoerg       const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
12997330f729Sjoerg       if (RD && !RD->isUnion() &&
13007330f729Sjoerg           IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
13017330f729Sjoerg         Diag(D->getLocation(), diag::warn_unused_private_field)
13027330f729Sjoerg               << D->getDeclName();
13037330f729Sjoerg       }
13047330f729Sjoerg     }
13057330f729Sjoerg   }
13067330f729Sjoerg 
13077330f729Sjoerg   if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
13087330f729Sjoerg     if (ExternalSource)
13097330f729Sjoerg       ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
13107330f729Sjoerg     for (const auto &DeletedFieldInfo : DeleteExprs) {
13117330f729Sjoerg       for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
13127330f729Sjoerg         AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
13137330f729Sjoerg                                   DeleteExprLoc.second);
13147330f729Sjoerg       }
13157330f729Sjoerg     }
13167330f729Sjoerg   }
13177330f729Sjoerg 
13187330f729Sjoerg   // Check we've noticed that we're no longer parsing the initializer for every
13197330f729Sjoerg   // variable. If we miss cases, then at best we have a performance issue and
13207330f729Sjoerg   // at worst a rejects-valid bug.
13217330f729Sjoerg   assert(ParsingInitForAutoVars.empty() &&
13227330f729Sjoerg          "Didn't unmark var as having its initializer parsed");
13237330f729Sjoerg 
13247330f729Sjoerg   if (!PP.isIncrementalProcessingEnabled())
13257330f729Sjoerg     TUScope = nullptr;
13267330f729Sjoerg }
13277330f729Sjoerg 
13287330f729Sjoerg 
13297330f729Sjoerg //===----------------------------------------------------------------------===//
13307330f729Sjoerg // Helper functions.
13317330f729Sjoerg //===----------------------------------------------------------------------===//
13327330f729Sjoerg 
getFunctionLevelDeclContext()13337330f729Sjoerg DeclContext *Sema::getFunctionLevelDeclContext() {
13347330f729Sjoerg   DeclContext *DC = CurContext;
13357330f729Sjoerg 
13367330f729Sjoerg   while (true) {
1337*e038c9c4Sjoerg     if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) ||
1338*e038c9c4Sjoerg         isa<RequiresExprBodyDecl>(DC)) {
13397330f729Sjoerg       DC = DC->getParent();
13407330f729Sjoerg     } else if (isa<CXXMethodDecl>(DC) &&
13417330f729Sjoerg                cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
13427330f729Sjoerg                cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
13437330f729Sjoerg       DC = DC->getParent()->getParent();
13447330f729Sjoerg     }
13457330f729Sjoerg     else break;
13467330f729Sjoerg   }
13477330f729Sjoerg 
13487330f729Sjoerg   return DC;
13497330f729Sjoerg }
13507330f729Sjoerg 
13517330f729Sjoerg /// getCurFunctionDecl - If inside of a function body, this returns a pointer
13527330f729Sjoerg /// to the function decl for the function being parsed.  If we're currently
13537330f729Sjoerg /// in a 'block', this returns the containing context.
getCurFunctionDecl()13547330f729Sjoerg FunctionDecl *Sema::getCurFunctionDecl() {
13557330f729Sjoerg   DeclContext *DC = getFunctionLevelDeclContext();
13567330f729Sjoerg   return dyn_cast<FunctionDecl>(DC);
13577330f729Sjoerg }
13587330f729Sjoerg 
getCurMethodDecl()13597330f729Sjoerg ObjCMethodDecl *Sema::getCurMethodDecl() {
13607330f729Sjoerg   DeclContext *DC = getFunctionLevelDeclContext();
13617330f729Sjoerg   while (isa<RecordDecl>(DC))
13627330f729Sjoerg     DC = DC->getParent();
13637330f729Sjoerg   return dyn_cast<ObjCMethodDecl>(DC);
13647330f729Sjoerg }
13657330f729Sjoerg 
getCurFunctionOrMethodDecl()13667330f729Sjoerg NamedDecl *Sema::getCurFunctionOrMethodDecl() {
13677330f729Sjoerg   DeclContext *DC = getFunctionLevelDeclContext();
13687330f729Sjoerg   if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
13697330f729Sjoerg     return cast<NamedDecl>(DC);
13707330f729Sjoerg   return nullptr;
13717330f729Sjoerg }
13727330f729Sjoerg 
getDefaultCXXMethodAddrSpace() const1373*e038c9c4Sjoerg LangAS Sema::getDefaultCXXMethodAddrSpace() const {
1374*e038c9c4Sjoerg   if (getLangOpts().OpenCL)
1375*e038c9c4Sjoerg     return LangAS::opencl_generic;
1376*e038c9c4Sjoerg   return LangAS::Default;
1377*e038c9c4Sjoerg }
1378*e038c9c4Sjoerg 
EmitCurrentDiagnostic(unsigned DiagID)13797330f729Sjoerg void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
13807330f729Sjoerg   // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
13817330f729Sjoerg   // and yet we also use the current diag ID on the DiagnosticsEngine. This has
13827330f729Sjoerg   // been made more painfully obvious by the refactor that introduced this
13837330f729Sjoerg   // function, but it is possible that the incoming argument can be
13847330f729Sjoerg   // eliminated. If it truly cannot be (for example, there is some reentrancy
13857330f729Sjoerg   // issue I am not seeing yet), then there should at least be a clarifying
13867330f729Sjoerg   // comment somewhere.
13877330f729Sjoerg   if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
13887330f729Sjoerg     switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
13897330f729Sjoerg               Diags.getCurrentDiagID())) {
13907330f729Sjoerg     case DiagnosticIDs::SFINAE_Report:
13917330f729Sjoerg       // We'll report the diagnostic below.
13927330f729Sjoerg       break;
13937330f729Sjoerg 
13947330f729Sjoerg     case DiagnosticIDs::SFINAE_SubstitutionFailure:
13957330f729Sjoerg       // Count this failure so that we know that template argument deduction
13967330f729Sjoerg       // has failed.
13977330f729Sjoerg       ++NumSFINAEErrors;
13987330f729Sjoerg 
13997330f729Sjoerg       // Make a copy of this suppressed diagnostic and store it with the
14007330f729Sjoerg       // template-deduction information.
14017330f729Sjoerg       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
14027330f729Sjoerg         Diagnostic DiagInfo(&Diags);
14037330f729Sjoerg         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
14047330f729Sjoerg                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
14057330f729Sjoerg       }
14067330f729Sjoerg 
14077330f729Sjoerg       Diags.setLastDiagnosticIgnored(true);
14087330f729Sjoerg       Diags.Clear();
14097330f729Sjoerg       return;
14107330f729Sjoerg 
14117330f729Sjoerg     case DiagnosticIDs::SFINAE_AccessControl: {
14127330f729Sjoerg       // Per C++ Core Issue 1170, access control is part of SFINAE.
14137330f729Sjoerg       // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
14147330f729Sjoerg       // make access control a part of SFINAE for the purposes of checking
14157330f729Sjoerg       // type traits.
14167330f729Sjoerg       if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
14177330f729Sjoerg         break;
14187330f729Sjoerg 
14197330f729Sjoerg       SourceLocation Loc = Diags.getCurrentDiagLoc();
14207330f729Sjoerg 
14217330f729Sjoerg       // Suppress this diagnostic.
14227330f729Sjoerg       ++NumSFINAEErrors;
14237330f729Sjoerg 
14247330f729Sjoerg       // Make a copy of this suppressed diagnostic and store it with the
14257330f729Sjoerg       // template-deduction information.
14267330f729Sjoerg       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
14277330f729Sjoerg         Diagnostic DiagInfo(&Diags);
14287330f729Sjoerg         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
14297330f729Sjoerg                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
14307330f729Sjoerg       }
14317330f729Sjoerg 
14327330f729Sjoerg       Diags.setLastDiagnosticIgnored(true);
14337330f729Sjoerg       Diags.Clear();
14347330f729Sjoerg 
14357330f729Sjoerg       // Now the diagnostic state is clear, produce a C++98 compatibility
14367330f729Sjoerg       // warning.
14377330f729Sjoerg       Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
14387330f729Sjoerg 
14397330f729Sjoerg       // The last diagnostic which Sema produced was ignored. Suppress any
14407330f729Sjoerg       // notes attached to it.
14417330f729Sjoerg       Diags.setLastDiagnosticIgnored(true);
14427330f729Sjoerg       return;
14437330f729Sjoerg     }
14447330f729Sjoerg 
14457330f729Sjoerg     case DiagnosticIDs::SFINAE_Suppress:
14467330f729Sjoerg       // Make a copy of this suppressed diagnostic and store it with the
14477330f729Sjoerg       // template-deduction information;
14487330f729Sjoerg       if (*Info) {
14497330f729Sjoerg         Diagnostic DiagInfo(&Diags);
14507330f729Sjoerg         (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
14517330f729Sjoerg                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
14527330f729Sjoerg       }
14537330f729Sjoerg 
14547330f729Sjoerg       // Suppress this diagnostic.
14557330f729Sjoerg       Diags.setLastDiagnosticIgnored(true);
14567330f729Sjoerg       Diags.Clear();
14577330f729Sjoerg       return;
14587330f729Sjoerg     }
14597330f729Sjoerg   }
14607330f729Sjoerg 
14617330f729Sjoerg   // Copy the diagnostic printing policy over the ASTContext printing policy.
14627330f729Sjoerg   // TODO: Stop doing that.  See: https://reviews.llvm.org/D45093#1090292
14637330f729Sjoerg   Context.setPrintingPolicy(getPrintingPolicy());
14647330f729Sjoerg 
14657330f729Sjoerg   // Emit the diagnostic.
14667330f729Sjoerg   if (!Diags.EmitCurrentDiagnostic())
14677330f729Sjoerg     return;
14687330f729Sjoerg 
14697330f729Sjoerg   // If this is not a note, and we're in a template instantiation
14707330f729Sjoerg   // that is different from the last template instantiation where
14717330f729Sjoerg   // we emitted an error, print a template instantiation
14727330f729Sjoerg   // backtrace.
14737330f729Sjoerg   if (!DiagnosticIDs::isBuiltinNote(DiagID))
14747330f729Sjoerg     PrintContextStack();
14757330f729Sjoerg }
14767330f729Sjoerg 
14777330f729Sjoerg Sema::SemaDiagnosticBuilder
Diag(SourceLocation Loc,const PartialDiagnostic & PD,bool DeferHint)1478*e038c9c4Sjoerg Sema::Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint) {
1479*e038c9c4Sjoerg   return Diag(Loc, PD.getDiagID(), DeferHint) << PD;
1480*e038c9c4Sjoerg }
14817330f729Sjoerg 
hasUncompilableErrorOccurred() const1482*e038c9c4Sjoerg bool Sema::hasUncompilableErrorOccurred() const {
1483*e038c9c4Sjoerg   if (getDiagnostics().hasUncompilableErrorOccurred())
1484*e038c9c4Sjoerg     return true;
1485*e038c9c4Sjoerg   auto *FD = dyn_cast<FunctionDecl>(CurContext);
1486*e038c9c4Sjoerg   if (!FD)
1487*e038c9c4Sjoerg     return false;
1488*e038c9c4Sjoerg   auto Loc = DeviceDeferredDiags.find(FD);
1489*e038c9c4Sjoerg   if (Loc == DeviceDeferredDiags.end())
1490*e038c9c4Sjoerg     return false;
1491*e038c9c4Sjoerg   for (auto PDAt : Loc->second) {
1492*e038c9c4Sjoerg     if (DiagnosticIDs::isDefaultMappingAsError(PDAt.second.getDiagID()))
1493*e038c9c4Sjoerg       return true;
1494*e038c9c4Sjoerg   }
1495*e038c9c4Sjoerg   return false;
14967330f729Sjoerg }
14977330f729Sjoerg 
14987330f729Sjoerg // Print notes showing how we can reach FD starting from an a priori
14997330f729Sjoerg // known-callable function.
emitCallStackNotes(Sema & S,FunctionDecl * FD)15007330f729Sjoerg static void emitCallStackNotes(Sema &S, FunctionDecl *FD) {
15017330f729Sjoerg   auto FnIt = S.DeviceKnownEmittedFns.find(FD);
15027330f729Sjoerg   while (FnIt != S.DeviceKnownEmittedFns.end()) {
1503*e038c9c4Sjoerg     // Respect error limit.
1504*e038c9c4Sjoerg     if (S.Diags.hasFatalErrorOccurred())
1505*e038c9c4Sjoerg       return;
15067330f729Sjoerg     DiagnosticBuilder Builder(
15077330f729Sjoerg         S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
15087330f729Sjoerg     Builder << FnIt->second.FD;
15097330f729Sjoerg     FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD);
15107330f729Sjoerg   }
15117330f729Sjoerg }
15127330f729Sjoerg 
1513*e038c9c4Sjoerg namespace {
1514*e038c9c4Sjoerg 
1515*e038c9c4Sjoerg /// Helper class that emits deferred diagnostic messages if an entity directly
1516*e038c9c4Sjoerg /// or indirectly using the function that causes the deferred diagnostic
1517*e038c9c4Sjoerg /// messages is known to be emitted.
1518*e038c9c4Sjoerg ///
1519*e038c9c4Sjoerg /// During parsing of AST, certain diagnostic messages are recorded as deferred
1520*e038c9c4Sjoerg /// diagnostics since it is unknown whether the functions containing such
1521*e038c9c4Sjoerg /// diagnostics will be emitted. A list of potentially emitted functions and
1522*e038c9c4Sjoerg /// variables that may potentially trigger emission of functions are also
1523*e038c9c4Sjoerg /// recorded. DeferredDiagnosticsEmitter recursively visits used functions
1524*e038c9c4Sjoerg /// by each function to emit deferred diagnostics.
1525*e038c9c4Sjoerg ///
1526*e038c9c4Sjoerg /// During the visit, certain OpenMP directives or initializer of variables
1527*e038c9c4Sjoerg /// with certain OpenMP attributes will cause subsequent visiting of any
1528*e038c9c4Sjoerg /// functions enter a state which is called OpenMP device context in this
1529*e038c9c4Sjoerg /// implementation. The state is exited when the directive or initializer is
1530*e038c9c4Sjoerg /// exited. This state can change the emission states of subsequent uses
1531*e038c9c4Sjoerg /// of functions.
1532*e038c9c4Sjoerg ///
1533*e038c9c4Sjoerg /// Conceptually the functions or variables to be visited form a use graph
1534*e038c9c4Sjoerg /// where the parent node uses the child node. At any point of the visit,
1535*e038c9c4Sjoerg /// the tree nodes traversed from the tree root to the current node form a use
1536*e038c9c4Sjoerg /// stack. The emission state of the current node depends on two factors:
1537*e038c9c4Sjoerg ///    1. the emission state of the root node
1538*e038c9c4Sjoerg ///    2. whether the current node is in OpenMP device context
1539*e038c9c4Sjoerg /// If the function is decided to be emitted, its contained deferred diagnostics
1540*e038c9c4Sjoerg /// are emitted, together with the information about the use stack.
1541*e038c9c4Sjoerg ///
1542*e038c9c4Sjoerg class DeferredDiagnosticsEmitter
1543*e038c9c4Sjoerg     : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
1544*e038c9c4Sjoerg public:
1545*e038c9c4Sjoerg   typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited;
1546*e038c9c4Sjoerg 
1547*e038c9c4Sjoerg   // Whether the function is already in the current use-path.
1548*e038c9c4Sjoerg   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath;
1549*e038c9c4Sjoerg 
1550*e038c9c4Sjoerg   // The current use-path.
1551*e038c9c4Sjoerg   llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath;
1552*e038c9c4Sjoerg 
1553*e038c9c4Sjoerg   // Whether the visiting of the function has been done. Done[0] is for the
1554*e038c9c4Sjoerg   // case not in OpenMP device context. Done[1] is for the case in OpenMP
1555*e038c9c4Sjoerg   // device context. We need two sets because diagnostics emission may be
1556*e038c9c4Sjoerg   // different depending on whether it is in OpenMP device context.
1557*e038c9c4Sjoerg   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2];
1558*e038c9c4Sjoerg 
1559*e038c9c4Sjoerg   // Emission state of the root node of the current use graph.
1560*e038c9c4Sjoerg   bool ShouldEmitRootNode;
1561*e038c9c4Sjoerg 
1562*e038c9c4Sjoerg   // Current OpenMP device context level. It is initialized to 0 and each
1563*e038c9c4Sjoerg   // entering of device context increases it by 1 and each exit decreases
1564*e038c9c4Sjoerg   // it by 1. Non-zero value indicates it is currently in device context.
1565*e038c9c4Sjoerg   unsigned InOMPDeviceContext;
1566*e038c9c4Sjoerg 
DeferredDiagnosticsEmitter(Sema & S)1567*e038c9c4Sjoerg   DeferredDiagnosticsEmitter(Sema &S)
1568*e038c9c4Sjoerg       : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
1569*e038c9c4Sjoerg 
shouldVisitDiscardedStmt() const1570*e038c9c4Sjoerg   bool shouldVisitDiscardedStmt() const { return false; }
1571*e038c9c4Sjoerg 
VisitOMPTargetDirective(OMPTargetDirective * Node)1572*e038c9c4Sjoerg   void VisitOMPTargetDirective(OMPTargetDirective *Node) {
1573*e038c9c4Sjoerg     ++InOMPDeviceContext;
1574*e038c9c4Sjoerg     Inherited::VisitOMPTargetDirective(Node);
1575*e038c9c4Sjoerg     --InOMPDeviceContext;
1576*e038c9c4Sjoerg   }
1577*e038c9c4Sjoerg 
visitUsedDecl(SourceLocation Loc,Decl * D)1578*e038c9c4Sjoerg   void visitUsedDecl(SourceLocation Loc, Decl *D) {
1579*e038c9c4Sjoerg     if (isa<VarDecl>(D))
1580*e038c9c4Sjoerg       return;
1581*e038c9c4Sjoerg     if (auto *FD = dyn_cast<FunctionDecl>(D))
1582*e038c9c4Sjoerg       checkFunc(Loc, FD);
1583*e038c9c4Sjoerg     else
1584*e038c9c4Sjoerg       Inherited::visitUsedDecl(Loc, D);
1585*e038c9c4Sjoerg   }
1586*e038c9c4Sjoerg 
checkVar(VarDecl * VD)1587*e038c9c4Sjoerg   void checkVar(VarDecl *VD) {
1588*e038c9c4Sjoerg     assert(VD->isFileVarDecl() &&
1589*e038c9c4Sjoerg            "Should only check file-scope variables");
1590*e038c9c4Sjoerg     if (auto *Init = VD->getInit()) {
1591*e038c9c4Sjoerg       auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
1592*e038c9c4Sjoerg       bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
1593*e038c9c4Sjoerg                              *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
1594*e038c9c4Sjoerg       if (IsDev)
1595*e038c9c4Sjoerg         ++InOMPDeviceContext;
1596*e038c9c4Sjoerg       this->Visit(Init);
1597*e038c9c4Sjoerg       if (IsDev)
1598*e038c9c4Sjoerg         --InOMPDeviceContext;
1599*e038c9c4Sjoerg     }
1600*e038c9c4Sjoerg   }
1601*e038c9c4Sjoerg 
checkFunc(SourceLocation Loc,FunctionDecl * FD)1602*e038c9c4Sjoerg   void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
1603*e038c9c4Sjoerg     auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];
1604*e038c9c4Sjoerg     FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back();
1605*e038c9c4Sjoerg     if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||
1606*e038c9c4Sjoerg         S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD))
1607*e038c9c4Sjoerg       return;
1608*e038c9c4Sjoerg     // Finalize analysis of OpenMP-specific constructs.
1609*e038c9c4Sjoerg     if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 &&
1610*e038c9c4Sjoerg         (ShouldEmitRootNode || InOMPDeviceContext))
1611*e038c9c4Sjoerg       S.finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
1612*e038c9c4Sjoerg     if (Caller)
1613*e038c9c4Sjoerg       S.DeviceKnownEmittedFns[FD] = {Caller, Loc};
1614*e038c9c4Sjoerg     // Always emit deferred diagnostics for the direct users. This does not
1615*e038c9c4Sjoerg     // lead to explosion of diagnostics since each user is visited at most
1616*e038c9c4Sjoerg     // twice.
1617*e038c9c4Sjoerg     if (ShouldEmitRootNode || InOMPDeviceContext)
1618*e038c9c4Sjoerg       emitDeferredDiags(FD, Caller);
1619*e038c9c4Sjoerg     // Do not revisit a function if the function body has been completely
1620*e038c9c4Sjoerg     // visited before.
1621*e038c9c4Sjoerg     if (!Done.insert(FD).second)
1622*e038c9c4Sjoerg       return;
1623*e038c9c4Sjoerg     InUsePath.insert(FD);
1624*e038c9c4Sjoerg     UsePath.push_back(FD);
1625*e038c9c4Sjoerg     if (auto *S = FD->getBody()) {
1626*e038c9c4Sjoerg       this->Visit(S);
1627*e038c9c4Sjoerg     }
1628*e038c9c4Sjoerg     UsePath.pop_back();
1629*e038c9c4Sjoerg     InUsePath.erase(FD);
1630*e038c9c4Sjoerg   }
1631*e038c9c4Sjoerg 
checkRecordedDecl(Decl * D)1632*e038c9c4Sjoerg   void checkRecordedDecl(Decl *D) {
1633*e038c9c4Sjoerg     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1634*e038c9c4Sjoerg       ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
1635*e038c9c4Sjoerg                            Sema::FunctionEmissionStatus::Emitted;
1636*e038c9c4Sjoerg       checkFunc(SourceLocation(), FD);
1637*e038c9c4Sjoerg     } else
1638*e038c9c4Sjoerg       checkVar(cast<VarDecl>(D));
1639*e038c9c4Sjoerg   }
1640*e038c9c4Sjoerg 
1641*e038c9c4Sjoerg   // Emit any deferred diagnostics for FD
emitDeferredDiags(FunctionDecl * FD,bool ShowCallStack)1642*e038c9c4Sjoerg   void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) {
16437330f729Sjoerg     auto It = S.DeviceDeferredDiags.find(FD);
16447330f729Sjoerg     if (It == S.DeviceDeferredDiags.end())
16457330f729Sjoerg       return;
16467330f729Sjoerg     bool HasWarningOrError = false;
1647*e038c9c4Sjoerg     bool FirstDiag = true;
16487330f729Sjoerg     for (PartialDiagnosticAt &PDAt : It->second) {
1649*e038c9c4Sjoerg       // Respect error limit.
1650*e038c9c4Sjoerg       if (S.Diags.hasFatalErrorOccurred())
1651*e038c9c4Sjoerg         return;
16527330f729Sjoerg       const SourceLocation &Loc = PDAt.first;
16537330f729Sjoerg       const PartialDiagnostic &PD = PDAt.second;
1654*e038c9c4Sjoerg       HasWarningOrError |=
1655*e038c9c4Sjoerg           S.getDiagnostics().getDiagnosticLevel(PD.getDiagID(), Loc) >=
1656*e038c9c4Sjoerg           DiagnosticsEngine::Warning;
1657*e038c9c4Sjoerg       {
16587330f729Sjoerg         DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
16597330f729Sjoerg         PD.Emit(Builder);
16607330f729Sjoerg       }
1661*e038c9c4Sjoerg       // Emit the note on the first diagnostic in case too many diagnostics
1662*e038c9c4Sjoerg       // cause the note not emitted.
1663*e038c9c4Sjoerg       if (FirstDiag && HasWarningOrError && ShowCallStack) {
16647330f729Sjoerg         emitCallStackNotes(S, FD);
1665*e038c9c4Sjoerg         FirstDiag = false;
1666*e038c9c4Sjoerg       }
1667*e038c9c4Sjoerg     }
1668*e038c9c4Sjoerg   }
1669*e038c9c4Sjoerg };
1670*e038c9c4Sjoerg } // namespace
1671*e038c9c4Sjoerg 
emitDeferredDiags()1672*e038c9c4Sjoerg void Sema::emitDeferredDiags() {
1673*e038c9c4Sjoerg   if (ExternalSource)
1674*e038c9c4Sjoerg     ExternalSource->ReadDeclsToCheckForDeferredDiags(
1675*e038c9c4Sjoerg         DeclsToCheckForDeferredDiags);
1676*e038c9c4Sjoerg 
1677*e038c9c4Sjoerg   if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||
1678*e038c9c4Sjoerg       DeclsToCheckForDeferredDiags.empty())
1679*e038c9c4Sjoerg     return;
1680*e038c9c4Sjoerg 
1681*e038c9c4Sjoerg   DeferredDiagnosticsEmitter DDE(*this);
1682*e038c9c4Sjoerg   for (auto D : DeclsToCheckForDeferredDiags)
1683*e038c9c4Sjoerg     DDE.checkRecordedDecl(D);
16847330f729Sjoerg }
16857330f729Sjoerg 
16867330f729Sjoerg // In CUDA, there are some constructs which may appear in semantically-valid
16877330f729Sjoerg // code, but trigger errors if we ever generate code for the function in which
16887330f729Sjoerg // they appear.  Essentially every construct you're not allowed to use on the
16897330f729Sjoerg // device falls into this category, because you are allowed to use these
16907330f729Sjoerg // constructs in a __host__ __device__ function, but only if that function is
16917330f729Sjoerg // never codegen'ed on the device.
16927330f729Sjoerg //
16937330f729Sjoerg // To handle semantic checking for these constructs, we keep track of the set of
16947330f729Sjoerg // functions we know will be emitted, either because we could tell a priori that
16957330f729Sjoerg // they would be emitted, or because they were transitively called by a
16967330f729Sjoerg // known-emitted function.
16977330f729Sjoerg //
16987330f729Sjoerg // We also keep a partial call graph of which not-known-emitted functions call
16997330f729Sjoerg // which other not-known-emitted functions.
17007330f729Sjoerg //
17017330f729Sjoerg // When we see something which is illegal if the current function is emitted
17027330f729Sjoerg // (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
17037330f729Sjoerg // CheckCUDACall), we first check if the current function is known-emitted.  If
17047330f729Sjoerg // so, we immediately output the diagnostic.
17057330f729Sjoerg //
17067330f729Sjoerg // Otherwise, we "defer" the diagnostic.  It sits in Sema::DeviceDeferredDiags
17077330f729Sjoerg // until we discover that the function is known-emitted, at which point we take
17087330f729Sjoerg // it out of this map and emit the diagnostic.
17097330f729Sjoerg 
SemaDiagnosticBuilder(Kind K,SourceLocation Loc,unsigned DiagID,FunctionDecl * Fn,Sema & S)1710*e038c9c4Sjoerg Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc,
1711*e038c9c4Sjoerg                                                    unsigned DiagID,
1712*e038c9c4Sjoerg                                                    FunctionDecl *Fn, Sema &S)
17137330f729Sjoerg     : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
17147330f729Sjoerg       ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
17157330f729Sjoerg   switch (K) {
17167330f729Sjoerg   case K_Nop:
17177330f729Sjoerg     break;
17187330f729Sjoerg   case K_Immediate:
17197330f729Sjoerg   case K_ImmediateWithCallStack:
1720*e038c9c4Sjoerg     ImmediateDiag.emplace(
1721*e038c9c4Sjoerg         ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));
17227330f729Sjoerg     break;
17237330f729Sjoerg   case K_Deferred:
17247330f729Sjoerg     assert(Fn && "Must have a function to attach the deferred diag to.");
17257330f729Sjoerg     auto &Diags = S.DeviceDeferredDiags[Fn];
17267330f729Sjoerg     PartialDiagId.emplace(Diags.size());
17277330f729Sjoerg     Diags.emplace_back(Loc, S.PDiag(DiagID));
17287330f729Sjoerg     break;
17297330f729Sjoerg   }
17307330f729Sjoerg }
17317330f729Sjoerg 
SemaDiagnosticBuilder(SemaDiagnosticBuilder && D)1732*e038c9c4Sjoerg Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D)
17337330f729Sjoerg     : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
17347330f729Sjoerg       ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
17357330f729Sjoerg       PartialDiagId(D.PartialDiagId) {
17367330f729Sjoerg   // Clean the previous diagnostics.
17377330f729Sjoerg   D.ShowCallStack = false;
17387330f729Sjoerg   D.ImmediateDiag.reset();
17397330f729Sjoerg   D.PartialDiagId.reset();
17407330f729Sjoerg }
17417330f729Sjoerg 
~SemaDiagnosticBuilder()1742*e038c9c4Sjoerg Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
17437330f729Sjoerg   if (ImmediateDiag) {
17447330f729Sjoerg     // Emit our diagnostic and, if it was a warning or error, output a callstack
17457330f729Sjoerg     // if Fn isn't a priori known-emitted.
17467330f729Sjoerg     bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
17477330f729Sjoerg                                 DiagID, Loc) >= DiagnosticsEngine::Warning;
17487330f729Sjoerg     ImmediateDiag.reset(); // Emit the immediate diag.
17497330f729Sjoerg     if (IsWarningOrError && ShowCallStack)
17507330f729Sjoerg       emitCallStackNotes(S, Fn);
17517330f729Sjoerg   } else {
17527330f729Sjoerg     assert((!PartialDiagId || ShowCallStack) &&
17537330f729Sjoerg            "Must always show call stack for deferred diags.");
17547330f729Sjoerg   }
17557330f729Sjoerg }
17567330f729Sjoerg 
1757*e038c9c4Sjoerg Sema::SemaDiagnosticBuilder
targetDiag(SourceLocation Loc,unsigned DiagID,FunctionDecl * FD)1758*e038c9c4Sjoerg Sema::targetDiag(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD) {
1759*e038c9c4Sjoerg   FD = FD ? FD : getCurFunctionDecl();
17607330f729Sjoerg   if (LangOpts.OpenMP)
1761*e038c9c4Sjoerg     return LangOpts.OpenMPIsDevice ? diagIfOpenMPDeviceCode(Loc, DiagID, FD)
1762*e038c9c4Sjoerg                                    : diagIfOpenMPHostCode(Loc, DiagID, FD);
17637330f729Sjoerg   if (getLangOpts().CUDA)
17647330f729Sjoerg     return getLangOpts().CUDAIsDevice ? CUDADiagIfDeviceCode(Loc, DiagID)
17657330f729Sjoerg                                       : CUDADiagIfHostCode(Loc, DiagID);
1766*e038c9c4Sjoerg 
1767*e038c9c4Sjoerg   if (getLangOpts().SYCLIsDevice)
1768*e038c9c4Sjoerg     return SYCLDiagIfDeviceCode(Loc, DiagID);
1769*e038c9c4Sjoerg 
1770*e038c9c4Sjoerg   return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, DiagID,
1771*e038c9c4Sjoerg                                FD, *this);
1772*e038c9c4Sjoerg }
1773*e038c9c4Sjoerg 
Diag(SourceLocation Loc,unsigned DiagID,bool DeferHint)1774*e038c9c4Sjoerg Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID,
1775*e038c9c4Sjoerg                                        bool DeferHint) {
1776*e038c9c4Sjoerg   bool IsError = Diags.getDiagnosticIDs()->isDefaultMappingAsError(DiagID);
1777*e038c9c4Sjoerg   bool ShouldDefer = getLangOpts().CUDA && LangOpts.GPUDeferDiag &&
1778*e038c9c4Sjoerg                      DiagnosticIDs::isDeferrable(DiagID) &&
1779*e038c9c4Sjoerg                      (DeferHint || !IsError);
1780*e038c9c4Sjoerg   auto SetIsLastErrorImmediate = [&](bool Flag) {
1781*e038c9c4Sjoerg     if (IsError)
1782*e038c9c4Sjoerg       IsLastErrorImmediate = Flag;
1783*e038c9c4Sjoerg   };
1784*e038c9c4Sjoerg   if (!ShouldDefer) {
1785*e038c9c4Sjoerg     SetIsLastErrorImmediate(true);
1786*e038c9c4Sjoerg     return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc,
1787*e038c9c4Sjoerg                                  DiagID, getCurFunctionDecl(), *this);
1788*e038c9c4Sjoerg   }
1789*e038c9c4Sjoerg 
1790*e038c9c4Sjoerg   SemaDiagnosticBuilder DB = getLangOpts().CUDAIsDevice
1791*e038c9c4Sjoerg                                  ? CUDADiagIfDeviceCode(Loc, DiagID)
1792*e038c9c4Sjoerg                                  : CUDADiagIfHostCode(Loc, DiagID);
1793*e038c9c4Sjoerg   SetIsLastErrorImmediate(DB.isImmediate());
1794*e038c9c4Sjoerg   return DB;
1795*e038c9c4Sjoerg }
1796*e038c9c4Sjoerg 
checkDeviceDecl(ValueDecl * D,SourceLocation Loc)1797*e038c9c4Sjoerg void Sema::checkDeviceDecl(ValueDecl *D, SourceLocation Loc) {
1798*e038c9c4Sjoerg   if (isUnevaluatedContext())
1799*e038c9c4Sjoerg     return;
1800*e038c9c4Sjoerg 
1801*e038c9c4Sjoerg   Decl *C = cast<Decl>(getCurLexicalContext());
1802*e038c9c4Sjoerg 
1803*e038c9c4Sjoerg   // Memcpy operations for structs containing a member with unsupported type
1804*e038c9c4Sjoerg   // are ok, though.
1805*e038c9c4Sjoerg   if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
1806*e038c9c4Sjoerg     if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
1807*e038c9c4Sjoerg         MD->isTrivial())
1808*e038c9c4Sjoerg       return;
1809*e038c9c4Sjoerg 
1810*e038c9c4Sjoerg     if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
1811*e038c9c4Sjoerg       if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())
1812*e038c9c4Sjoerg         return;
1813*e038c9c4Sjoerg   }
1814*e038c9c4Sjoerg 
1815*e038c9c4Sjoerg   // Try to associate errors with the lexical context, if that is a function, or
1816*e038c9c4Sjoerg   // the value declaration otherwise.
1817*e038c9c4Sjoerg   FunctionDecl *FD =
1818*e038c9c4Sjoerg       isa<FunctionDecl>(C) ? cast<FunctionDecl>(C) : dyn_cast<FunctionDecl>(D);
1819*e038c9c4Sjoerg   auto CheckType = [&](QualType Ty) {
1820*e038c9c4Sjoerg     if (Ty->isDependentType())
1821*e038c9c4Sjoerg       return;
1822*e038c9c4Sjoerg 
1823*e038c9c4Sjoerg     if (Ty->isExtIntType()) {
1824*e038c9c4Sjoerg       if (!Context.getTargetInfo().hasExtIntType()) {
1825*e038c9c4Sjoerg         targetDiag(Loc, diag::err_device_unsupported_type, FD)
1826*e038c9c4Sjoerg             << D << false /*show bit size*/ << 0 /*bitsize*/
1827*e038c9c4Sjoerg             << Ty << Context.getTargetInfo().getTriple().str();
1828*e038c9c4Sjoerg       }
1829*e038c9c4Sjoerg       return;
1830*e038c9c4Sjoerg     }
1831*e038c9c4Sjoerg 
1832*e038c9c4Sjoerg     if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1833*e038c9c4Sjoerg         ((Ty->isFloat128Type() ||
1834*e038c9c4Sjoerg           (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1835*e038c9c4Sjoerg          !Context.getTargetInfo().hasFloat128Type()) ||
1836*e038c9c4Sjoerg         (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1837*e038c9c4Sjoerg          !Context.getTargetInfo().hasInt128Type())) {
1838*e038c9c4Sjoerg       if (targetDiag(Loc, diag::err_device_unsupported_type, FD)
1839*e038c9c4Sjoerg           << D << true /*show bit size*/
1840*e038c9c4Sjoerg           << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1841*e038c9c4Sjoerg           << Context.getTargetInfo().getTriple().str())
1842*e038c9c4Sjoerg         D->setInvalidDecl();
1843*e038c9c4Sjoerg       targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
1844*e038c9c4Sjoerg     }
1845*e038c9c4Sjoerg   };
1846*e038c9c4Sjoerg 
1847*e038c9c4Sjoerg   QualType Ty = D->getType();
1848*e038c9c4Sjoerg   CheckType(Ty);
1849*e038c9c4Sjoerg 
1850*e038c9c4Sjoerg   if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
1851*e038c9c4Sjoerg     for (const auto &ParamTy : FPTy->param_types())
1852*e038c9c4Sjoerg       CheckType(ParamTy);
1853*e038c9c4Sjoerg     CheckType(FPTy->getReturnType());
1854*e038c9c4Sjoerg   }
1855*e038c9c4Sjoerg   if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty))
1856*e038c9c4Sjoerg     CheckType(FNPTy->getReturnType());
18577330f729Sjoerg }
18587330f729Sjoerg 
18597330f729Sjoerg /// Looks through the macro-expansion chain for the given
18607330f729Sjoerg /// location, looking for a macro expansion with the given name.
18617330f729Sjoerg /// If one is found, returns true and sets the location to that
18627330f729Sjoerg /// expansion loc.
findMacroSpelling(SourceLocation & locref,StringRef name)18637330f729Sjoerg bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
18647330f729Sjoerg   SourceLocation loc = locref;
18657330f729Sjoerg   if (!loc.isMacroID()) return false;
18667330f729Sjoerg 
18677330f729Sjoerg   // There's no good way right now to look at the intermediate
18687330f729Sjoerg   // expansions, so just jump to the expansion location.
18697330f729Sjoerg   loc = getSourceManager().getExpansionLoc(loc);
18707330f729Sjoerg 
18717330f729Sjoerg   // If that's written with the name, stop here.
1872*e038c9c4Sjoerg   SmallString<16> buffer;
18737330f729Sjoerg   if (getPreprocessor().getSpelling(loc, buffer) == name) {
18747330f729Sjoerg     locref = loc;
18757330f729Sjoerg     return true;
18767330f729Sjoerg   }
18777330f729Sjoerg   return false;
18787330f729Sjoerg }
18797330f729Sjoerg 
18807330f729Sjoerg /// Determines the active Scope associated with the given declaration
18817330f729Sjoerg /// context.
18827330f729Sjoerg ///
18837330f729Sjoerg /// This routine maps a declaration context to the active Scope object that
18847330f729Sjoerg /// represents that declaration context in the parser. It is typically used
18857330f729Sjoerg /// from "scope-less" code (e.g., template instantiation, lazy creation of
18867330f729Sjoerg /// declarations) that injects a name for name-lookup purposes and, therefore,
18877330f729Sjoerg /// must update the Scope.
18887330f729Sjoerg ///
18897330f729Sjoerg /// \returns The scope corresponding to the given declaraion context, or NULL
18907330f729Sjoerg /// if no such scope is open.
getScopeForContext(DeclContext * Ctx)18917330f729Sjoerg Scope *Sema::getScopeForContext(DeclContext *Ctx) {
18927330f729Sjoerg 
18937330f729Sjoerg   if (!Ctx)
18947330f729Sjoerg     return nullptr;
18957330f729Sjoerg 
18967330f729Sjoerg   Ctx = Ctx->getPrimaryContext();
18977330f729Sjoerg   for (Scope *S = getCurScope(); S; S = S->getParent()) {
18987330f729Sjoerg     // Ignore scopes that cannot have declarations. This is important for
18997330f729Sjoerg     // out-of-line definitions of static class members.
19007330f729Sjoerg     if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
19017330f729Sjoerg       if (DeclContext *Entity = S->getEntity())
19027330f729Sjoerg         if (Ctx == Entity->getPrimaryContext())
19037330f729Sjoerg           return S;
19047330f729Sjoerg   }
19057330f729Sjoerg 
19067330f729Sjoerg   return nullptr;
19077330f729Sjoerg }
19087330f729Sjoerg 
19097330f729Sjoerg /// Enter a new function scope
PushFunctionScope()19107330f729Sjoerg void Sema::PushFunctionScope() {
19117330f729Sjoerg   if (FunctionScopes.empty() && CachedFunctionScope) {
19127330f729Sjoerg     // Use CachedFunctionScope to avoid allocating memory when possible.
19137330f729Sjoerg     CachedFunctionScope->Clear();
19147330f729Sjoerg     FunctionScopes.push_back(CachedFunctionScope.release());
19157330f729Sjoerg   } else {
19167330f729Sjoerg     FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
19177330f729Sjoerg   }
19187330f729Sjoerg   if (LangOpts.OpenMP)
19197330f729Sjoerg     pushOpenMPFunctionRegion();
19207330f729Sjoerg }
19217330f729Sjoerg 
PushBlockScope(Scope * BlockScope,BlockDecl * Block)19227330f729Sjoerg void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
19237330f729Sjoerg   FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
19247330f729Sjoerg                                               BlockScope, Block));
19257330f729Sjoerg }
19267330f729Sjoerg 
PushLambdaScope()19277330f729Sjoerg LambdaScopeInfo *Sema::PushLambdaScope() {
19287330f729Sjoerg   LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
19297330f729Sjoerg   FunctionScopes.push_back(LSI);
19307330f729Sjoerg   return LSI;
19317330f729Sjoerg }
19327330f729Sjoerg 
RecordParsingTemplateParameterDepth(unsigned Depth)19337330f729Sjoerg void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
19347330f729Sjoerg   if (LambdaScopeInfo *const LSI = getCurLambda()) {
19357330f729Sjoerg     LSI->AutoTemplateParameterDepth = Depth;
19367330f729Sjoerg     return;
19377330f729Sjoerg   }
19387330f729Sjoerg   llvm_unreachable(
19397330f729Sjoerg       "Remove assertion if intentionally called in a non-lambda context.");
19407330f729Sjoerg }
19417330f729Sjoerg 
19427330f729Sjoerg // Check that the type of the VarDecl has an accessible copy constructor and
19437330f729Sjoerg // resolve its destructor's exception specification.
checkEscapingByref(VarDecl * VD,Sema & S)19447330f729Sjoerg static void checkEscapingByref(VarDecl *VD, Sema &S) {
19457330f729Sjoerg   QualType T = VD->getType();
19467330f729Sjoerg   EnterExpressionEvaluationContext scope(
19477330f729Sjoerg       S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
19487330f729Sjoerg   SourceLocation Loc = VD->getLocation();
19497330f729Sjoerg   Expr *VarRef =
19507330f729Sjoerg       new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
19517330f729Sjoerg   ExprResult Result = S.PerformMoveOrCopyInitialization(
19527330f729Sjoerg       InitializedEntity::InitializeBlock(Loc, T, false), VD, VD->getType(),
19537330f729Sjoerg       VarRef, /*AllowNRVO=*/true);
19547330f729Sjoerg   if (!Result.isInvalid()) {
19557330f729Sjoerg     Result = S.MaybeCreateExprWithCleanups(Result);
19567330f729Sjoerg     Expr *Init = Result.getAs<Expr>();
19577330f729Sjoerg     S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));
19587330f729Sjoerg   }
19597330f729Sjoerg 
19607330f729Sjoerg   // The destructor's exception specification is needed when IRGen generates
19617330f729Sjoerg   // block copy/destroy functions. Resolve it here.
19627330f729Sjoerg   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
19637330f729Sjoerg     if (CXXDestructorDecl *DD = RD->getDestructor()) {
19647330f729Sjoerg       auto *FPT = DD->getType()->getAs<FunctionProtoType>();
19657330f729Sjoerg       S.ResolveExceptionSpec(Loc, FPT);
19667330f729Sjoerg     }
19677330f729Sjoerg }
19687330f729Sjoerg 
markEscapingByrefs(const FunctionScopeInfo & FSI,Sema & S)19697330f729Sjoerg static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
19707330f729Sjoerg   // Set the EscapingByref flag of __block variables captured by
19717330f729Sjoerg   // escaping blocks.
19727330f729Sjoerg   for (const BlockDecl *BD : FSI.Blocks) {
19737330f729Sjoerg     for (const BlockDecl::Capture &BC : BD->captures()) {
19747330f729Sjoerg       VarDecl *VD = BC.getVariable();
19757330f729Sjoerg       if (VD->hasAttr<BlocksAttr>()) {
19767330f729Sjoerg         // Nothing to do if this is a __block variable captured by a
19777330f729Sjoerg         // non-escaping block.
19787330f729Sjoerg         if (BD->doesNotEscape())
19797330f729Sjoerg           continue;
19807330f729Sjoerg         VD->setEscapingByref();
19817330f729Sjoerg       }
19827330f729Sjoerg       // Check whether the captured variable is or contains an object of
19837330f729Sjoerg       // non-trivial C union type.
19847330f729Sjoerg       QualType CapType = BC.getVariable()->getType();
19857330f729Sjoerg       if (CapType.hasNonTrivialToPrimitiveDestructCUnion() ||
19867330f729Sjoerg           CapType.hasNonTrivialToPrimitiveCopyCUnion())
19877330f729Sjoerg         S.checkNonTrivialCUnion(BC.getVariable()->getType(),
19887330f729Sjoerg                                 BD->getCaretLocation(),
19897330f729Sjoerg                                 Sema::NTCUC_BlockCapture,
19907330f729Sjoerg                                 Sema::NTCUK_Destruct|Sema::NTCUK_Copy);
19917330f729Sjoerg     }
19927330f729Sjoerg   }
19937330f729Sjoerg 
19947330f729Sjoerg   for (VarDecl *VD : FSI.ByrefBlockVars) {
19957330f729Sjoerg     // __block variables might require us to capture a copy-initializer.
19967330f729Sjoerg     if (!VD->isEscapingByref())
19977330f729Sjoerg       continue;
19987330f729Sjoerg     // It's currently invalid to ever have a __block variable with an
19997330f729Sjoerg     // array type; should we diagnose that here?
20007330f729Sjoerg     // Regardless, we don't want to ignore array nesting when
20017330f729Sjoerg     // constructing this copy.
20027330f729Sjoerg     if (VD->getType()->isStructureOrClassType())
20037330f729Sjoerg       checkEscapingByref(VD, S);
20047330f729Sjoerg   }
20057330f729Sjoerg }
20067330f729Sjoerg 
20077330f729Sjoerg /// Pop a function (or block or lambda or captured region) scope from the stack.
20087330f729Sjoerg ///
20097330f729Sjoerg /// \param WP The warning policy to use for CFG-based warnings, or null if such
20107330f729Sjoerg ///        warnings should not be produced.
20117330f729Sjoerg /// \param D The declaration corresponding to this function scope, if producing
20127330f729Sjoerg ///        CFG-based warnings.
20137330f729Sjoerg /// \param BlockType The type of the block expression, if D is a BlockDecl.
20147330f729Sjoerg Sema::PoppedFunctionScopePtr
PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy * WP,const Decl * D,QualType BlockType)20157330f729Sjoerg Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
20167330f729Sjoerg                            const Decl *D, QualType BlockType) {
20177330f729Sjoerg   assert(!FunctionScopes.empty() && "mismatched push/pop!");
20187330f729Sjoerg 
20197330f729Sjoerg   markEscapingByrefs(*FunctionScopes.back(), *this);
20207330f729Sjoerg 
20217330f729Sjoerg   PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
20227330f729Sjoerg                                PoppedFunctionScopeDeleter(this));
20237330f729Sjoerg 
20247330f729Sjoerg   if (LangOpts.OpenMP)
20257330f729Sjoerg     popOpenMPFunctionRegion(Scope.get());
20267330f729Sjoerg 
20277330f729Sjoerg   // Issue any analysis-based warnings.
20287330f729Sjoerg   if (WP && D)
20297330f729Sjoerg     AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
20307330f729Sjoerg   else
20317330f729Sjoerg     for (const auto &PUD : Scope->PossiblyUnreachableDiags)
20327330f729Sjoerg       Diag(PUD.Loc, PUD.PD);
20337330f729Sjoerg 
20347330f729Sjoerg   return Scope;
20357330f729Sjoerg }
20367330f729Sjoerg 
20377330f729Sjoerg void Sema::PoppedFunctionScopeDeleter::
operator ()(sema::FunctionScopeInfo * Scope) const20387330f729Sjoerg operator()(sema::FunctionScopeInfo *Scope) const {
20397330f729Sjoerg   // Stash the function scope for later reuse if it's for a normal function.
20407330f729Sjoerg   if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
20417330f729Sjoerg     Self->CachedFunctionScope.reset(Scope);
20427330f729Sjoerg   else
20437330f729Sjoerg     delete Scope;
20447330f729Sjoerg }
20457330f729Sjoerg 
PushCompoundScope(bool IsStmtExpr)20467330f729Sjoerg void Sema::PushCompoundScope(bool IsStmtExpr) {
20477330f729Sjoerg   getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo(IsStmtExpr));
20487330f729Sjoerg }
20497330f729Sjoerg 
PopCompoundScope()20507330f729Sjoerg void Sema::PopCompoundScope() {
20517330f729Sjoerg   FunctionScopeInfo *CurFunction = getCurFunction();
20527330f729Sjoerg   assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
20537330f729Sjoerg 
20547330f729Sjoerg   CurFunction->CompoundScopes.pop_back();
20557330f729Sjoerg }
20567330f729Sjoerg 
20577330f729Sjoerg /// Determine whether any errors occurred within this function/method/
20587330f729Sjoerg /// block.
hasAnyUnrecoverableErrorsInThisFunction() const20597330f729Sjoerg bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
2060*e038c9c4Sjoerg   return getCurFunction()->hasUnrecoverableErrorOccurred();
20617330f729Sjoerg }
20627330f729Sjoerg 
setFunctionHasBranchIntoScope()20637330f729Sjoerg void Sema::setFunctionHasBranchIntoScope() {
20647330f729Sjoerg   if (!FunctionScopes.empty())
20657330f729Sjoerg     FunctionScopes.back()->setHasBranchIntoScope();
20667330f729Sjoerg }
20677330f729Sjoerg 
setFunctionHasBranchProtectedScope()20687330f729Sjoerg void Sema::setFunctionHasBranchProtectedScope() {
20697330f729Sjoerg   if (!FunctionScopes.empty())
20707330f729Sjoerg     FunctionScopes.back()->setHasBranchProtectedScope();
20717330f729Sjoerg }
20727330f729Sjoerg 
setFunctionHasIndirectGoto()20737330f729Sjoerg void Sema::setFunctionHasIndirectGoto() {
20747330f729Sjoerg   if (!FunctionScopes.empty())
20757330f729Sjoerg     FunctionScopes.back()->setHasIndirectGoto();
20767330f729Sjoerg }
20777330f729Sjoerg 
setFunctionHasMustTail()2078*e038c9c4Sjoerg void Sema::setFunctionHasMustTail() {
2079*e038c9c4Sjoerg   if (!FunctionScopes.empty())
2080*e038c9c4Sjoerg     FunctionScopes.back()->setHasMustTail();
2081*e038c9c4Sjoerg }
2082*e038c9c4Sjoerg 
getCurBlock()20837330f729Sjoerg BlockScopeInfo *Sema::getCurBlock() {
20847330f729Sjoerg   if (FunctionScopes.empty())
20857330f729Sjoerg     return nullptr;
20867330f729Sjoerg 
20877330f729Sjoerg   auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
20887330f729Sjoerg   if (CurBSI && CurBSI->TheDecl &&
20897330f729Sjoerg       !CurBSI->TheDecl->Encloses(CurContext)) {
20907330f729Sjoerg     // We have switched contexts due to template instantiation.
20917330f729Sjoerg     assert(!CodeSynthesisContexts.empty());
20927330f729Sjoerg     return nullptr;
20937330f729Sjoerg   }
20947330f729Sjoerg 
20957330f729Sjoerg   return CurBSI;
20967330f729Sjoerg }
20977330f729Sjoerg 
getEnclosingFunction() const20987330f729Sjoerg FunctionScopeInfo *Sema::getEnclosingFunction() const {
20997330f729Sjoerg   if (FunctionScopes.empty())
21007330f729Sjoerg     return nullptr;
21017330f729Sjoerg 
21027330f729Sjoerg   for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
21037330f729Sjoerg     if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
21047330f729Sjoerg       continue;
21057330f729Sjoerg     return FunctionScopes[e];
21067330f729Sjoerg   }
21077330f729Sjoerg   return nullptr;
21087330f729Sjoerg }
21097330f729Sjoerg 
getEnclosingLambda() const21107330f729Sjoerg LambdaScopeInfo *Sema::getEnclosingLambda() const {
21117330f729Sjoerg   for (auto *Scope : llvm::reverse(FunctionScopes)) {
21127330f729Sjoerg     if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) {
21137330f729Sjoerg       if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext)) {
21147330f729Sjoerg         // We have switched contexts due to template instantiation.
21157330f729Sjoerg         // FIXME: We should swap out the FunctionScopes during code synthesis
21167330f729Sjoerg         // so that we don't need to check for this.
21177330f729Sjoerg         assert(!CodeSynthesisContexts.empty());
21187330f729Sjoerg         return nullptr;
21197330f729Sjoerg       }
21207330f729Sjoerg       return LSI;
21217330f729Sjoerg     }
21227330f729Sjoerg   }
21237330f729Sjoerg   return nullptr;
21247330f729Sjoerg }
21257330f729Sjoerg 
getCurLambda(bool IgnoreNonLambdaCapturingScope)21267330f729Sjoerg LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
21277330f729Sjoerg   if (FunctionScopes.empty())
21287330f729Sjoerg     return nullptr;
21297330f729Sjoerg 
21307330f729Sjoerg   auto I = FunctionScopes.rbegin();
21317330f729Sjoerg   if (IgnoreNonLambdaCapturingScope) {
21327330f729Sjoerg     auto E = FunctionScopes.rend();
21337330f729Sjoerg     while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
21347330f729Sjoerg       ++I;
21357330f729Sjoerg     if (I == E)
21367330f729Sjoerg       return nullptr;
21377330f729Sjoerg   }
21387330f729Sjoerg   auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
21397330f729Sjoerg   if (CurLSI && CurLSI->Lambda &&
21407330f729Sjoerg       !CurLSI->Lambda->Encloses(CurContext)) {
21417330f729Sjoerg     // We have switched contexts due to template instantiation.
21427330f729Sjoerg     assert(!CodeSynthesisContexts.empty());
21437330f729Sjoerg     return nullptr;
21447330f729Sjoerg   }
21457330f729Sjoerg 
21467330f729Sjoerg   return CurLSI;
21477330f729Sjoerg }
21487330f729Sjoerg 
21497330f729Sjoerg // We have a generic lambda if we parsed auto parameters, or we have
21507330f729Sjoerg // an associated template parameter list.
getCurGenericLambda()21517330f729Sjoerg LambdaScopeInfo *Sema::getCurGenericLambda() {
21527330f729Sjoerg   if (LambdaScopeInfo *LSI =  getCurLambda()) {
21537330f729Sjoerg     return (LSI->TemplateParams.size() ||
21547330f729Sjoerg                     LSI->GLTemplateParameterList) ? LSI : nullptr;
21557330f729Sjoerg   }
21567330f729Sjoerg   return nullptr;
21577330f729Sjoerg }
21587330f729Sjoerg 
21597330f729Sjoerg 
ActOnComment(SourceRange Comment)21607330f729Sjoerg void Sema::ActOnComment(SourceRange Comment) {
21617330f729Sjoerg   if (!LangOpts.RetainCommentsFromSystemHeaders &&
21627330f729Sjoerg       SourceMgr.isInSystemHeader(Comment.getBegin()))
21637330f729Sjoerg     return;
21647330f729Sjoerg   RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
21657330f729Sjoerg   if (RC.isAlmostTrailingComment()) {
21667330f729Sjoerg     SourceRange MagicMarkerRange(Comment.getBegin(),
21677330f729Sjoerg                                  Comment.getBegin().getLocWithOffset(3));
21687330f729Sjoerg     StringRef MagicMarkerText;
21697330f729Sjoerg     switch (RC.getKind()) {
21707330f729Sjoerg     case RawComment::RCK_OrdinaryBCPL:
21717330f729Sjoerg       MagicMarkerText = "///<";
21727330f729Sjoerg       break;
21737330f729Sjoerg     case RawComment::RCK_OrdinaryC:
21747330f729Sjoerg       MagicMarkerText = "/**<";
21757330f729Sjoerg       break;
21767330f729Sjoerg     default:
21777330f729Sjoerg       llvm_unreachable("if this is an almost Doxygen comment, "
21787330f729Sjoerg                        "it should be ordinary");
21797330f729Sjoerg     }
21807330f729Sjoerg     Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
21817330f729Sjoerg       FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
21827330f729Sjoerg   }
21837330f729Sjoerg   Context.addComment(RC);
21847330f729Sjoerg }
21857330f729Sjoerg 
21867330f729Sjoerg // Pin this vtable to this file.
~ExternalSemaSource()21877330f729Sjoerg ExternalSemaSource::~ExternalSemaSource() {}
2188*e038c9c4Sjoerg char ExternalSemaSource::ID;
21897330f729Sjoerg 
ReadMethodPool(Selector Sel)21907330f729Sjoerg void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
updateOutOfDateSelector(Selector Sel)21917330f729Sjoerg void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
21927330f729Sjoerg 
ReadKnownNamespaces(SmallVectorImpl<NamespaceDecl * > & Namespaces)21937330f729Sjoerg void ExternalSemaSource::ReadKnownNamespaces(
21947330f729Sjoerg                            SmallVectorImpl<NamespaceDecl *> &Namespaces) {
21957330f729Sjoerg }
21967330f729Sjoerg 
ReadUndefinedButUsed(llvm::MapVector<NamedDecl *,SourceLocation> & Undefined)21977330f729Sjoerg void ExternalSemaSource::ReadUndefinedButUsed(
21987330f729Sjoerg     llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
21997330f729Sjoerg 
ReadMismatchingDeleteExpressions(llvm::MapVector<FieldDecl *,llvm::SmallVector<std::pair<SourceLocation,bool>,4>> &)22007330f729Sjoerg void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
22017330f729Sjoerg     FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
22027330f729Sjoerg 
22037330f729Sjoerg /// Figure out if an expression could be turned into a call.
22047330f729Sjoerg ///
22057330f729Sjoerg /// Use this when trying to recover from an error where the programmer may have
22067330f729Sjoerg /// written just the name of a function instead of actually calling it.
22077330f729Sjoerg ///
22087330f729Sjoerg /// \param E - The expression to examine.
22097330f729Sjoerg /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
22107330f729Sjoerg ///  with no arguments, this parameter is set to the type returned by such a
22117330f729Sjoerg ///  call; otherwise, it is set to an empty QualType.
22127330f729Sjoerg /// \param OverloadSet - If the expression is an overloaded function
22137330f729Sjoerg ///  name, this parameter is populated with the decls of the various overloads.
tryExprAsCall(Expr & E,QualType & ZeroArgCallReturnTy,UnresolvedSetImpl & OverloadSet)22147330f729Sjoerg bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
22157330f729Sjoerg                          UnresolvedSetImpl &OverloadSet) {
22167330f729Sjoerg   ZeroArgCallReturnTy = QualType();
22177330f729Sjoerg   OverloadSet.clear();
22187330f729Sjoerg 
22197330f729Sjoerg   const OverloadExpr *Overloads = nullptr;
22207330f729Sjoerg   bool IsMemExpr = false;
22217330f729Sjoerg   if (E.getType() == Context.OverloadTy) {
22227330f729Sjoerg     OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
22237330f729Sjoerg 
22247330f729Sjoerg     // Ignore overloads that are pointer-to-member constants.
22257330f729Sjoerg     if (FR.HasFormOfMemberPointer)
22267330f729Sjoerg       return false;
22277330f729Sjoerg 
22287330f729Sjoerg     Overloads = FR.Expression;
22297330f729Sjoerg   } else if (E.getType() == Context.BoundMemberTy) {
22307330f729Sjoerg     Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
22317330f729Sjoerg     IsMemExpr = true;
22327330f729Sjoerg   }
22337330f729Sjoerg 
22347330f729Sjoerg   bool Ambiguous = false;
22357330f729Sjoerg   bool IsMV = false;
22367330f729Sjoerg 
22377330f729Sjoerg   if (Overloads) {
22387330f729Sjoerg     for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
22397330f729Sjoerg          DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
22407330f729Sjoerg       OverloadSet.addDecl(*it);
22417330f729Sjoerg 
22427330f729Sjoerg       // Check whether the function is a non-template, non-member which takes no
22437330f729Sjoerg       // arguments.
22447330f729Sjoerg       if (IsMemExpr)
22457330f729Sjoerg         continue;
22467330f729Sjoerg       if (const FunctionDecl *OverloadDecl
22477330f729Sjoerg             = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
22487330f729Sjoerg         if (OverloadDecl->getMinRequiredArguments() == 0) {
22497330f729Sjoerg           if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
22507330f729Sjoerg               (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
22517330f729Sjoerg                           OverloadDecl->isCPUSpecificMultiVersion()))) {
22527330f729Sjoerg             ZeroArgCallReturnTy = QualType();
22537330f729Sjoerg             Ambiguous = true;
22547330f729Sjoerg           } else {
22557330f729Sjoerg             ZeroArgCallReturnTy = OverloadDecl->getReturnType();
22567330f729Sjoerg             IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
22577330f729Sjoerg                    OverloadDecl->isCPUSpecificMultiVersion();
22587330f729Sjoerg           }
22597330f729Sjoerg         }
22607330f729Sjoerg       }
22617330f729Sjoerg     }
22627330f729Sjoerg 
22637330f729Sjoerg     // If it's not a member, use better machinery to try to resolve the call
22647330f729Sjoerg     if (!IsMemExpr)
22657330f729Sjoerg       return !ZeroArgCallReturnTy.isNull();
22667330f729Sjoerg   }
22677330f729Sjoerg 
22687330f729Sjoerg   // Attempt to call the member with no arguments - this will correctly handle
22697330f729Sjoerg   // member templates with defaults/deduction of template arguments, overloads
22707330f729Sjoerg   // with default arguments, etc.
22717330f729Sjoerg   if (IsMemExpr && !E.isTypeDependent()) {
22727330f729Sjoerg     Sema::TentativeAnalysisScope Trap(*this);
22737330f729Sjoerg     ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
22747330f729Sjoerg                                              None, SourceLocation());
22757330f729Sjoerg     if (R.isUsable()) {
22767330f729Sjoerg       ZeroArgCallReturnTy = R.get()->getType();
22777330f729Sjoerg       return true;
22787330f729Sjoerg     }
22797330f729Sjoerg     return false;
22807330f729Sjoerg   }
22817330f729Sjoerg 
22827330f729Sjoerg   if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
22837330f729Sjoerg     if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
22847330f729Sjoerg       if (Fun->getMinRequiredArguments() == 0)
22857330f729Sjoerg         ZeroArgCallReturnTy = Fun->getReturnType();
22867330f729Sjoerg       return true;
22877330f729Sjoerg     }
22887330f729Sjoerg   }
22897330f729Sjoerg 
22907330f729Sjoerg   // We don't have an expression that's convenient to get a FunctionDecl from,
22917330f729Sjoerg   // but we can at least check if the type is "function of 0 arguments".
22927330f729Sjoerg   QualType ExprTy = E.getType();
22937330f729Sjoerg   const FunctionType *FunTy = nullptr;
22947330f729Sjoerg   QualType PointeeTy = ExprTy->getPointeeType();
22957330f729Sjoerg   if (!PointeeTy.isNull())
22967330f729Sjoerg     FunTy = PointeeTy->getAs<FunctionType>();
22977330f729Sjoerg   if (!FunTy)
22987330f729Sjoerg     FunTy = ExprTy->getAs<FunctionType>();
22997330f729Sjoerg 
23007330f729Sjoerg   if (const FunctionProtoType *FPT =
23017330f729Sjoerg       dyn_cast_or_null<FunctionProtoType>(FunTy)) {
23027330f729Sjoerg     if (FPT->getNumParams() == 0)
23037330f729Sjoerg       ZeroArgCallReturnTy = FunTy->getReturnType();
23047330f729Sjoerg     return true;
23057330f729Sjoerg   }
23067330f729Sjoerg   return false;
23077330f729Sjoerg }
23087330f729Sjoerg 
23097330f729Sjoerg /// Give notes for a set of overloads.
23107330f729Sjoerg ///
23117330f729Sjoerg /// A companion to tryExprAsCall. In cases when the name that the programmer
23127330f729Sjoerg /// wrote was an overloaded function, we may be able to make some guesses about
23137330f729Sjoerg /// plausible overloads based on their return types; such guesses can be handed
23147330f729Sjoerg /// off to this method to be emitted as notes.
23157330f729Sjoerg ///
23167330f729Sjoerg /// \param Overloads - The overloads to note.
23177330f729Sjoerg /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
23187330f729Sjoerg ///  -fshow-overloads=best, this is the location to attach to the note about too
23197330f729Sjoerg ///  many candidates. Typically this will be the location of the original
23207330f729Sjoerg ///  ill-formed expression.
noteOverloads(Sema & S,const UnresolvedSetImpl & Overloads,const SourceLocation FinalNoteLoc)23217330f729Sjoerg static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
23227330f729Sjoerg                           const SourceLocation FinalNoteLoc) {
2323*e038c9c4Sjoerg   unsigned ShownOverloads = 0;
2324*e038c9c4Sjoerg   unsigned SuppressedOverloads = 0;
23257330f729Sjoerg   for (UnresolvedSetImpl::iterator It = Overloads.begin(),
23267330f729Sjoerg        DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2327*e038c9c4Sjoerg     if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) {
23287330f729Sjoerg       ++SuppressedOverloads;
23297330f729Sjoerg       continue;
23307330f729Sjoerg     }
23317330f729Sjoerg 
23327330f729Sjoerg     NamedDecl *Fn = (*It)->getUnderlyingDecl();
23337330f729Sjoerg     // Don't print overloads for non-default multiversioned functions.
23347330f729Sjoerg     if (const auto *FD = Fn->getAsFunction()) {
23357330f729Sjoerg       if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
23367330f729Sjoerg           !FD->getAttr<TargetAttr>()->isDefaultVersion())
23377330f729Sjoerg         continue;
23387330f729Sjoerg     }
23397330f729Sjoerg     S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
23407330f729Sjoerg     ++ShownOverloads;
23417330f729Sjoerg   }
23427330f729Sjoerg 
2343*e038c9c4Sjoerg   S.Diags.overloadCandidatesShown(ShownOverloads);
2344*e038c9c4Sjoerg 
23457330f729Sjoerg   if (SuppressedOverloads)
23467330f729Sjoerg     S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
23477330f729Sjoerg       << SuppressedOverloads;
23487330f729Sjoerg }
23497330f729Sjoerg 
notePlausibleOverloads(Sema & S,SourceLocation Loc,const UnresolvedSetImpl & Overloads,bool (* IsPlausibleResult)(QualType))23507330f729Sjoerg static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
23517330f729Sjoerg                                    const UnresolvedSetImpl &Overloads,
23527330f729Sjoerg                                    bool (*IsPlausibleResult)(QualType)) {
23537330f729Sjoerg   if (!IsPlausibleResult)
23547330f729Sjoerg     return noteOverloads(S, Overloads, Loc);
23557330f729Sjoerg 
23567330f729Sjoerg   UnresolvedSet<2> PlausibleOverloads;
23577330f729Sjoerg   for (OverloadExpr::decls_iterator It = Overloads.begin(),
23587330f729Sjoerg          DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
23597330f729Sjoerg     const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
23607330f729Sjoerg     QualType OverloadResultTy = OverloadDecl->getReturnType();
23617330f729Sjoerg     if (IsPlausibleResult(OverloadResultTy))
23627330f729Sjoerg       PlausibleOverloads.addDecl(It.getDecl());
23637330f729Sjoerg   }
23647330f729Sjoerg   noteOverloads(S, PlausibleOverloads, Loc);
23657330f729Sjoerg }
23667330f729Sjoerg 
23677330f729Sjoerg /// Determine whether the given expression can be called by just
23687330f729Sjoerg /// putting parentheses after it.  Notably, expressions with unary
23697330f729Sjoerg /// operators can't be because the unary operator will start parsing
23707330f729Sjoerg /// outside the call.
IsCallableWithAppend(Expr * E)23717330f729Sjoerg static bool IsCallableWithAppend(Expr *E) {
23727330f729Sjoerg   E = E->IgnoreImplicit();
23737330f729Sjoerg   return (!isa<CStyleCastExpr>(E) &&
23747330f729Sjoerg           !isa<UnaryOperator>(E) &&
23757330f729Sjoerg           !isa<BinaryOperator>(E) &&
23767330f729Sjoerg           !isa<CXXOperatorCallExpr>(E));
23777330f729Sjoerg }
23787330f729Sjoerg 
IsCPUDispatchCPUSpecificMultiVersion(const Expr * E)23797330f729Sjoerg static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {
23807330f729Sjoerg   if (const auto *UO = dyn_cast<UnaryOperator>(E))
23817330f729Sjoerg     E = UO->getSubExpr();
23827330f729Sjoerg 
23837330f729Sjoerg   if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
23847330f729Sjoerg     if (ULE->getNumDecls() == 0)
23857330f729Sjoerg       return false;
23867330f729Sjoerg 
23877330f729Sjoerg     const NamedDecl *ND = *ULE->decls_begin();
23887330f729Sjoerg     if (const auto *FD = dyn_cast<FunctionDecl>(ND))
23897330f729Sjoerg       return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();
23907330f729Sjoerg   }
23917330f729Sjoerg   return false;
23927330f729Sjoerg }
23937330f729Sjoerg 
tryToRecoverWithCall(ExprResult & E,const PartialDiagnostic & PD,bool ForceComplain,bool (* IsPlausibleResult)(QualType))23947330f729Sjoerg bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
23957330f729Sjoerg                                 bool ForceComplain,
23967330f729Sjoerg                                 bool (*IsPlausibleResult)(QualType)) {
23977330f729Sjoerg   SourceLocation Loc = E.get()->getExprLoc();
23987330f729Sjoerg   SourceRange Range = E.get()->getSourceRange();
23997330f729Sjoerg 
24007330f729Sjoerg   QualType ZeroArgCallTy;
24017330f729Sjoerg   UnresolvedSet<4> Overloads;
24027330f729Sjoerg   if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
24037330f729Sjoerg       !ZeroArgCallTy.isNull() &&
24047330f729Sjoerg       (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
24057330f729Sjoerg     // At this point, we know E is potentially callable with 0
24067330f729Sjoerg     // arguments and that it returns something of a reasonable type,
24077330f729Sjoerg     // so we can emit a fixit and carry on pretending that E was
24087330f729Sjoerg     // actually a CallExpr.
24097330f729Sjoerg     SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
24107330f729Sjoerg     bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
24117330f729Sjoerg     Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
24127330f729Sjoerg                   << (IsCallableWithAppend(E.get())
24137330f729Sjoerg                           ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
24147330f729Sjoerg                           : FixItHint());
24157330f729Sjoerg     if (!IsMV)
24167330f729Sjoerg       notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
24177330f729Sjoerg 
24187330f729Sjoerg     // FIXME: Try this before emitting the fixit, and suppress diagnostics
24197330f729Sjoerg     // while doing so.
24207330f729Sjoerg     E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), None,
24217330f729Sjoerg                       Range.getEnd().getLocWithOffset(1));
24227330f729Sjoerg     return true;
24237330f729Sjoerg   }
24247330f729Sjoerg 
24257330f729Sjoerg   if (!ForceComplain) return false;
24267330f729Sjoerg 
24277330f729Sjoerg   bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
24287330f729Sjoerg   Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
24297330f729Sjoerg   if (!IsMV)
24307330f729Sjoerg     notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
24317330f729Sjoerg   E = ExprError();
24327330f729Sjoerg   return true;
24337330f729Sjoerg }
24347330f729Sjoerg 
getSuperIdentifier() const24357330f729Sjoerg IdentifierInfo *Sema::getSuperIdentifier() const {
24367330f729Sjoerg   if (!Ident_super)
24377330f729Sjoerg     Ident_super = &Context.Idents.get("super");
24387330f729Sjoerg   return Ident_super;
24397330f729Sjoerg }
24407330f729Sjoerg 
getFloat128Identifier() const24417330f729Sjoerg IdentifierInfo *Sema::getFloat128Identifier() const {
24427330f729Sjoerg   if (!Ident___float128)
24437330f729Sjoerg     Ident___float128 = &Context.Idents.get("__float128");
24447330f729Sjoerg   return Ident___float128;
24457330f729Sjoerg }
24467330f729Sjoerg 
PushCapturedRegionScope(Scope * S,CapturedDecl * CD,RecordDecl * RD,CapturedRegionKind K,unsigned OpenMPCaptureLevel)24477330f729Sjoerg void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
24487330f729Sjoerg                                    CapturedRegionKind K,
24497330f729Sjoerg                                    unsigned OpenMPCaptureLevel) {
24507330f729Sjoerg   auto *CSI = new CapturedRegionScopeInfo(
24517330f729Sjoerg       getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
24527330f729Sjoerg       (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0,
24537330f729Sjoerg       OpenMPCaptureLevel);
24547330f729Sjoerg   CSI->ReturnType = Context.VoidTy;
24557330f729Sjoerg   FunctionScopes.push_back(CSI);
24567330f729Sjoerg }
24577330f729Sjoerg 
getCurCapturedRegion()24587330f729Sjoerg CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
24597330f729Sjoerg   if (FunctionScopes.empty())
24607330f729Sjoerg     return nullptr;
24617330f729Sjoerg 
24627330f729Sjoerg   return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
24637330f729Sjoerg }
24647330f729Sjoerg 
24657330f729Sjoerg const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
getMismatchingDeleteExpressions() const24667330f729Sjoerg Sema::getMismatchingDeleteExpressions() const {
24677330f729Sjoerg   return DeleteExprs;
24687330f729Sjoerg }
2469