xref: /openbsd-src/gnu/llvm/clang/lib/Sema/Sema.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This file implements the actions class which performs semantic analysis and
10e5dd7070Spatrick // builds an AST out of a parse stream.
11e5dd7070Spatrick //
12e5dd7070Spatrick //===----------------------------------------------------------------------===//
13e5dd7070Spatrick 
14ec727ea7Spatrick #include "UsedDeclVisitor.h"
15e5dd7070Spatrick #include "clang/AST/ASTContext.h"
16e5dd7070Spatrick #include "clang/AST/ASTDiagnostic.h"
17a9ac8606Spatrick #include "clang/AST/Decl.h"
18e5dd7070Spatrick #include "clang/AST/DeclCXX.h"
19e5dd7070Spatrick #include "clang/AST/DeclFriend.h"
20e5dd7070Spatrick #include "clang/AST/DeclObjC.h"
21e5dd7070Spatrick #include "clang/AST/Expr.h"
22e5dd7070Spatrick #include "clang/AST/ExprCXX.h"
23e5dd7070Spatrick #include "clang/AST/PrettyDeclStackTrace.h"
24e5dd7070Spatrick #include "clang/AST/StmtCXX.h"
25a9ac8606Spatrick #include "clang/Basic/DarwinSDKInfo.h"
26e5dd7070Spatrick #include "clang/Basic/DiagnosticOptions.h"
27e5dd7070Spatrick #include "clang/Basic/PartialDiagnostic.h"
28ec727ea7Spatrick #include "clang/Basic/SourceManager.h"
29e5dd7070Spatrick #include "clang/Basic/Stack.h"
30e5dd7070Spatrick #include "clang/Basic/TargetInfo.h"
31e5dd7070Spatrick #include "clang/Lex/HeaderSearch.h"
32a9ac8606Spatrick #include "clang/Lex/HeaderSearchOptions.h"
33e5dd7070Spatrick #include "clang/Lex/Preprocessor.h"
34e5dd7070Spatrick #include "clang/Sema/CXXFieldCollector.h"
35e5dd7070Spatrick #include "clang/Sema/DelayedDiagnostic.h"
36e5dd7070Spatrick #include "clang/Sema/ExternalSemaSource.h"
37e5dd7070Spatrick #include "clang/Sema/Initialization.h"
38e5dd7070Spatrick #include "clang/Sema/MultiplexExternalSemaSource.h"
39e5dd7070Spatrick #include "clang/Sema/ObjCMethodList.h"
40*12c85518Srobert #include "clang/Sema/RISCVIntrinsicManager.h"
41e5dd7070Spatrick #include "clang/Sema/Scope.h"
42e5dd7070Spatrick #include "clang/Sema/ScopeInfo.h"
43e5dd7070Spatrick #include "clang/Sema/SemaConsumer.h"
44e5dd7070Spatrick #include "clang/Sema/SemaInternal.h"
45e5dd7070Spatrick #include "clang/Sema/TemplateDeduction.h"
46e5dd7070Spatrick #include "clang/Sema/TemplateInstCallback.h"
47e5dd7070Spatrick #include "clang/Sema/TypoCorrection.h"
48e5dd7070Spatrick #include "llvm/ADT/DenseMap.h"
49*12c85518Srobert #include "llvm/ADT/STLExtras.h"
50a9ac8606Spatrick #include "llvm/ADT/SmallPtrSet.h"
51e5dd7070Spatrick #include "llvm/Support/TimeProfiler.h"
52*12c85518Srobert #include <optional>
53e5dd7070Spatrick 
54e5dd7070Spatrick using namespace clang;
55e5dd7070Spatrick using namespace sema;
56e5dd7070Spatrick 
getLocForEndOfToken(SourceLocation Loc,unsigned Offset)57e5dd7070Spatrick SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
58e5dd7070Spatrick   return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
59e5dd7070Spatrick }
60e5dd7070Spatrick 
getModuleLoader() const61e5dd7070Spatrick ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
62e5dd7070Spatrick 
63a9ac8606Spatrick DarwinSDKInfo *
getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,StringRef Platform)64a9ac8606Spatrick Sema::getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
65a9ac8606Spatrick                                               StringRef Platform) {
66*12c85518Srobert   auto *SDKInfo = getDarwinSDKInfoForAvailabilityChecking();
67*12c85518Srobert   if (!SDKInfo && !WarnedDarwinSDKInfoMissing) {
68*12c85518Srobert     Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking)
69*12c85518Srobert         << Platform;
70*12c85518Srobert     WarnedDarwinSDKInfoMissing = true;
71*12c85518Srobert   }
72*12c85518Srobert   return SDKInfo;
73*12c85518Srobert }
74*12c85518Srobert 
getDarwinSDKInfoForAvailabilityChecking()75*12c85518Srobert DarwinSDKInfo *Sema::getDarwinSDKInfoForAvailabilityChecking() {
76a9ac8606Spatrick   if (CachedDarwinSDKInfo)
77a9ac8606Spatrick     return CachedDarwinSDKInfo->get();
78a9ac8606Spatrick   auto SDKInfo = parseDarwinSDKInfo(
79a9ac8606Spatrick       PP.getFileManager().getVirtualFileSystem(),
80a9ac8606Spatrick       PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot);
81a9ac8606Spatrick   if (SDKInfo && *SDKInfo) {
82a9ac8606Spatrick     CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo));
83a9ac8606Spatrick     return CachedDarwinSDKInfo->get();
84a9ac8606Spatrick   }
85a9ac8606Spatrick   if (!SDKInfo)
86a9ac8606Spatrick     llvm::consumeError(SDKInfo.takeError());
87a9ac8606Spatrick   CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>();
88a9ac8606Spatrick   return nullptr;
89a9ac8606Spatrick }
90a9ac8606Spatrick 
91e5dd7070Spatrick IdentifierInfo *
InventAbbreviatedTemplateParameterTypeName(IdentifierInfo * ParamName,unsigned int Index)92e5dd7070Spatrick Sema::InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
93e5dd7070Spatrick                                                  unsigned int Index) {
94e5dd7070Spatrick   std::string InventedName;
95e5dd7070Spatrick   llvm::raw_string_ostream OS(InventedName);
96e5dd7070Spatrick 
97e5dd7070Spatrick   if (!ParamName)
98e5dd7070Spatrick     OS << "auto:" << Index + 1;
99e5dd7070Spatrick   else
100e5dd7070Spatrick     OS << ParamName->getName() << ":auto";
101e5dd7070Spatrick 
102e5dd7070Spatrick   OS.flush();
103e5dd7070Spatrick   return &Context.Idents.get(OS.str());
104e5dd7070Spatrick }
105e5dd7070Spatrick 
getPrintingPolicy(const ASTContext & Context,const Preprocessor & PP)106e5dd7070Spatrick PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
107e5dd7070Spatrick                                        const Preprocessor &PP) {
108e5dd7070Spatrick   PrintingPolicy Policy = Context.getPrintingPolicy();
109e5dd7070Spatrick   // In diagnostics, we print _Bool as bool if the latter is defined as the
110e5dd7070Spatrick   // former.
111e5dd7070Spatrick   Policy.Bool = Context.getLangOpts().Bool;
112e5dd7070Spatrick   if (!Policy.Bool) {
113e5dd7070Spatrick     if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
114e5dd7070Spatrick       Policy.Bool = BoolMacro->isObjectLike() &&
115e5dd7070Spatrick                     BoolMacro->getNumTokens() == 1 &&
116e5dd7070Spatrick                     BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
117e5dd7070Spatrick     }
118e5dd7070Spatrick   }
119e5dd7070Spatrick 
120*12c85518Srobert   // Shorten the data output if needed
121*12c85518Srobert   Policy.EntireContentsOfLargeArray = false;
122*12c85518Srobert 
123e5dd7070Spatrick   return Policy;
124e5dd7070Spatrick }
125e5dd7070Spatrick 
ActOnTranslationUnitScope(Scope * S)126e5dd7070Spatrick void Sema::ActOnTranslationUnitScope(Scope *S) {
127e5dd7070Spatrick   TUScope = S;
128e5dd7070Spatrick   PushDeclContext(S, Context.getTranslationUnitDecl());
129e5dd7070Spatrick }
130e5dd7070Spatrick 
131e5dd7070Spatrick namespace clang {
132e5dd7070Spatrick namespace sema {
133e5dd7070Spatrick 
134e5dd7070Spatrick class SemaPPCallbacks : public PPCallbacks {
135e5dd7070Spatrick   Sema *S = nullptr;
136e5dd7070Spatrick   llvm::SmallVector<SourceLocation, 8> IncludeStack;
137e5dd7070Spatrick 
138e5dd7070Spatrick public:
set(Sema & S)139e5dd7070Spatrick   void set(Sema &S) { this->S = &S; }
140e5dd7070Spatrick 
reset()141e5dd7070Spatrick   void reset() { S = nullptr; }
142e5dd7070Spatrick 
FileChanged(SourceLocation Loc,FileChangeReason Reason,SrcMgr::CharacteristicKind FileType,FileID PrevFID)143*12c85518Srobert   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
144e5dd7070Spatrick                    SrcMgr::CharacteristicKind FileType,
145e5dd7070Spatrick                    FileID PrevFID) override {
146e5dd7070Spatrick     if (!S)
147e5dd7070Spatrick       return;
148e5dd7070Spatrick     switch (Reason) {
149e5dd7070Spatrick     case EnterFile: {
150e5dd7070Spatrick       SourceManager &SM = S->getSourceManager();
151e5dd7070Spatrick       SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
152e5dd7070Spatrick       if (IncludeLoc.isValid()) {
153e5dd7070Spatrick         if (llvm::timeTraceProfilerEnabled()) {
154e5dd7070Spatrick           const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
155e5dd7070Spatrick           llvm::timeTraceProfilerBegin(
156e5dd7070Spatrick               "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>"));
157e5dd7070Spatrick         }
158e5dd7070Spatrick 
159e5dd7070Spatrick         IncludeStack.push_back(IncludeLoc);
160a9ac8606Spatrick         S->DiagnoseNonDefaultPragmaAlignPack(
161a9ac8606Spatrick             Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude,
162a9ac8606Spatrick             IncludeLoc);
163e5dd7070Spatrick       }
164e5dd7070Spatrick       break;
165e5dd7070Spatrick     }
166e5dd7070Spatrick     case ExitFile:
167e5dd7070Spatrick       if (!IncludeStack.empty()) {
168e5dd7070Spatrick         if (llvm::timeTraceProfilerEnabled())
169e5dd7070Spatrick           llvm::timeTraceProfilerEnd();
170e5dd7070Spatrick 
171a9ac8606Spatrick         S->DiagnoseNonDefaultPragmaAlignPack(
172a9ac8606Spatrick             Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit,
173e5dd7070Spatrick             IncludeStack.pop_back_val());
174e5dd7070Spatrick       }
175e5dd7070Spatrick       break;
176e5dd7070Spatrick     default:
177e5dd7070Spatrick       break;
178e5dd7070Spatrick     }
179e5dd7070Spatrick   }
180e5dd7070Spatrick };
181e5dd7070Spatrick 
182e5dd7070Spatrick } // end namespace sema
183e5dd7070Spatrick } // end namespace clang
184e5dd7070Spatrick 
185ec727ea7Spatrick const unsigned Sema::MaxAlignmentExponent;
186*12c85518Srobert const uint64_t Sema::MaximumAlignment;
187ec727ea7Spatrick 
Sema(Preprocessor & pp,ASTContext & ctxt,ASTConsumer & consumer,TranslationUnitKind TUKind,CodeCompleteConsumer * CodeCompleter)188e5dd7070Spatrick Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
189e5dd7070Spatrick            TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
190*12c85518Srobert     : ExternalSource(nullptr), CurFPFeatures(pp.getLangOpts()),
191*12c85518Srobert       LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer),
192*12c85518Srobert       Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
193*12c85518Srobert       CollectStats(false), CodeCompleter(CodeCompleter), CurContext(nullptr),
194e5dd7070Spatrick       OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
195e5dd7070Spatrick       MSPointerToMemberRepresentationMethod(
196e5dd7070Spatrick           LangOpts.getMSPointerToMemberRepresentationMethod()),
197a9ac8606Spatrick       VtorDispStack(LangOpts.getVtorDispMode()),
198a9ac8606Spatrick       AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)),
199e5dd7070Spatrick       DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
200*12c85518Srobert       CodeSegStack(nullptr), StrictGuardStackCheckStack(false),
201*12c85518Srobert       FpPragmaStack(FPOptionsOverride()), CurInitSeg(nullptr),
202*12c85518Srobert       VisContext(nullptr), PragmaAttributeCurrentTargetDecl(nullptr),
203*12c85518Srobert       IsBuildingRecoveryCallExpr(false), LateTemplateParser(nullptr),
204e5dd7070Spatrick       LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
205e5dd7070Spatrick       StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
206e5dd7070Spatrick       StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr),
207*12c85518Srobert       MSVCGuidDecl(nullptr), StdSourceLocationImplDecl(nullptr),
208*12c85518Srobert       NSNumberDecl(nullptr), NSValueDecl(nullptr), NSStringDecl(nullptr),
209*12c85518Srobert       StringWithUTF8StringMethod(nullptr),
210e5dd7070Spatrick       ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
211e5dd7070Spatrick       ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
212e5dd7070Spatrick       DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
213e5dd7070Spatrick       TUKind(TUKind), NumSFINAEErrors(0),
214e5dd7070Spatrick       FullyCheckedComparisonCategories(
215e5dd7070Spatrick           static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
216e5dd7070Spatrick       SatisfactionCache(Context), AccessCheckingSFINAE(false),
217e5dd7070Spatrick       InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
218e5dd7070Spatrick       ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
219e5dd7070Spatrick       DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
220e5dd7070Spatrick       ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
221e5dd7070Spatrick       CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
222a9ac8606Spatrick   assert(pp.TUKind == TUKind);
223e5dd7070Spatrick   TUScope = nullptr;
224e5dd7070Spatrick   isConstantEvaluatedOverride = false;
225e5dd7070Spatrick 
226e5dd7070Spatrick   LoadedExternalKnownNamespaces = false;
227e5dd7070Spatrick   for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
228e5dd7070Spatrick     NSNumberLiteralMethods[I] = nullptr;
229e5dd7070Spatrick 
230e5dd7070Spatrick   if (getLangOpts().ObjC)
231e5dd7070Spatrick     NSAPIObj.reset(new NSAPI(Context));
232e5dd7070Spatrick 
233e5dd7070Spatrick   if (getLangOpts().CPlusPlus)
234e5dd7070Spatrick     FieldCollector.reset(new CXXFieldCollector());
235e5dd7070Spatrick 
236e5dd7070Spatrick   // Tell diagnostics how to render things from the AST library.
237e5dd7070Spatrick   Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
238e5dd7070Spatrick 
239*12c85518Srobert   // This evaluation context exists to ensure that there's always at least one
240*12c85518Srobert   // valid evaluation context available. It is never removed from the
241*12c85518Srobert   // evaluation stack.
242e5dd7070Spatrick   ExprEvalContexts.emplace_back(
243e5dd7070Spatrick       ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
244e5dd7070Spatrick       nullptr, ExpressionEvaluationContextRecord::EK_Other);
245e5dd7070Spatrick 
246e5dd7070Spatrick   // Initialization of data sharing attributes stack for OpenMP
247e5dd7070Spatrick   InitDataSharingAttributesStack();
248e5dd7070Spatrick 
249e5dd7070Spatrick   std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
250e5dd7070Spatrick       std::make_unique<sema::SemaPPCallbacks>();
251e5dd7070Spatrick   SemaPPCallbackHandler = Callbacks.get();
252e5dd7070Spatrick   PP.addPPCallbacks(std::move(Callbacks));
253e5dd7070Spatrick   SemaPPCallbackHandler->set(*this);
254*12c85518Srobert 
255*12c85518Srobert   CurFPFeatures.setFPEvalMethod(PP.getCurrentFPEvalMethod());
256e5dd7070Spatrick }
257e5dd7070Spatrick 
258e5dd7070Spatrick // Anchor Sema's type info to this TU.
anchor()259e5dd7070Spatrick void Sema::anchor() {}
260e5dd7070Spatrick 
addImplicitTypedef(StringRef Name,QualType T)261e5dd7070Spatrick void Sema::addImplicitTypedef(StringRef Name, QualType T) {
262e5dd7070Spatrick   DeclarationName DN = &Context.Idents.get(Name);
263e5dd7070Spatrick   if (IdResolver.begin(DN) == IdResolver.end())
264e5dd7070Spatrick     PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
265e5dd7070Spatrick }
266e5dd7070Spatrick 
Initialize()267e5dd7070Spatrick void Sema::Initialize() {
268e5dd7070Spatrick   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
269e5dd7070Spatrick     SC->InitializeSema(*this);
270e5dd7070Spatrick 
271e5dd7070Spatrick   // Tell the external Sema source about this Sema object.
272e5dd7070Spatrick   if (ExternalSemaSource *ExternalSema
273e5dd7070Spatrick       = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
274e5dd7070Spatrick     ExternalSema->InitializeSema(*this);
275e5dd7070Spatrick 
276e5dd7070Spatrick   // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
277e5dd7070Spatrick   // will not be able to merge any duplicate __va_list_tag decls correctly.
278e5dd7070Spatrick   VAListTagName = PP.getIdentifierInfo("__va_list_tag");
279e5dd7070Spatrick 
280e5dd7070Spatrick   if (!TUScope)
281e5dd7070Spatrick     return;
282e5dd7070Spatrick 
283e5dd7070Spatrick   // Initialize predefined 128-bit integer types, if needed.
284a9ac8606Spatrick   if (Context.getTargetInfo().hasInt128Type() ||
285a9ac8606Spatrick       (Context.getAuxTargetInfo() &&
286a9ac8606Spatrick        Context.getAuxTargetInfo()->hasInt128Type())) {
287e5dd7070Spatrick     // If either of the 128-bit integer types are unavailable to name lookup,
288e5dd7070Spatrick     // define them now.
289e5dd7070Spatrick     DeclarationName Int128 = &Context.Idents.get("__int128_t");
290e5dd7070Spatrick     if (IdResolver.begin(Int128) == IdResolver.end())
291e5dd7070Spatrick       PushOnScopeChains(Context.getInt128Decl(), TUScope);
292e5dd7070Spatrick 
293e5dd7070Spatrick     DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
294e5dd7070Spatrick     if (IdResolver.begin(UInt128) == IdResolver.end())
295e5dd7070Spatrick       PushOnScopeChains(Context.getUInt128Decl(), TUScope);
296e5dd7070Spatrick   }
297e5dd7070Spatrick 
298e5dd7070Spatrick 
299e5dd7070Spatrick   // Initialize predefined Objective-C types:
300e5dd7070Spatrick   if (getLangOpts().ObjC) {
301e5dd7070Spatrick     // If 'SEL' does not yet refer to any declarations, make it refer to the
302e5dd7070Spatrick     // predefined 'SEL'.
303e5dd7070Spatrick     DeclarationName SEL = &Context.Idents.get("SEL");
304e5dd7070Spatrick     if (IdResolver.begin(SEL) == IdResolver.end())
305e5dd7070Spatrick       PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
306e5dd7070Spatrick 
307e5dd7070Spatrick     // If 'id' does not yet refer to any declarations, make it refer to the
308e5dd7070Spatrick     // predefined 'id'.
309e5dd7070Spatrick     DeclarationName Id = &Context.Idents.get("id");
310e5dd7070Spatrick     if (IdResolver.begin(Id) == IdResolver.end())
311e5dd7070Spatrick       PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
312e5dd7070Spatrick 
313e5dd7070Spatrick     // Create the built-in typedef for 'Class'.
314e5dd7070Spatrick     DeclarationName Class = &Context.Idents.get("Class");
315e5dd7070Spatrick     if (IdResolver.begin(Class) == IdResolver.end())
316e5dd7070Spatrick       PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
317e5dd7070Spatrick 
318e5dd7070Spatrick     // Create the built-in forward declaratino for 'Protocol'.
319e5dd7070Spatrick     DeclarationName Protocol = &Context.Idents.get("Protocol");
320e5dd7070Spatrick     if (IdResolver.begin(Protocol) == IdResolver.end())
321e5dd7070Spatrick       PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
322e5dd7070Spatrick   }
323e5dd7070Spatrick 
324e5dd7070Spatrick   // Create the internal type for the *StringMakeConstantString builtins.
325e5dd7070Spatrick   DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
326e5dd7070Spatrick   if (IdResolver.begin(ConstantString) == IdResolver.end())
327e5dd7070Spatrick     PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
328e5dd7070Spatrick 
329e5dd7070Spatrick   // Initialize Microsoft "predefined C++ types".
330e5dd7070Spatrick   if (getLangOpts().MSVCCompat) {
331e5dd7070Spatrick     if (getLangOpts().CPlusPlus &&
332e5dd7070Spatrick         IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
333e5dd7070Spatrick       PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
334e5dd7070Spatrick                         TUScope);
335e5dd7070Spatrick 
336e5dd7070Spatrick     addImplicitTypedef("size_t", Context.getSizeType());
337e5dd7070Spatrick   }
338e5dd7070Spatrick 
339e5dd7070Spatrick   // Initialize predefined OpenCL types and supported extensions and (optional)
340e5dd7070Spatrick   // core features.
341e5dd7070Spatrick   if (getLangOpts().OpenCL) {
342e5dd7070Spatrick     getOpenCLOptions().addSupport(
343a9ac8606Spatrick         Context.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts());
344e5dd7070Spatrick     addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
345e5dd7070Spatrick     addImplicitTypedef("event_t", Context.OCLEventTy);
346*12c85518Srobert     auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion();
347*12c85518Srobert     if (OCLCompatibleVersion >= 200) {
348*12c85518Srobert       if (getLangOpts().OpenCLCPlusPlus || getLangOpts().Blocks) {
349e5dd7070Spatrick         addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
350e5dd7070Spatrick         addImplicitTypedef("queue_t", Context.OCLQueueTy);
351*12c85518Srobert       }
352a9ac8606Spatrick       if (getLangOpts().OpenCLPipes)
353e5dd7070Spatrick         addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
354e5dd7070Spatrick       addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
355e5dd7070Spatrick       addImplicitTypedef("atomic_uint",
356e5dd7070Spatrick                          Context.getAtomicType(Context.UnsignedIntTy));
357e5dd7070Spatrick       addImplicitTypedef("atomic_float",
358e5dd7070Spatrick                          Context.getAtomicType(Context.FloatTy));
359e5dd7070Spatrick       // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
360e5dd7070Spatrick       // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
361e5dd7070Spatrick       addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
362a9ac8606Spatrick 
363e5dd7070Spatrick 
364e5dd7070Spatrick       // OpenCL v2.0 s6.13.11.6:
365e5dd7070Spatrick       // - The atomic_long and atomic_ulong types are supported if the
366e5dd7070Spatrick       //   cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
367e5dd7070Spatrick       //   extensions are supported.
368e5dd7070Spatrick       // - The atomic_double type is only supported if double precision
369e5dd7070Spatrick       //   is supported and the cl_khr_int64_base_atomics and
370e5dd7070Spatrick       //   cl_khr_int64_extended_atomics extensions are supported.
371e5dd7070Spatrick       // - If the device address space is 64-bits, the data types
372e5dd7070Spatrick       //   atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
373e5dd7070Spatrick       //   atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
374e5dd7070Spatrick       //   cl_khr_int64_extended_atomics extensions are supported.
375a9ac8606Spatrick 
376a9ac8606Spatrick       auto AddPointerSizeDependentTypes = [&]() {
377a9ac8606Spatrick         auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
378a9ac8606Spatrick         auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
379a9ac8606Spatrick         auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
380a9ac8606Spatrick         auto AtomicPtrDiffT =
381a9ac8606Spatrick             Context.getAtomicType(Context.getPointerDiffType());
382a9ac8606Spatrick         addImplicitTypedef("atomic_size_t", AtomicSizeT);
383a9ac8606Spatrick         addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
384a9ac8606Spatrick         addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
385a9ac8606Spatrick         addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
386a9ac8606Spatrick       };
387a9ac8606Spatrick 
388a9ac8606Spatrick       if (Context.getTypeSize(Context.getSizeType()) == 32) {
389a9ac8606Spatrick         AddPointerSizeDependentTypes();
390a9ac8606Spatrick       }
391a9ac8606Spatrick 
392*12c85518Srobert       if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) {
393*12c85518Srobert         auto AtomicHalfT = Context.getAtomicType(Context.HalfTy);
394*12c85518Srobert         addImplicitTypedef("atomic_half", AtomicHalfT);
395*12c85518Srobert       }
396*12c85518Srobert 
397e5dd7070Spatrick       std::vector<QualType> Atomic64BitTypes;
398a9ac8606Spatrick       if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",
399a9ac8606Spatrick                                          getLangOpts()) &&
400a9ac8606Spatrick           getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",
401a9ac8606Spatrick                                          getLangOpts())) {
402a9ac8606Spatrick         if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {
403a9ac8606Spatrick           auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
404a9ac8606Spatrick           addImplicitTypedef("atomic_double", AtomicDoubleT);
405e5dd7070Spatrick           Atomic64BitTypes.push_back(AtomicDoubleT);
406e5dd7070Spatrick         }
407a9ac8606Spatrick         auto AtomicLongT = Context.getAtomicType(Context.LongTy);
408a9ac8606Spatrick         auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
409a9ac8606Spatrick         addImplicitTypedef("atomic_long", AtomicLongT);
410a9ac8606Spatrick         addImplicitTypedef("atomic_ulong", AtomicULongT);
411e5dd7070Spatrick 
412a9ac8606Spatrick 
413a9ac8606Spatrick         if (Context.getTypeSize(Context.getSizeType()) == 64) {
414a9ac8606Spatrick           AddPointerSizeDependentTypes();
415a9ac8606Spatrick         }
416a9ac8606Spatrick       }
417e5dd7070Spatrick     }
418e5dd7070Spatrick 
419e5dd7070Spatrick #define EXT_OPAQUE_TYPE(ExtType, Id, Ext)                                      \
420a9ac8606Spatrick   if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) {                   \
421e5dd7070Spatrick     addImplicitTypedef(#ExtType, Context.Id##Ty);                              \
422a9ac8606Spatrick   }
423e5dd7070Spatrick #include "clang/Basic/OpenCLExtensionTypes.def"
424e5dd7070Spatrick   }
425e5dd7070Spatrick 
426e5dd7070Spatrick   if (Context.getTargetInfo().hasAArch64SVETypes()) {
427e5dd7070Spatrick #define SVE_TYPE(Name, Id, SingletonId) \
428e5dd7070Spatrick     addImplicitTypedef(Name, Context.SingletonId);
429e5dd7070Spatrick #include "clang/Basic/AArch64SVEACLETypes.def"
430e5dd7070Spatrick   }
431e5dd7070Spatrick 
432*12c85518Srobert   if (Context.getTargetInfo().getTriple().isPPC64()) {
433a9ac8606Spatrick #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
434a9ac8606Spatrick       addImplicitTypedef(#Name, Context.Id##Ty);
435a9ac8606Spatrick #include "clang/Basic/PPCTypes.def"
436a9ac8606Spatrick #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
437a9ac8606Spatrick     addImplicitTypedef(#Name, Context.Id##Ty);
438a9ac8606Spatrick #include "clang/Basic/PPCTypes.def"
439a9ac8606Spatrick   }
440a9ac8606Spatrick 
441a9ac8606Spatrick   if (Context.getTargetInfo().hasRISCVVTypes()) {
442a9ac8606Spatrick #define RVV_TYPE(Name, Id, SingletonId)                                        \
443a9ac8606Spatrick   addImplicitTypedef(Name, Context.SingletonId);
444a9ac8606Spatrick #include "clang/Basic/RISCVVTypes.def"
445a9ac8606Spatrick   }
446a9ac8606Spatrick 
447e5dd7070Spatrick   if (Context.getTargetInfo().hasBuiltinMSVaList()) {
448e5dd7070Spatrick     DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
449e5dd7070Spatrick     if (IdResolver.begin(MSVaList) == IdResolver.end())
450e5dd7070Spatrick       PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
451e5dd7070Spatrick   }
452e5dd7070Spatrick 
453e5dd7070Spatrick   DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
454e5dd7070Spatrick   if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
455e5dd7070Spatrick     PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
456e5dd7070Spatrick }
457e5dd7070Spatrick 
~Sema()458e5dd7070Spatrick Sema::~Sema() {
459a9ac8606Spatrick   assert(InstantiatingSpecializations.empty() &&
460a9ac8606Spatrick          "failed to clean up an InstantiatingTemplate?");
461a9ac8606Spatrick 
462e5dd7070Spatrick   if (VisContext) FreeVisContext();
463e5dd7070Spatrick 
464e5dd7070Spatrick   // Kill all the active scopes.
465e5dd7070Spatrick   for (sema::FunctionScopeInfo *FSI : FunctionScopes)
466e5dd7070Spatrick     delete FSI;
467e5dd7070Spatrick 
468e5dd7070Spatrick   // Tell the SemaConsumer to forget about us; we're going out of scope.
469e5dd7070Spatrick   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
470e5dd7070Spatrick     SC->ForgetSema();
471e5dd7070Spatrick 
472e5dd7070Spatrick   // Detach from the external Sema source.
473e5dd7070Spatrick   if (ExternalSemaSource *ExternalSema
474e5dd7070Spatrick         = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
475e5dd7070Spatrick     ExternalSema->ForgetSema();
476e5dd7070Spatrick 
477e5dd7070Spatrick   // Delete cached satisfactions.
478e5dd7070Spatrick   std::vector<ConstraintSatisfaction *> Satisfactions;
479e5dd7070Spatrick   Satisfactions.reserve(Satisfactions.size());
480e5dd7070Spatrick   for (auto &Node : SatisfactionCache)
481e5dd7070Spatrick     Satisfactions.push_back(&Node);
482e5dd7070Spatrick   for (auto *Node : Satisfactions)
483e5dd7070Spatrick     delete Node;
484e5dd7070Spatrick 
485e5dd7070Spatrick   threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
486e5dd7070Spatrick 
487e5dd7070Spatrick   // Destroys data sharing attributes stack for OpenMP
488e5dd7070Spatrick   DestroyDataSharingAttributesStack();
489e5dd7070Spatrick 
490e5dd7070Spatrick   // Detach from the PP callback handler which outlives Sema since it's owned
491e5dd7070Spatrick   // by the preprocessor.
492e5dd7070Spatrick   SemaPPCallbackHandler->reset();
493e5dd7070Spatrick }
494e5dd7070Spatrick 
warnStackExhausted(SourceLocation Loc)495e5dd7070Spatrick void Sema::warnStackExhausted(SourceLocation Loc) {
496e5dd7070Spatrick   // Only warn about this once.
497e5dd7070Spatrick   if (!WarnedStackExhausted) {
498e5dd7070Spatrick     Diag(Loc, diag::warn_stack_exhausted);
499e5dd7070Spatrick     WarnedStackExhausted = true;
500e5dd7070Spatrick   }
501e5dd7070Spatrick }
502e5dd7070Spatrick 
runWithSufficientStackSpace(SourceLocation Loc,llvm::function_ref<void ()> Fn)503e5dd7070Spatrick void Sema::runWithSufficientStackSpace(SourceLocation Loc,
504e5dd7070Spatrick                                        llvm::function_ref<void()> Fn) {
505e5dd7070Spatrick   clang::runWithSufficientStackSpace([&] { warnStackExhausted(Loc); }, Fn);
506e5dd7070Spatrick }
507e5dd7070Spatrick 
508e5dd7070Spatrick /// makeUnavailableInSystemHeader - There is an error in the current
509e5dd7070Spatrick /// context.  If we're still in a system header, and we can plausibly
510e5dd7070Spatrick /// make the relevant declaration unavailable instead of erroring, do
511e5dd7070Spatrick /// so and return true.
makeUnavailableInSystemHeader(SourceLocation loc,UnavailableAttr::ImplicitReason reason)512e5dd7070Spatrick bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
513e5dd7070Spatrick                                       UnavailableAttr::ImplicitReason reason) {
514e5dd7070Spatrick   // If we're not in a function, it's an error.
515e5dd7070Spatrick   FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
516e5dd7070Spatrick   if (!fn) return false;
517e5dd7070Spatrick 
518e5dd7070Spatrick   // If we're in template instantiation, it's an error.
519e5dd7070Spatrick   if (inTemplateInstantiation())
520e5dd7070Spatrick     return false;
521e5dd7070Spatrick 
522e5dd7070Spatrick   // If that function's not in a system header, it's an error.
523e5dd7070Spatrick   if (!Context.getSourceManager().isInSystemHeader(loc))
524e5dd7070Spatrick     return false;
525e5dd7070Spatrick 
526e5dd7070Spatrick   // If the function is already unavailable, it's not an error.
527e5dd7070Spatrick   if (fn->hasAttr<UnavailableAttr>()) return true;
528e5dd7070Spatrick 
529e5dd7070Spatrick   fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
530e5dd7070Spatrick   return true;
531e5dd7070Spatrick }
532e5dd7070Spatrick 
getASTMutationListener() const533e5dd7070Spatrick ASTMutationListener *Sema::getASTMutationListener() const {
534e5dd7070Spatrick   return getASTConsumer().GetASTMutationListener();
535e5dd7070Spatrick }
536e5dd7070Spatrick 
537e5dd7070Spatrick ///Registers an external source. If an external source already exists,
538e5dd7070Spatrick /// creates a multiplex external source and appends to it.
539e5dd7070Spatrick ///
540e5dd7070Spatrick ///\param[in] E - A non-null external sema source.
541e5dd7070Spatrick ///
addExternalSource(ExternalSemaSource * E)542e5dd7070Spatrick void Sema::addExternalSource(ExternalSemaSource *E) {
543e5dd7070Spatrick   assert(E && "Cannot use with NULL ptr");
544e5dd7070Spatrick 
545e5dd7070Spatrick   if (!ExternalSource) {
546e5dd7070Spatrick     ExternalSource = E;
547e5dd7070Spatrick     return;
548e5dd7070Spatrick   }
549e5dd7070Spatrick 
550*12c85518Srobert   if (auto *Ex = dyn_cast<MultiplexExternalSemaSource>(ExternalSource))
551*12c85518Srobert     Ex->AddSource(E);
552*12c85518Srobert   else
553*12c85518Srobert     ExternalSource = new MultiplexExternalSemaSource(ExternalSource.get(), E);
554e5dd7070Spatrick }
555e5dd7070Spatrick 
556e5dd7070Spatrick /// Print out statistics about the semantic analysis.
PrintStats() const557e5dd7070Spatrick void Sema::PrintStats() const {
558e5dd7070Spatrick   llvm::errs() << "\n*** Semantic Analysis Stats:\n";
559e5dd7070Spatrick   llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
560e5dd7070Spatrick 
561e5dd7070Spatrick   BumpAlloc.PrintStats();
562e5dd7070Spatrick   AnalysisWarnings.PrintStats();
563e5dd7070Spatrick }
564e5dd7070Spatrick 
diagnoseNullableToNonnullConversion(QualType DstType,QualType SrcType,SourceLocation Loc)565e5dd7070Spatrick void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
566e5dd7070Spatrick                                                QualType SrcType,
567e5dd7070Spatrick                                                SourceLocation Loc) {
568*12c85518Srobert   std::optional<NullabilityKind> ExprNullability = SrcType->getNullability();
569a9ac8606Spatrick   if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable &&
570a9ac8606Spatrick                            *ExprNullability != NullabilityKind::NullableResult))
571e5dd7070Spatrick     return;
572e5dd7070Spatrick 
573*12c85518Srobert   std::optional<NullabilityKind> TypeNullability = DstType->getNullability();
574e5dd7070Spatrick   if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
575e5dd7070Spatrick     return;
576e5dd7070Spatrick 
577e5dd7070Spatrick   Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
578e5dd7070Spatrick }
579e5dd7070Spatrick 
diagnoseZeroToNullptrConversion(CastKind Kind,const Expr * E)580e5dd7070Spatrick void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E) {
581e5dd7070Spatrick   // nullptr only exists from C++11 on, so don't warn on its absence earlier.
582e5dd7070Spatrick   if (!getLangOpts().CPlusPlus11)
583e5dd7070Spatrick     return;
584e5dd7070Spatrick 
585e5dd7070Spatrick   if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
586e5dd7070Spatrick     return;
587e5dd7070Spatrick   if (E->IgnoreParenImpCasts()->getType()->isNullPtrType())
588e5dd7070Spatrick     return;
589e5dd7070Spatrick 
590*12c85518Srobert   if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
591*12c85518Srobert                       E->getBeginLoc()))
592*12c85518Srobert     return;
593*12c85518Srobert 
594a9ac8606Spatrick   // Don't diagnose the conversion from a 0 literal to a null pointer argument
595a9ac8606Spatrick   // in a synthesized call to operator<=>.
596a9ac8606Spatrick   if (!CodeSynthesisContexts.empty() &&
597a9ac8606Spatrick       CodeSynthesisContexts.back().Kind ==
598a9ac8606Spatrick           CodeSynthesisContext::RewritingOperatorAsSpaceship)
599a9ac8606Spatrick     return;
600a9ac8606Spatrick 
601*12c85518Srobert   // Ignore null pointers in defaulted comparison operators.
602*12c85518Srobert   FunctionDecl *FD = getCurFunctionDecl();
603*12c85518Srobert   if (FD && FD->isDefaulted()) {
604*12c85518Srobert     return;
605*12c85518Srobert   }
606*12c85518Srobert 
607e5dd7070Spatrick   // If it is a macro from system header, and if the macro name is not "NULL",
608e5dd7070Spatrick   // do not warn.
609e5dd7070Spatrick   SourceLocation MaybeMacroLoc = E->getBeginLoc();
610e5dd7070Spatrick   if (Diags.getSuppressSystemWarnings() &&
611e5dd7070Spatrick       SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
612e5dd7070Spatrick       !findMacroSpelling(MaybeMacroLoc, "NULL"))
613e5dd7070Spatrick     return;
614e5dd7070Spatrick 
615e5dd7070Spatrick   Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
616e5dd7070Spatrick       << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
617e5dd7070Spatrick }
618e5dd7070Spatrick 
619e5dd7070Spatrick /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
620e5dd7070Spatrick /// If there is already an implicit cast, merge into the existing one.
621e5dd7070Spatrick /// The result is of the given category.
ImpCastExprToType(Expr * E,QualType Ty,CastKind Kind,ExprValueKind VK,const CXXCastPath * BasePath,CheckedConversionKind CCK)622e5dd7070Spatrick ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
623e5dd7070Spatrick                                    CastKind Kind, ExprValueKind VK,
624e5dd7070Spatrick                                    const CXXCastPath *BasePath,
625e5dd7070Spatrick                                    CheckedConversionKind CCK) {
626e5dd7070Spatrick #ifndef NDEBUG
627a9ac8606Spatrick   if (VK == VK_PRValue && !E->isPRValue()) {
628e5dd7070Spatrick     switch (Kind) {
629e5dd7070Spatrick     default:
630a9ac8606Spatrick       llvm_unreachable(
631a9ac8606Spatrick           ("can't implicitly cast glvalue to prvalue with this cast "
632a9ac8606Spatrick            "kind: " +
633a9ac8606Spatrick            std::string(CastExpr::getCastKindName(Kind)))
634a9ac8606Spatrick               .c_str());
635e5dd7070Spatrick     case CK_Dependent:
636e5dd7070Spatrick     case CK_LValueToRValue:
637e5dd7070Spatrick     case CK_ArrayToPointerDecay:
638e5dd7070Spatrick     case CK_FunctionToPointerDecay:
639e5dd7070Spatrick     case CK_ToVoid:
640e5dd7070Spatrick     case CK_NonAtomicToAtomic:
641e5dd7070Spatrick       break;
642e5dd7070Spatrick     }
643e5dd7070Spatrick   }
644a9ac8606Spatrick   assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) &&
645a9ac8606Spatrick          "can't cast prvalue to glvalue");
646e5dd7070Spatrick #endif
647e5dd7070Spatrick 
648e5dd7070Spatrick   diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc());
649e5dd7070Spatrick   diagnoseZeroToNullptrConversion(Kind, E);
650e5dd7070Spatrick 
651e5dd7070Spatrick   QualType ExprTy = Context.getCanonicalType(E->getType());
652e5dd7070Spatrick   QualType TypeTy = Context.getCanonicalType(Ty);
653e5dd7070Spatrick 
654e5dd7070Spatrick   if (ExprTy == TypeTy)
655e5dd7070Spatrick     return E;
656e5dd7070Spatrick 
657a9ac8606Spatrick   if (Kind == CK_ArrayToPointerDecay) {
658e5dd7070Spatrick     // C++1z [conv.array]: The temporary materialization conversion is applied.
659e5dd7070Spatrick     // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
660a9ac8606Spatrick     if (getLangOpts().CPlusPlus && E->isPRValue()) {
661e5dd7070Spatrick       // The temporary is an lvalue in C++98 and an xvalue otherwise.
662e5dd7070Spatrick       ExprResult Materialized = CreateMaterializeTemporaryExpr(
663e5dd7070Spatrick           E->getType(), E, !getLangOpts().CPlusPlus11);
664e5dd7070Spatrick       if (Materialized.isInvalid())
665e5dd7070Spatrick         return ExprError();
666e5dd7070Spatrick       E = Materialized.get();
667e5dd7070Spatrick     }
668a9ac8606Spatrick     // C17 6.7.1p6 footnote 124: The implementation can treat any register
669a9ac8606Spatrick     // declaration simply as an auto declaration. However, whether or not
670a9ac8606Spatrick     // addressable storage is actually used, the address of any part of an
671a9ac8606Spatrick     // object declared with storage-class specifier register cannot be
672a9ac8606Spatrick     // computed, either explicitly(by use of the unary & operator as discussed
673a9ac8606Spatrick     // in 6.5.3.2) or implicitly(by converting an array name to a pointer as
674a9ac8606Spatrick     // discussed in 6.3.2.1).Thus, the only operator that can be applied to an
675a9ac8606Spatrick     // array declared with storage-class specifier register is sizeof.
676a9ac8606Spatrick     if (VK == VK_PRValue && !getLangOpts().CPlusPlus && !E->isPRValue()) {
677a9ac8606Spatrick       if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
678a9ac8606Spatrick         if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
679a9ac8606Spatrick           if (VD->getStorageClass() == SC_Register) {
680a9ac8606Spatrick             Diag(E->getExprLoc(), diag::err_typecheck_address_of)
681a9ac8606Spatrick                 << /*register variable*/ 3 << E->getSourceRange();
682a9ac8606Spatrick             return ExprError();
683a9ac8606Spatrick           }
684a9ac8606Spatrick         }
685a9ac8606Spatrick       }
686a9ac8606Spatrick     }
687a9ac8606Spatrick   }
688e5dd7070Spatrick 
689e5dd7070Spatrick   if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
690e5dd7070Spatrick     if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
691e5dd7070Spatrick       ImpCast->setType(Ty);
692e5dd7070Spatrick       ImpCast->setValueKind(VK);
693e5dd7070Spatrick       return E;
694e5dd7070Spatrick     }
695e5dd7070Spatrick   }
696e5dd7070Spatrick 
697a9ac8606Spatrick   return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
698a9ac8606Spatrick                                   CurFPFeatureOverrides());
699e5dd7070Spatrick }
700e5dd7070Spatrick 
701e5dd7070Spatrick /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
702e5dd7070Spatrick /// to the conversion from scalar type ScalarTy to the Boolean type.
ScalarTypeToBooleanCastKind(QualType ScalarTy)703e5dd7070Spatrick CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
704e5dd7070Spatrick   switch (ScalarTy->getScalarTypeKind()) {
705e5dd7070Spatrick   case Type::STK_Bool: return CK_NoOp;
706e5dd7070Spatrick   case Type::STK_CPointer: return CK_PointerToBoolean;
707e5dd7070Spatrick   case Type::STK_BlockPointer: return CK_PointerToBoolean;
708e5dd7070Spatrick   case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
709e5dd7070Spatrick   case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
710e5dd7070Spatrick   case Type::STK_Integral: return CK_IntegralToBoolean;
711e5dd7070Spatrick   case Type::STK_Floating: return CK_FloatingToBoolean;
712e5dd7070Spatrick   case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
713e5dd7070Spatrick   case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
714e5dd7070Spatrick   case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
715e5dd7070Spatrick   }
716e5dd7070Spatrick   llvm_unreachable("unknown scalar type kind");
717e5dd7070Spatrick }
718e5dd7070Spatrick 
719e5dd7070Spatrick /// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
ShouldRemoveFromUnused(Sema * SemaRef,const DeclaratorDecl * D)720e5dd7070Spatrick static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
721e5dd7070Spatrick   if (D->getMostRecentDecl()->isUsed())
722e5dd7070Spatrick     return true;
723e5dd7070Spatrick 
724e5dd7070Spatrick   if (D->isExternallyVisible())
725e5dd7070Spatrick     return true;
726e5dd7070Spatrick 
727e5dd7070Spatrick   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
728e5dd7070Spatrick     // If this is a function template and none of its specializations is used,
729e5dd7070Spatrick     // we should warn.
730e5dd7070Spatrick     if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
731e5dd7070Spatrick       for (const auto *Spec : Template->specializations())
732e5dd7070Spatrick         if (ShouldRemoveFromUnused(SemaRef, Spec))
733e5dd7070Spatrick           return true;
734e5dd7070Spatrick 
735e5dd7070Spatrick     // UnusedFileScopedDecls stores the first declaration.
736e5dd7070Spatrick     // The declaration may have become definition so check again.
737e5dd7070Spatrick     const FunctionDecl *DeclToCheck;
738e5dd7070Spatrick     if (FD->hasBody(DeclToCheck))
739e5dd7070Spatrick       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
740e5dd7070Spatrick 
741e5dd7070Spatrick     // Later redecls may add new information resulting in not having to warn,
742e5dd7070Spatrick     // so check again.
743e5dd7070Spatrick     DeclToCheck = FD->getMostRecentDecl();
744e5dd7070Spatrick     if (DeclToCheck != FD)
745e5dd7070Spatrick       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
746e5dd7070Spatrick   }
747e5dd7070Spatrick 
748e5dd7070Spatrick   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
749e5dd7070Spatrick     // If a variable usable in constant expressions is referenced,
750e5dd7070Spatrick     // don't warn if it isn't used: if the value of a variable is required
751e5dd7070Spatrick     // for the computation of a constant expression, it doesn't make sense to
752e5dd7070Spatrick     // warn even if the variable isn't odr-used.  (isReferenced doesn't
753e5dd7070Spatrick     // precisely reflect that, but it's a decent approximation.)
754e5dd7070Spatrick     if (VD->isReferenced() &&
755e5dd7070Spatrick         VD->mightBeUsableInConstantExpressions(SemaRef->Context))
756e5dd7070Spatrick       return true;
757e5dd7070Spatrick 
758e5dd7070Spatrick     if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
759e5dd7070Spatrick       // If this is a variable template and none of its specializations is used,
760e5dd7070Spatrick       // we should warn.
761e5dd7070Spatrick       for (const auto *Spec : Template->specializations())
762e5dd7070Spatrick         if (ShouldRemoveFromUnused(SemaRef, Spec))
763e5dd7070Spatrick           return true;
764e5dd7070Spatrick 
765e5dd7070Spatrick     // UnusedFileScopedDecls stores the first declaration.
766e5dd7070Spatrick     // The declaration may have become definition so check again.
767e5dd7070Spatrick     const VarDecl *DeclToCheck = VD->getDefinition();
768e5dd7070Spatrick     if (DeclToCheck)
769e5dd7070Spatrick       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
770e5dd7070Spatrick 
771e5dd7070Spatrick     // Later redecls may add new information resulting in not having to warn,
772e5dd7070Spatrick     // so check again.
773e5dd7070Spatrick     DeclToCheck = VD->getMostRecentDecl();
774e5dd7070Spatrick     if (DeclToCheck != VD)
775e5dd7070Spatrick       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
776e5dd7070Spatrick   }
777e5dd7070Spatrick 
778e5dd7070Spatrick   return false;
779e5dd7070Spatrick }
780e5dd7070Spatrick 
isFunctionOrVarDeclExternC(NamedDecl * ND)781e5dd7070Spatrick static bool isFunctionOrVarDeclExternC(NamedDecl *ND) {
782e5dd7070Spatrick   if (auto *FD = dyn_cast<FunctionDecl>(ND))
783e5dd7070Spatrick     return FD->isExternC();
784e5dd7070Spatrick   return cast<VarDecl>(ND)->isExternC();
785e5dd7070Spatrick }
786e5dd7070Spatrick 
787e5dd7070Spatrick /// Determine whether ND is an external-linkage function or variable whose
788e5dd7070Spatrick /// type has no linkage.
isExternalWithNoLinkageType(ValueDecl * VD)789e5dd7070Spatrick bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) {
790e5dd7070Spatrick   // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
791e5dd7070Spatrick   // because we also want to catch the case where its type has VisibleNoLinkage,
792e5dd7070Spatrick   // which does not affect the linkage of VD.
793e5dd7070Spatrick   return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
794e5dd7070Spatrick          !isExternalFormalLinkage(VD->getType()->getLinkage()) &&
795e5dd7070Spatrick          !isFunctionOrVarDeclExternC(VD);
796e5dd7070Spatrick }
797e5dd7070Spatrick 
798e5dd7070Spatrick /// Obtains a sorted list of functions and variables that are undefined but
799e5dd7070Spatrick /// ODR-used.
getUndefinedButUsed(SmallVectorImpl<std::pair<NamedDecl *,SourceLocation>> & Undefined)800e5dd7070Spatrick void Sema::getUndefinedButUsed(
801e5dd7070Spatrick     SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
802e5dd7070Spatrick   for (const auto &UndefinedUse : UndefinedButUsed) {
803e5dd7070Spatrick     NamedDecl *ND = UndefinedUse.first;
804e5dd7070Spatrick 
805e5dd7070Spatrick     // Ignore attributes that have become invalid.
806e5dd7070Spatrick     if (ND->isInvalidDecl()) continue;
807e5dd7070Spatrick 
808e5dd7070Spatrick     // __attribute__((weakref)) is basically a definition.
809e5dd7070Spatrick     if (ND->hasAttr<WeakRefAttr>()) continue;
810e5dd7070Spatrick 
811e5dd7070Spatrick     if (isa<CXXDeductionGuideDecl>(ND))
812e5dd7070Spatrick       continue;
813e5dd7070Spatrick 
814e5dd7070Spatrick     if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
815e5dd7070Spatrick       // An exported function will always be emitted when defined, so even if
816e5dd7070Spatrick       // the function is inline, it doesn't have to be emitted in this TU. An
817e5dd7070Spatrick       // imported function implies that it has been exported somewhere else.
818e5dd7070Spatrick       continue;
819e5dd7070Spatrick     }
820e5dd7070Spatrick 
821e5dd7070Spatrick     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
822e5dd7070Spatrick       if (FD->isDefined())
823e5dd7070Spatrick         continue;
824e5dd7070Spatrick       if (FD->isExternallyVisible() &&
825e5dd7070Spatrick           !isExternalWithNoLinkageType(FD) &&
826e5dd7070Spatrick           !FD->getMostRecentDecl()->isInlined() &&
827e5dd7070Spatrick           !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
828e5dd7070Spatrick         continue;
829e5dd7070Spatrick       if (FD->getBuiltinID())
830e5dd7070Spatrick         continue;
831e5dd7070Spatrick     } else {
832e5dd7070Spatrick       auto *VD = cast<VarDecl>(ND);
833e5dd7070Spatrick       if (VD->hasDefinition() != VarDecl::DeclarationOnly)
834e5dd7070Spatrick         continue;
835e5dd7070Spatrick       if (VD->isExternallyVisible() &&
836e5dd7070Spatrick           !isExternalWithNoLinkageType(VD) &&
837e5dd7070Spatrick           !VD->getMostRecentDecl()->isInline() &&
838e5dd7070Spatrick           !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
839e5dd7070Spatrick         continue;
840e5dd7070Spatrick 
841e5dd7070Spatrick       // Skip VarDecls that lack formal definitions but which we know are in
842e5dd7070Spatrick       // fact defined somewhere.
843e5dd7070Spatrick       if (VD->isKnownToBeDefined())
844e5dd7070Spatrick         continue;
845e5dd7070Spatrick     }
846e5dd7070Spatrick 
847e5dd7070Spatrick     Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
848e5dd7070Spatrick   }
849e5dd7070Spatrick }
850e5dd7070Spatrick 
851e5dd7070Spatrick /// checkUndefinedButUsed - Check for undefined objects with internal linkage
852e5dd7070Spatrick /// or that are inline.
checkUndefinedButUsed(Sema & S)853e5dd7070Spatrick static void checkUndefinedButUsed(Sema &S) {
854e5dd7070Spatrick   if (S.UndefinedButUsed.empty()) return;
855e5dd7070Spatrick 
856e5dd7070Spatrick   // Collect all the still-undefined entities with internal linkage.
857e5dd7070Spatrick   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
858e5dd7070Spatrick   S.getUndefinedButUsed(Undefined);
859e5dd7070Spatrick   if (Undefined.empty()) return;
860e5dd7070Spatrick 
861e5dd7070Spatrick   for (auto Undef : Undefined) {
862e5dd7070Spatrick     ValueDecl *VD = cast<ValueDecl>(Undef.first);
863e5dd7070Spatrick     SourceLocation UseLoc = Undef.second;
864e5dd7070Spatrick 
865e5dd7070Spatrick     if (S.isExternalWithNoLinkageType(VD)) {
866e5dd7070Spatrick       // C++ [basic.link]p8:
867e5dd7070Spatrick       //   A type without linkage shall not be used as the type of a variable
868e5dd7070Spatrick       //   or function with external linkage unless
869e5dd7070Spatrick       //    -- the entity has C language linkage
870e5dd7070Spatrick       //    -- the entity is not odr-used or is defined in the same TU
871e5dd7070Spatrick       //
872e5dd7070Spatrick       // As an extension, accept this in cases where the type is externally
873e5dd7070Spatrick       // visible, since the function or variable actually can be defined in
874e5dd7070Spatrick       // another translation unit in that case.
875e5dd7070Spatrick       S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
876e5dd7070Spatrick                                     ? diag::ext_undefined_internal_type
877e5dd7070Spatrick                                     : diag::err_undefined_internal_type)
878e5dd7070Spatrick         << isa<VarDecl>(VD) << VD;
879e5dd7070Spatrick     } else if (!VD->isExternallyVisible()) {
880e5dd7070Spatrick       // FIXME: We can promote this to an error. The function or variable can't
881e5dd7070Spatrick       // be defined anywhere else, so the program must necessarily violate the
882e5dd7070Spatrick       // one definition rule.
883a9ac8606Spatrick       bool IsImplicitBase = false;
884a9ac8606Spatrick       if (const auto *BaseD = dyn_cast<FunctionDecl>(VD)) {
885a9ac8606Spatrick         auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();
886a9ac8606Spatrick         if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
887a9ac8606Spatrick                           llvm::omp::TraitProperty::
888a9ac8606Spatrick                               implementation_extension_disable_implicit_base)) {
889a9ac8606Spatrick           const auto *Func = cast<FunctionDecl>(
890a9ac8606Spatrick               cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl());
891a9ac8606Spatrick           IsImplicitBase = BaseD->isImplicit() &&
892a9ac8606Spatrick                            Func->getIdentifier()->isMangledOpenMPVariantName();
893a9ac8606Spatrick         }
894a9ac8606Spatrick       }
895a9ac8606Spatrick       if (!S.getLangOpts().OpenMP || !IsImplicitBase)
896e5dd7070Spatrick         S.Diag(VD->getLocation(), diag::warn_undefined_internal)
897e5dd7070Spatrick             << isa<VarDecl>(VD) << VD;
898e5dd7070Spatrick     } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
899e5dd7070Spatrick       (void)FD;
900e5dd7070Spatrick       assert(FD->getMostRecentDecl()->isInlined() &&
901e5dd7070Spatrick              "used object requires definition but isn't inline or internal?");
902e5dd7070Spatrick       // FIXME: This is ill-formed; we should reject.
903e5dd7070Spatrick       S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
904e5dd7070Spatrick     } else {
905e5dd7070Spatrick       assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
906e5dd7070Spatrick              "used var requires definition but isn't inline or internal?");
907e5dd7070Spatrick       S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
908e5dd7070Spatrick     }
909e5dd7070Spatrick     if (UseLoc.isValid())
910e5dd7070Spatrick       S.Diag(UseLoc, diag::note_used_here);
911e5dd7070Spatrick   }
912e5dd7070Spatrick 
913e5dd7070Spatrick   S.UndefinedButUsed.clear();
914e5dd7070Spatrick }
915e5dd7070Spatrick 
LoadExternalWeakUndeclaredIdentifiers()916e5dd7070Spatrick void Sema::LoadExternalWeakUndeclaredIdentifiers() {
917e5dd7070Spatrick   if (!ExternalSource)
918e5dd7070Spatrick     return;
919e5dd7070Spatrick 
920e5dd7070Spatrick   SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
921e5dd7070Spatrick   ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
922e5dd7070Spatrick   for (auto &WeakID : WeakIDs)
923*12c85518Srobert     (void)WeakUndeclaredIdentifiers[WeakID.first].insert(WeakID.second);
924e5dd7070Spatrick }
925e5dd7070Spatrick 
926e5dd7070Spatrick 
927e5dd7070Spatrick typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
928e5dd7070Spatrick 
929e5dd7070Spatrick /// Returns true, if all methods and nested classes of the given
930e5dd7070Spatrick /// CXXRecordDecl are defined in this translation unit.
931e5dd7070Spatrick ///
932e5dd7070Spatrick /// Should only be called from ActOnEndOfTranslationUnit so that all
933e5dd7070Spatrick /// definitions are actually read.
MethodsAndNestedClassesComplete(const CXXRecordDecl * RD,RecordCompleteMap & MNCComplete)934e5dd7070Spatrick static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
935e5dd7070Spatrick                                             RecordCompleteMap &MNCComplete) {
936e5dd7070Spatrick   RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
937e5dd7070Spatrick   if (Cache != MNCComplete.end())
938e5dd7070Spatrick     return Cache->second;
939e5dd7070Spatrick   if (!RD->isCompleteDefinition())
940e5dd7070Spatrick     return false;
941e5dd7070Spatrick   bool Complete = true;
942e5dd7070Spatrick   for (DeclContext::decl_iterator I = RD->decls_begin(),
943e5dd7070Spatrick                                   E = RD->decls_end();
944e5dd7070Spatrick        I != E && Complete; ++I) {
945e5dd7070Spatrick     if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
946e5dd7070Spatrick       Complete = M->isDefined() || M->isDefaulted() ||
947e5dd7070Spatrick                  (M->isPure() && !isa<CXXDestructorDecl>(M));
948e5dd7070Spatrick     else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
949e5dd7070Spatrick       // If the template function is marked as late template parsed at this
950e5dd7070Spatrick       // point, it has not been instantiated and therefore we have not
951e5dd7070Spatrick       // performed semantic analysis on it yet, so we cannot know if the type
952e5dd7070Spatrick       // can be considered complete.
953e5dd7070Spatrick       Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
954e5dd7070Spatrick                   F->getTemplatedDecl()->isDefined();
955e5dd7070Spatrick     else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
956e5dd7070Spatrick       if (R->isInjectedClassName())
957e5dd7070Spatrick         continue;
958e5dd7070Spatrick       if (R->hasDefinition())
959e5dd7070Spatrick         Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
960e5dd7070Spatrick                                                    MNCComplete);
961e5dd7070Spatrick       else
962e5dd7070Spatrick         Complete = false;
963e5dd7070Spatrick     }
964e5dd7070Spatrick   }
965e5dd7070Spatrick   MNCComplete[RD] = Complete;
966e5dd7070Spatrick   return Complete;
967e5dd7070Spatrick }
968e5dd7070Spatrick 
969e5dd7070Spatrick /// Returns true, if the given CXXRecordDecl is fully defined in this
970e5dd7070Spatrick /// translation unit, i.e. all methods are defined or pure virtual and all
971e5dd7070Spatrick /// friends, friend functions and nested classes are fully defined in this
972e5dd7070Spatrick /// translation unit.
973e5dd7070Spatrick ///
974e5dd7070Spatrick /// Should only be called from ActOnEndOfTranslationUnit so that all
975e5dd7070Spatrick /// definitions are actually read.
IsRecordFullyDefined(const CXXRecordDecl * RD,RecordCompleteMap & RecordsComplete,RecordCompleteMap & MNCComplete)976e5dd7070Spatrick static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
977e5dd7070Spatrick                                  RecordCompleteMap &RecordsComplete,
978e5dd7070Spatrick                                  RecordCompleteMap &MNCComplete) {
979e5dd7070Spatrick   RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
980e5dd7070Spatrick   if (Cache != RecordsComplete.end())
981e5dd7070Spatrick     return Cache->second;
982e5dd7070Spatrick   bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
983e5dd7070Spatrick   for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
984e5dd7070Spatrick                                       E = RD->friend_end();
985e5dd7070Spatrick        I != E && Complete; ++I) {
986e5dd7070Spatrick     // Check if friend classes and methods are complete.
987e5dd7070Spatrick     if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
988e5dd7070Spatrick       // Friend classes are available as the TypeSourceInfo of the FriendDecl.
989e5dd7070Spatrick       if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
990e5dd7070Spatrick         Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
991e5dd7070Spatrick       else
992e5dd7070Spatrick         Complete = false;
993e5dd7070Spatrick     } else {
994e5dd7070Spatrick       // Friend functions are available through the NamedDecl of FriendDecl.
995e5dd7070Spatrick       if (const FunctionDecl *FD =
996e5dd7070Spatrick           dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
997e5dd7070Spatrick         Complete = FD->isDefined();
998e5dd7070Spatrick       else
999e5dd7070Spatrick         // This is a template friend, give up.
1000e5dd7070Spatrick         Complete = false;
1001e5dd7070Spatrick     }
1002e5dd7070Spatrick   }
1003e5dd7070Spatrick   RecordsComplete[RD] = Complete;
1004e5dd7070Spatrick   return Complete;
1005e5dd7070Spatrick }
1006e5dd7070Spatrick 
emitAndClearUnusedLocalTypedefWarnings()1007e5dd7070Spatrick void Sema::emitAndClearUnusedLocalTypedefWarnings() {
1008e5dd7070Spatrick   if (ExternalSource)
1009e5dd7070Spatrick     ExternalSource->ReadUnusedLocalTypedefNameCandidates(
1010e5dd7070Spatrick         UnusedLocalTypedefNameCandidates);
1011e5dd7070Spatrick   for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
1012e5dd7070Spatrick     if (TD->isReferenced())
1013e5dd7070Spatrick       continue;
1014e5dd7070Spatrick     Diag(TD->getLocation(), diag::warn_unused_local_typedef)
1015e5dd7070Spatrick         << isa<TypeAliasDecl>(TD) << TD->getDeclName();
1016e5dd7070Spatrick   }
1017e5dd7070Spatrick   UnusedLocalTypedefNameCandidates.clear();
1018e5dd7070Spatrick }
1019e5dd7070Spatrick 
1020e5dd7070Spatrick /// This is called before the very first declaration in the translation unit
1021e5dd7070Spatrick /// is parsed. Note that the ASTContext may have already injected some
1022e5dd7070Spatrick /// declarations.
ActOnStartOfTranslationUnit()1023e5dd7070Spatrick void Sema::ActOnStartOfTranslationUnit() {
1024*12c85518Srobert   if (getLangOpts().CPlusPlusModules &&
1025*12c85518Srobert       getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit)
1026*12c85518Srobert     HandleStartOfHeaderUnit();
1027*12c85518Srobert   else if (getLangOpts().ModulesTS &&
1028*12c85518Srobert            (getLangOpts().getCompilingModule() ==
1029*12c85518Srobert                 LangOptions::CMK_ModuleInterface ||
1030e5dd7070Spatrick             getLangOpts().getCompilingModule() == LangOptions::CMK_None)) {
1031e5dd7070Spatrick     // We start in an implied global module fragment.
1032e5dd7070Spatrick     SourceLocation StartOfTU =
1033e5dd7070Spatrick         SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1034e5dd7070Spatrick     ActOnGlobalModuleFragmentDecl(StartOfTU);
1035e5dd7070Spatrick     ModuleScopes.back().ImplicitGlobalModuleFragment = true;
1036e5dd7070Spatrick   }
1037e5dd7070Spatrick }
1038e5dd7070Spatrick 
ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind)1039e5dd7070Spatrick void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {
1040e5dd7070Spatrick   // No explicit actions are required at the end of the global module fragment.
1041e5dd7070Spatrick   if (Kind == TUFragmentKind::Global)
1042e5dd7070Spatrick     return;
1043e5dd7070Spatrick 
1044e5dd7070Spatrick   // Transfer late parsed template instantiations over to the pending template
1045e5dd7070Spatrick   // instantiation list. During normal compilation, the late template parser
1046e5dd7070Spatrick   // will be installed and instantiating these templates will succeed.
1047e5dd7070Spatrick   //
1048e5dd7070Spatrick   // If we are building a TU prefix for serialization, it is also safe to
1049e5dd7070Spatrick   // transfer these over, even though they are not parsed. The end of the TU
1050e5dd7070Spatrick   // should be outside of any eager template instantiation scope, so when this
1051e5dd7070Spatrick   // AST is deserialized, these templates will not be parsed until the end of
1052e5dd7070Spatrick   // the combined TU.
1053e5dd7070Spatrick   PendingInstantiations.insert(PendingInstantiations.end(),
1054e5dd7070Spatrick                                LateParsedInstantiations.begin(),
1055e5dd7070Spatrick                                LateParsedInstantiations.end());
1056e5dd7070Spatrick   LateParsedInstantiations.clear();
1057e5dd7070Spatrick 
1058e5dd7070Spatrick   // If DefinedUsedVTables ends up marking any virtual member functions it
1059e5dd7070Spatrick   // might lead to more pending template instantiations, which we then need
1060e5dd7070Spatrick   // to instantiate.
1061e5dd7070Spatrick   DefineUsedVTables();
1062e5dd7070Spatrick 
1063e5dd7070Spatrick   // C++: Perform implicit template instantiations.
1064e5dd7070Spatrick   //
1065e5dd7070Spatrick   // FIXME: When we perform these implicit instantiations, we do not
1066e5dd7070Spatrick   // carefully keep track of the point of instantiation (C++ [temp.point]).
1067e5dd7070Spatrick   // This means that name lookup that occurs within the template
1068e5dd7070Spatrick   // instantiation will always happen at the end of the translation unit,
1069e5dd7070Spatrick   // so it will find some names that are not required to be found. This is
1070e5dd7070Spatrick   // valid, but we could do better by diagnosing if an instantiation uses a
1071e5dd7070Spatrick   // name that was not visible at its first point of instantiation.
1072e5dd7070Spatrick   if (ExternalSource) {
1073e5dd7070Spatrick     // Load pending instantiations from the external source.
1074e5dd7070Spatrick     SmallVector<PendingImplicitInstantiation, 4> Pending;
1075e5dd7070Spatrick     ExternalSource->ReadPendingInstantiations(Pending);
1076e5dd7070Spatrick     for (auto PII : Pending)
1077e5dd7070Spatrick       if (auto Func = dyn_cast<FunctionDecl>(PII.first))
1078e5dd7070Spatrick         Func->setInstantiationIsPending(true);
1079e5dd7070Spatrick     PendingInstantiations.insert(PendingInstantiations.begin(),
1080e5dd7070Spatrick                                  Pending.begin(), Pending.end());
1081e5dd7070Spatrick   }
1082e5dd7070Spatrick 
1083e5dd7070Spatrick   {
1084e5dd7070Spatrick     llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1085e5dd7070Spatrick     PerformPendingInstantiations();
1086e5dd7070Spatrick   }
1087e5dd7070Spatrick 
1088ec727ea7Spatrick   emitDeferredDiags();
1089e5dd7070Spatrick 
1090e5dd7070Spatrick   assert(LateParsedInstantiations.empty() &&
1091e5dd7070Spatrick          "end of TU template instantiation should not create more "
1092e5dd7070Spatrick          "late-parsed templates");
1093e5dd7070Spatrick 
1094e5dd7070Spatrick   // Report diagnostics for uncorrected delayed typos. Ideally all of them
1095e5dd7070Spatrick   // should have been corrected by that time, but it is very hard to cover all
1096e5dd7070Spatrick   // cases in practice.
1097e5dd7070Spatrick   for (const auto &Typo : DelayedTypos) {
1098e5dd7070Spatrick     // We pass an empty TypoCorrection to indicate no correction was performed.
1099e5dd7070Spatrick     Typo.second.DiagHandler(TypoCorrection());
1100e5dd7070Spatrick   }
1101e5dd7070Spatrick   DelayedTypos.clear();
1102e5dd7070Spatrick }
1103e5dd7070Spatrick 
1104e5dd7070Spatrick /// ActOnEndOfTranslationUnit - This is called at the very end of the
1105e5dd7070Spatrick /// translation unit when EOF is reached and all but the top-level scope is
1106e5dd7070Spatrick /// popped.
ActOnEndOfTranslationUnit()1107e5dd7070Spatrick void Sema::ActOnEndOfTranslationUnit() {
1108e5dd7070Spatrick   assert(DelayedDiagnostics.getCurrentPool() == nullptr
1109e5dd7070Spatrick          && "reached end of translation unit with a pool attached?");
1110e5dd7070Spatrick 
1111e5dd7070Spatrick   // If code completion is enabled, don't perform any end-of-translation-unit
1112e5dd7070Spatrick   // work.
1113e5dd7070Spatrick   if (PP.isCodeCompletionEnabled())
1114e5dd7070Spatrick     return;
1115e5dd7070Spatrick 
1116e5dd7070Spatrick   // Complete translation units and modules define vtables and perform implicit
1117e5dd7070Spatrick   // instantiations. PCH files do not.
1118e5dd7070Spatrick   if (TUKind != TU_Prefix) {
1119e5dd7070Spatrick     DiagnoseUseOfUnimplementedSelectors();
1120e5dd7070Spatrick 
1121e5dd7070Spatrick     ActOnEndOfTranslationUnitFragment(
1122e5dd7070Spatrick         !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1123e5dd7070Spatrick                                      Module::PrivateModuleFragment
1124e5dd7070Spatrick             ? TUFragmentKind::Private
1125e5dd7070Spatrick             : TUFragmentKind::Normal);
1126e5dd7070Spatrick 
1127e5dd7070Spatrick     if (LateTemplateParserCleanup)
1128e5dd7070Spatrick       LateTemplateParserCleanup(OpaqueParser);
1129e5dd7070Spatrick 
1130e5dd7070Spatrick     CheckDelayedMemberExceptionSpecs();
1131e5dd7070Spatrick   } else {
1132e5dd7070Spatrick     // If we are building a TU prefix for serialization, it is safe to transfer
1133e5dd7070Spatrick     // these over, even though they are not parsed. The end of the TU should be
1134e5dd7070Spatrick     // outside of any eager template instantiation scope, so when this AST is
1135e5dd7070Spatrick     // deserialized, these templates will not be parsed until the end of the
1136e5dd7070Spatrick     // combined TU.
1137e5dd7070Spatrick     PendingInstantiations.insert(PendingInstantiations.end(),
1138e5dd7070Spatrick                                  LateParsedInstantiations.begin(),
1139e5dd7070Spatrick                                  LateParsedInstantiations.end());
1140e5dd7070Spatrick     LateParsedInstantiations.clear();
1141ec727ea7Spatrick 
1142ec727ea7Spatrick     if (LangOpts.PCHInstantiateTemplates) {
1143ec727ea7Spatrick       llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1144ec727ea7Spatrick       PerformPendingInstantiations();
1145ec727ea7Spatrick     }
1146e5dd7070Spatrick   }
1147e5dd7070Spatrick 
1148a9ac8606Spatrick   DiagnoseUnterminatedPragmaAlignPack();
1149e5dd7070Spatrick   DiagnoseUnterminatedPragmaAttribute();
1150*12c85518Srobert   DiagnoseUnterminatedOpenMPDeclareTarget();
1151e5dd7070Spatrick 
1152e5dd7070Spatrick   // All delayed member exception specs should be checked or we end up accepting
1153e5dd7070Spatrick   // incompatible declarations.
1154e5dd7070Spatrick   assert(DelayedOverridingExceptionSpecChecks.empty());
1155e5dd7070Spatrick   assert(DelayedEquivalentExceptionSpecChecks.empty());
1156e5dd7070Spatrick 
1157e5dd7070Spatrick   // All dllexport classes should have been processed already.
1158e5dd7070Spatrick   assert(DelayedDllExportClasses.empty());
1159e5dd7070Spatrick   assert(DelayedDllExportMemberFunctions.empty());
1160e5dd7070Spatrick 
1161e5dd7070Spatrick   // Remove file scoped decls that turned out to be used.
1162e5dd7070Spatrick   UnusedFileScopedDecls.erase(
1163e5dd7070Spatrick       std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
1164e5dd7070Spatrick                      UnusedFileScopedDecls.end(),
1165e5dd7070Spatrick                      [this](const DeclaratorDecl *DD) {
1166e5dd7070Spatrick                        return ShouldRemoveFromUnused(this, DD);
1167e5dd7070Spatrick                      }),
1168e5dd7070Spatrick       UnusedFileScopedDecls.end());
1169e5dd7070Spatrick 
1170e5dd7070Spatrick   if (TUKind == TU_Prefix) {
1171e5dd7070Spatrick     // Translation unit prefixes don't need any of the checking below.
1172e5dd7070Spatrick     if (!PP.isIncrementalProcessingEnabled())
1173e5dd7070Spatrick       TUScope = nullptr;
1174e5dd7070Spatrick     return;
1175e5dd7070Spatrick   }
1176e5dd7070Spatrick 
1177e5dd7070Spatrick   // Check for #pragma weak identifiers that were never declared
1178e5dd7070Spatrick   LoadExternalWeakUndeclaredIdentifiers();
1179*12c85518Srobert   for (const auto &WeakIDs : WeakUndeclaredIdentifiers) {
1180*12c85518Srobert     if (WeakIDs.second.empty())
1181e5dd7070Spatrick       continue;
1182e5dd7070Spatrick 
1183*12c85518Srobert     Decl *PrevDecl = LookupSingleName(TUScope, WeakIDs.first, SourceLocation(),
1184e5dd7070Spatrick                                       LookupOrdinaryName);
1185e5dd7070Spatrick     if (PrevDecl != nullptr &&
1186e5dd7070Spatrick         !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
1187*12c85518Srobert       for (const auto &WI : WeakIDs.second)
1188*12c85518Srobert         Diag(WI.getLocation(), diag::warn_attribute_wrong_decl_type)
1189e5dd7070Spatrick             << "'weak'" << ExpectedVariableOrFunction;
1190e5dd7070Spatrick     else
1191*12c85518Srobert       for (const auto &WI : WeakIDs.second)
1192*12c85518Srobert         Diag(WI.getLocation(), diag::warn_weak_identifier_undeclared)
1193*12c85518Srobert             << WeakIDs.first;
1194e5dd7070Spatrick   }
1195e5dd7070Spatrick 
1196e5dd7070Spatrick   if (LangOpts.CPlusPlus11 &&
1197e5dd7070Spatrick       !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
1198e5dd7070Spatrick     CheckDelegatingCtorCycles();
1199e5dd7070Spatrick 
1200e5dd7070Spatrick   if (!Diags.hasErrorOccurred()) {
1201e5dd7070Spatrick     if (ExternalSource)
1202e5dd7070Spatrick       ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
1203e5dd7070Spatrick     checkUndefinedButUsed(*this);
1204e5dd7070Spatrick   }
1205e5dd7070Spatrick 
1206e5dd7070Spatrick   // A global-module-fragment is only permitted within a module unit.
1207e5dd7070Spatrick   bool DiagnosedMissingModuleDeclaration = false;
1208e5dd7070Spatrick   if (!ModuleScopes.empty() &&
1209e5dd7070Spatrick       ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment &&
1210e5dd7070Spatrick       !ModuleScopes.back().ImplicitGlobalModuleFragment) {
1211e5dd7070Spatrick     Diag(ModuleScopes.back().BeginLoc,
1212e5dd7070Spatrick          diag::err_module_declaration_missing_after_global_module_introducer);
1213e5dd7070Spatrick     DiagnosedMissingModuleDeclaration = true;
1214e5dd7070Spatrick   }
1215e5dd7070Spatrick 
1216e5dd7070Spatrick   if (TUKind == TU_Module) {
1217e5dd7070Spatrick     // If we are building a module interface unit, we need to have seen the
1218e5dd7070Spatrick     // module declaration by now.
1219e5dd7070Spatrick     if (getLangOpts().getCompilingModule() ==
1220e5dd7070Spatrick             LangOptions::CMK_ModuleInterface &&
1221*12c85518Srobert         !isCurrentModulePurview() && !DiagnosedMissingModuleDeclaration) {
1222e5dd7070Spatrick       // FIXME: Make a better guess as to where to put the module declaration.
1223e5dd7070Spatrick       Diag(getSourceManager().getLocForStartOfFile(
1224e5dd7070Spatrick                getSourceManager().getMainFileID()),
1225e5dd7070Spatrick            diag::err_module_declaration_missing);
1226e5dd7070Spatrick     }
1227e5dd7070Spatrick 
1228e5dd7070Spatrick     // If we are building a module, resolve all of the exported declarations
1229e5dd7070Spatrick     // now.
1230e5dd7070Spatrick     if (Module *CurrentModule = PP.getCurrentModule()) {
1231e5dd7070Spatrick       ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
1232e5dd7070Spatrick 
1233e5dd7070Spatrick       SmallVector<Module *, 2> Stack;
1234e5dd7070Spatrick       Stack.push_back(CurrentModule);
1235e5dd7070Spatrick       while (!Stack.empty()) {
1236e5dd7070Spatrick         Module *Mod = Stack.pop_back_val();
1237e5dd7070Spatrick 
1238e5dd7070Spatrick         // Resolve the exported declarations and conflicts.
1239e5dd7070Spatrick         // FIXME: Actually complain, once we figure out how to teach the
1240e5dd7070Spatrick         // diagnostic client to deal with complaints in the module map at this
1241e5dd7070Spatrick         // point.
1242e5dd7070Spatrick         ModMap.resolveExports(Mod, /*Complain=*/false);
1243e5dd7070Spatrick         ModMap.resolveUses(Mod, /*Complain=*/false);
1244e5dd7070Spatrick         ModMap.resolveConflicts(Mod, /*Complain=*/false);
1245e5dd7070Spatrick 
1246e5dd7070Spatrick         // Queue the submodules, so their exports will also be resolved.
1247e5dd7070Spatrick         Stack.append(Mod->submodule_begin(), Mod->submodule_end());
1248e5dd7070Spatrick       }
1249e5dd7070Spatrick     }
1250e5dd7070Spatrick 
1251e5dd7070Spatrick     // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1252e5dd7070Spatrick     // modules when they are built, not every time they are used.
1253e5dd7070Spatrick     emitAndClearUnusedLocalTypedefWarnings();
1254e5dd7070Spatrick   }
1255e5dd7070Spatrick 
1256*12c85518Srobert   // C++ standard modules. Diagnose cases where a function is declared inline
1257*12c85518Srobert   // in the module purview but has no definition before the end of the TU or
1258*12c85518Srobert   // the start of a Private Module Fragment (if one is present).
1259*12c85518Srobert   if (!PendingInlineFuncDecls.empty()) {
1260*12c85518Srobert     for (auto *D : PendingInlineFuncDecls) {
1261*12c85518Srobert       if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1262*12c85518Srobert         bool DefInPMF = false;
1263*12c85518Srobert         if (auto *FDD = FD->getDefinition()) {
1264*12c85518Srobert           assert(FDD->getOwningModule() &&
1265*12c85518Srobert                  FDD->getOwningModule()->isModulePurview());
1266*12c85518Srobert           DefInPMF = FDD->getOwningModule()->isPrivateModule();
1267*12c85518Srobert           if (!DefInPMF)
1268*12c85518Srobert             continue;
1269*12c85518Srobert         }
1270*12c85518Srobert         Diag(FD->getLocation(), diag::err_export_inline_not_defined)
1271*12c85518Srobert             << DefInPMF;
1272*12c85518Srobert         // If we have a PMF it should be at the end of the ModuleScopes.
1273*12c85518Srobert         if (DefInPMF &&
1274*12c85518Srobert             ModuleScopes.back().Module->Kind == Module::PrivateModuleFragment) {
1275*12c85518Srobert           Diag(ModuleScopes.back().BeginLoc,
1276*12c85518Srobert                diag::note_private_module_fragment);
1277*12c85518Srobert         }
1278*12c85518Srobert       }
1279*12c85518Srobert     }
1280*12c85518Srobert     PendingInlineFuncDecls.clear();
1281*12c85518Srobert   }
1282*12c85518Srobert 
1283e5dd7070Spatrick   // C99 6.9.2p2:
1284e5dd7070Spatrick   //   A declaration of an identifier for an object that has file
1285e5dd7070Spatrick   //   scope without an initializer, and without a storage-class
1286e5dd7070Spatrick   //   specifier or with the storage-class specifier static,
1287e5dd7070Spatrick   //   constitutes a tentative definition. If a translation unit
1288e5dd7070Spatrick   //   contains one or more tentative definitions for an identifier,
1289e5dd7070Spatrick   //   and the translation unit contains no external definition for
1290e5dd7070Spatrick   //   that identifier, then the behavior is exactly as if the
1291e5dd7070Spatrick   //   translation unit contains a file scope declaration of that
1292e5dd7070Spatrick   //   identifier, with the composite type as of the end of the
1293e5dd7070Spatrick   //   translation unit, with an initializer equal to 0.
1294e5dd7070Spatrick   llvm::SmallSet<VarDecl *, 32> Seen;
1295e5dd7070Spatrick   for (TentativeDefinitionsType::iterator
1296*12c85518Srobert            T = TentativeDefinitions.begin(ExternalSource.get()),
1297e5dd7070Spatrick            TEnd = TentativeDefinitions.end();
1298e5dd7070Spatrick        T != TEnd; ++T) {
1299e5dd7070Spatrick     VarDecl *VD = (*T)->getActingDefinition();
1300e5dd7070Spatrick 
1301e5dd7070Spatrick     // If the tentative definition was completed, getActingDefinition() returns
1302e5dd7070Spatrick     // null. If we've already seen this variable before, insert()'s second
1303e5dd7070Spatrick     // return value is false.
1304e5dd7070Spatrick     if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
1305e5dd7070Spatrick       continue;
1306e5dd7070Spatrick 
1307e5dd7070Spatrick     if (const IncompleteArrayType *ArrayT
1308e5dd7070Spatrick         = Context.getAsIncompleteArrayType(VD->getType())) {
1309e5dd7070Spatrick       // Set the length of the array to 1 (C99 6.9.2p5).
1310e5dd7070Spatrick       Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
1311e5dd7070Spatrick       llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
1312e5dd7070Spatrick       QualType T = Context.getConstantArrayType(ArrayT->getElementType(), One,
1313e5dd7070Spatrick                                                 nullptr, ArrayType::Normal, 0);
1314e5dd7070Spatrick       VD->setType(T);
1315e5dd7070Spatrick     } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
1316e5dd7070Spatrick                                    diag::err_tentative_def_incomplete_type))
1317e5dd7070Spatrick       VD->setInvalidDecl();
1318e5dd7070Spatrick 
1319e5dd7070Spatrick     // No initialization is performed for a tentative definition.
1320e5dd7070Spatrick     CheckCompleteVariableDeclaration(VD);
1321e5dd7070Spatrick 
1322e5dd7070Spatrick     // Notify the consumer that we've completed a tentative definition.
1323e5dd7070Spatrick     if (!VD->isInvalidDecl())
1324e5dd7070Spatrick       Consumer.CompleteTentativeDefinition(VD);
1325e5dd7070Spatrick   }
1326e5dd7070Spatrick 
1327*12c85518Srobert   for (auto *D : ExternalDeclarations) {
1328e5dd7070Spatrick     if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())
1329e5dd7070Spatrick       continue;
1330e5dd7070Spatrick 
1331e5dd7070Spatrick     Consumer.CompleteExternalDeclaration(D);
1332e5dd7070Spatrick   }
1333e5dd7070Spatrick 
1334e5dd7070Spatrick   // If there were errors, disable 'unused' warnings since they will mostly be
1335e5dd7070Spatrick   // noise. Don't warn for a use from a module: either we should warn on all
1336e5dd7070Spatrick   // file-scope declarations in modules or not at all, but whether the
1337e5dd7070Spatrick   // declaration is used is immaterial.
1338e5dd7070Spatrick   if (!Diags.hasErrorOccurred() && TUKind != TU_Module) {
1339e5dd7070Spatrick     // Output warning for unused file scoped decls.
1340e5dd7070Spatrick     for (UnusedFileScopedDeclsType::iterator
1341*12c85518Srobert              I = UnusedFileScopedDecls.begin(ExternalSource.get()),
1342*12c85518Srobert              E = UnusedFileScopedDecls.end();
1343*12c85518Srobert          I != E; ++I) {
1344e5dd7070Spatrick       if (ShouldRemoveFromUnused(this, *I))
1345e5dd7070Spatrick         continue;
1346e5dd7070Spatrick 
1347e5dd7070Spatrick       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1348e5dd7070Spatrick         const FunctionDecl *DiagD;
1349e5dd7070Spatrick         if (!FD->hasBody(DiagD))
1350e5dd7070Spatrick           DiagD = FD;
1351e5dd7070Spatrick         if (DiagD->isDeleted())
1352e5dd7070Spatrick           continue; // Deleted functions are supposed to be unused.
1353e5dd7070Spatrick         if (DiagD->isReferenced()) {
1354e5dd7070Spatrick           if (isa<CXXMethodDecl>(DiagD))
1355e5dd7070Spatrick             Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1356a9ac8606Spatrick                 << DiagD;
1357e5dd7070Spatrick           else {
1358e5dd7070Spatrick             if (FD->getStorageClass() == SC_Static &&
1359e5dd7070Spatrick                 !FD->isInlineSpecified() &&
1360e5dd7070Spatrick                 !SourceMgr.isInMainFile(
1361e5dd7070Spatrick                    SourceMgr.getExpansionLoc(FD->getLocation())))
1362e5dd7070Spatrick               Diag(DiagD->getLocation(),
1363e5dd7070Spatrick                    diag::warn_unneeded_static_internal_decl)
1364a9ac8606Spatrick                   << DiagD;
1365e5dd7070Spatrick             else
1366e5dd7070Spatrick               Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1367a9ac8606Spatrick                   << /*function*/ 0 << DiagD;
1368e5dd7070Spatrick           }
1369e5dd7070Spatrick         } else {
1370e5dd7070Spatrick           if (FD->getDescribedFunctionTemplate())
1371e5dd7070Spatrick             Diag(DiagD->getLocation(), diag::warn_unused_template)
1372a9ac8606Spatrick                 << /*function*/ 0 << DiagD;
1373e5dd7070Spatrick           else
1374a9ac8606Spatrick             Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)
1375a9ac8606Spatrick                                            ? diag::warn_unused_member_function
1376e5dd7070Spatrick                                            : diag::warn_unused_function)
1377a9ac8606Spatrick                 << DiagD;
1378e5dd7070Spatrick         }
1379e5dd7070Spatrick       } else {
1380e5dd7070Spatrick         const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
1381e5dd7070Spatrick         if (!DiagD)
1382e5dd7070Spatrick           DiagD = cast<VarDecl>(*I);
1383e5dd7070Spatrick         if (DiagD->isReferenced()) {
1384e5dd7070Spatrick           Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1385a9ac8606Spatrick               << /*variable*/ 1 << DiagD;
1386e5dd7070Spatrick         } else if (DiagD->getType().isConstQualified()) {
1387e5dd7070Spatrick           const SourceManager &SM = SourceMgr;
1388e5dd7070Spatrick           if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
1389e5dd7070Spatrick               !PP.getLangOpts().IsHeaderFile)
1390e5dd7070Spatrick             Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1391a9ac8606Spatrick                 << DiagD;
1392e5dd7070Spatrick         } else {
1393e5dd7070Spatrick           if (DiagD->getDescribedVarTemplate())
1394e5dd7070Spatrick             Diag(DiagD->getLocation(), diag::warn_unused_template)
1395a9ac8606Spatrick                 << /*variable*/ 1 << DiagD;
1396e5dd7070Spatrick           else
1397a9ac8606Spatrick             Diag(DiagD->getLocation(), diag::warn_unused_variable) << DiagD;
1398e5dd7070Spatrick         }
1399e5dd7070Spatrick       }
1400e5dd7070Spatrick     }
1401e5dd7070Spatrick 
1402e5dd7070Spatrick     emitAndClearUnusedLocalTypedefWarnings();
1403e5dd7070Spatrick   }
1404e5dd7070Spatrick 
1405e5dd7070Spatrick   if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
1406e5dd7070Spatrick     // FIXME: Load additional unused private field candidates from the external
1407e5dd7070Spatrick     // source.
1408e5dd7070Spatrick     RecordCompleteMap RecordsComplete;
1409e5dd7070Spatrick     RecordCompleteMap MNCComplete;
1410e5dd7070Spatrick     for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
1411e5dd7070Spatrick          E = UnusedPrivateFields.end(); I != E; ++I) {
1412e5dd7070Spatrick       const NamedDecl *D = *I;
1413e5dd7070Spatrick       const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1414e5dd7070Spatrick       if (RD && !RD->isUnion() &&
1415e5dd7070Spatrick           IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
1416e5dd7070Spatrick         Diag(D->getLocation(), diag::warn_unused_private_field)
1417e5dd7070Spatrick               << D->getDeclName();
1418e5dd7070Spatrick       }
1419e5dd7070Spatrick     }
1420e5dd7070Spatrick   }
1421e5dd7070Spatrick 
1422e5dd7070Spatrick   if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
1423e5dd7070Spatrick     if (ExternalSource)
1424e5dd7070Spatrick       ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1425e5dd7070Spatrick     for (const auto &DeletedFieldInfo : DeleteExprs) {
1426e5dd7070Spatrick       for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1427e5dd7070Spatrick         AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
1428e5dd7070Spatrick                                   DeleteExprLoc.second);
1429e5dd7070Spatrick       }
1430e5dd7070Spatrick     }
1431e5dd7070Spatrick   }
1432e5dd7070Spatrick 
1433e5dd7070Spatrick   // Check we've noticed that we're no longer parsing the initializer for every
1434e5dd7070Spatrick   // variable. If we miss cases, then at best we have a performance issue and
1435e5dd7070Spatrick   // at worst a rejects-valid bug.
1436e5dd7070Spatrick   assert(ParsingInitForAutoVars.empty() &&
1437e5dd7070Spatrick          "Didn't unmark var as having its initializer parsed");
1438e5dd7070Spatrick 
1439e5dd7070Spatrick   if (!PP.isIncrementalProcessingEnabled())
1440e5dd7070Spatrick     TUScope = nullptr;
1441e5dd7070Spatrick }
1442e5dd7070Spatrick 
1443e5dd7070Spatrick 
1444e5dd7070Spatrick //===----------------------------------------------------------------------===//
1445e5dd7070Spatrick // Helper functions.
1446e5dd7070Spatrick //===----------------------------------------------------------------------===//
1447e5dd7070Spatrick 
getFunctionLevelDeclContext(bool AllowLambda)1448*12c85518Srobert DeclContext *Sema::getFunctionLevelDeclContext(bool AllowLambda) {
1449e5dd7070Spatrick   DeclContext *DC = CurContext;
1450e5dd7070Spatrick 
1451e5dd7070Spatrick   while (true) {
1452e5dd7070Spatrick     if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) ||
1453e5dd7070Spatrick         isa<RequiresExprBodyDecl>(DC)) {
1454e5dd7070Spatrick       DC = DC->getParent();
1455*12c85518Srobert     } else if (!AllowLambda && isa<CXXMethodDecl>(DC) &&
1456e5dd7070Spatrick                cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
1457e5dd7070Spatrick                cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
1458e5dd7070Spatrick       DC = DC->getParent()->getParent();
1459*12c85518Srobert     } else break;
1460e5dd7070Spatrick   }
1461e5dd7070Spatrick 
1462e5dd7070Spatrick   return DC;
1463e5dd7070Spatrick }
1464e5dd7070Spatrick 
1465e5dd7070Spatrick /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1466e5dd7070Spatrick /// to the function decl for the function being parsed.  If we're currently
1467e5dd7070Spatrick /// in a 'block', this returns the containing context.
getCurFunctionDecl(bool AllowLambda)1468*12c85518Srobert FunctionDecl *Sema::getCurFunctionDecl(bool AllowLambda) {
1469*12c85518Srobert   DeclContext *DC = getFunctionLevelDeclContext(AllowLambda);
1470e5dd7070Spatrick   return dyn_cast<FunctionDecl>(DC);
1471e5dd7070Spatrick }
1472e5dd7070Spatrick 
getCurMethodDecl()1473e5dd7070Spatrick ObjCMethodDecl *Sema::getCurMethodDecl() {
1474e5dd7070Spatrick   DeclContext *DC = getFunctionLevelDeclContext();
1475e5dd7070Spatrick   while (isa<RecordDecl>(DC))
1476e5dd7070Spatrick     DC = DC->getParent();
1477e5dd7070Spatrick   return dyn_cast<ObjCMethodDecl>(DC);
1478e5dd7070Spatrick }
1479e5dd7070Spatrick 
getCurFunctionOrMethodDecl()1480e5dd7070Spatrick NamedDecl *Sema::getCurFunctionOrMethodDecl() {
1481e5dd7070Spatrick   DeclContext *DC = getFunctionLevelDeclContext();
1482e5dd7070Spatrick   if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
1483e5dd7070Spatrick     return cast<NamedDecl>(DC);
1484e5dd7070Spatrick   return nullptr;
1485e5dd7070Spatrick }
1486e5dd7070Spatrick 
getDefaultCXXMethodAddrSpace() const1487e5dd7070Spatrick LangAS Sema::getDefaultCXXMethodAddrSpace() const {
1488e5dd7070Spatrick   if (getLangOpts().OpenCL)
1489*12c85518Srobert     return getASTContext().getDefaultOpenCLPointeeAddrSpace();
1490e5dd7070Spatrick   return LangAS::Default;
1491e5dd7070Spatrick }
1492e5dd7070Spatrick 
EmitCurrentDiagnostic(unsigned DiagID)1493e5dd7070Spatrick void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1494e5dd7070Spatrick   // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1495e5dd7070Spatrick   // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1496e5dd7070Spatrick   // been made more painfully obvious by the refactor that introduced this
1497e5dd7070Spatrick   // function, but it is possible that the incoming argument can be
1498e5dd7070Spatrick   // eliminated. If it truly cannot be (for example, there is some reentrancy
1499e5dd7070Spatrick   // issue I am not seeing yet), then there should at least be a clarifying
1500e5dd7070Spatrick   // comment somewhere.
1501*12c85518Srobert   if (std::optional<TemplateDeductionInfo *> Info = isSFINAEContext()) {
1502e5dd7070Spatrick     switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
1503e5dd7070Spatrick               Diags.getCurrentDiagID())) {
1504e5dd7070Spatrick     case DiagnosticIDs::SFINAE_Report:
1505e5dd7070Spatrick       // We'll report the diagnostic below.
1506e5dd7070Spatrick       break;
1507e5dd7070Spatrick 
1508e5dd7070Spatrick     case DiagnosticIDs::SFINAE_SubstitutionFailure:
1509e5dd7070Spatrick       // Count this failure so that we know that template argument deduction
1510e5dd7070Spatrick       // has failed.
1511e5dd7070Spatrick       ++NumSFINAEErrors;
1512e5dd7070Spatrick 
1513e5dd7070Spatrick       // Make a copy of this suppressed diagnostic and store it with the
1514e5dd7070Spatrick       // template-deduction information.
1515e5dd7070Spatrick       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1516e5dd7070Spatrick         Diagnostic DiagInfo(&Diags);
1517e5dd7070Spatrick         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1518e5dd7070Spatrick                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1519e5dd7070Spatrick       }
1520e5dd7070Spatrick 
1521e5dd7070Spatrick       Diags.setLastDiagnosticIgnored(true);
1522e5dd7070Spatrick       Diags.Clear();
1523e5dd7070Spatrick       return;
1524e5dd7070Spatrick 
1525e5dd7070Spatrick     case DiagnosticIDs::SFINAE_AccessControl: {
1526e5dd7070Spatrick       // Per C++ Core Issue 1170, access control is part of SFINAE.
1527e5dd7070Spatrick       // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1528e5dd7070Spatrick       // make access control a part of SFINAE for the purposes of checking
1529e5dd7070Spatrick       // type traits.
1530e5dd7070Spatrick       if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
1531e5dd7070Spatrick         break;
1532e5dd7070Spatrick 
1533e5dd7070Spatrick       SourceLocation Loc = Diags.getCurrentDiagLoc();
1534e5dd7070Spatrick 
1535e5dd7070Spatrick       // Suppress this diagnostic.
1536e5dd7070Spatrick       ++NumSFINAEErrors;
1537e5dd7070Spatrick 
1538e5dd7070Spatrick       // Make a copy of this suppressed diagnostic and store it with the
1539e5dd7070Spatrick       // template-deduction information.
1540e5dd7070Spatrick       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1541e5dd7070Spatrick         Diagnostic DiagInfo(&Diags);
1542e5dd7070Spatrick         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1543e5dd7070Spatrick                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1544e5dd7070Spatrick       }
1545e5dd7070Spatrick 
1546e5dd7070Spatrick       Diags.setLastDiagnosticIgnored(true);
1547e5dd7070Spatrick       Diags.Clear();
1548e5dd7070Spatrick 
1549e5dd7070Spatrick       // Now the diagnostic state is clear, produce a C++98 compatibility
1550e5dd7070Spatrick       // warning.
1551e5dd7070Spatrick       Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1552e5dd7070Spatrick 
1553e5dd7070Spatrick       // The last diagnostic which Sema produced was ignored. Suppress any
1554e5dd7070Spatrick       // notes attached to it.
1555e5dd7070Spatrick       Diags.setLastDiagnosticIgnored(true);
1556e5dd7070Spatrick       return;
1557e5dd7070Spatrick     }
1558e5dd7070Spatrick 
1559e5dd7070Spatrick     case DiagnosticIDs::SFINAE_Suppress:
1560e5dd7070Spatrick       // Make a copy of this suppressed diagnostic and store it with the
1561e5dd7070Spatrick       // template-deduction information;
1562e5dd7070Spatrick       if (*Info) {
1563e5dd7070Spatrick         Diagnostic DiagInfo(&Diags);
1564e5dd7070Spatrick         (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1565e5dd7070Spatrick                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1566e5dd7070Spatrick       }
1567e5dd7070Spatrick 
1568e5dd7070Spatrick       // Suppress this diagnostic.
1569e5dd7070Spatrick       Diags.setLastDiagnosticIgnored(true);
1570e5dd7070Spatrick       Diags.Clear();
1571e5dd7070Spatrick       return;
1572e5dd7070Spatrick     }
1573e5dd7070Spatrick   }
1574e5dd7070Spatrick 
1575e5dd7070Spatrick   // Copy the diagnostic printing policy over the ASTContext printing policy.
1576e5dd7070Spatrick   // TODO: Stop doing that.  See: https://reviews.llvm.org/D45093#1090292
1577e5dd7070Spatrick   Context.setPrintingPolicy(getPrintingPolicy());
1578e5dd7070Spatrick 
1579e5dd7070Spatrick   // Emit the diagnostic.
1580e5dd7070Spatrick   if (!Diags.EmitCurrentDiagnostic())
1581e5dd7070Spatrick     return;
1582e5dd7070Spatrick 
1583e5dd7070Spatrick   // If this is not a note, and we're in a template instantiation
1584e5dd7070Spatrick   // that is different from the last template instantiation where
1585e5dd7070Spatrick   // we emitted an error, print a template instantiation
1586e5dd7070Spatrick   // backtrace.
1587e5dd7070Spatrick   if (!DiagnosticIDs::isBuiltinNote(DiagID))
1588e5dd7070Spatrick     PrintContextStack();
1589e5dd7070Spatrick }
1590e5dd7070Spatrick 
1591e5dd7070Spatrick Sema::SemaDiagnosticBuilder
Diag(SourceLocation Loc,const PartialDiagnostic & PD,bool DeferHint)1592a9ac8606Spatrick Sema::Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint) {
1593a9ac8606Spatrick   return Diag(Loc, PD.getDiagID(), DeferHint) << PD;
1594a9ac8606Spatrick }
1595e5dd7070Spatrick 
hasUncompilableErrorOccurred() const1596a9ac8606Spatrick bool Sema::hasUncompilableErrorOccurred() const {
1597a9ac8606Spatrick   if (getDiagnostics().hasUncompilableErrorOccurred())
1598a9ac8606Spatrick     return true;
1599a9ac8606Spatrick   auto *FD = dyn_cast<FunctionDecl>(CurContext);
1600a9ac8606Spatrick   if (!FD)
1601a9ac8606Spatrick     return false;
1602a9ac8606Spatrick   auto Loc = DeviceDeferredDiags.find(FD);
1603a9ac8606Spatrick   if (Loc == DeviceDeferredDiags.end())
1604a9ac8606Spatrick     return false;
1605a9ac8606Spatrick   for (auto PDAt : Loc->second) {
1606a9ac8606Spatrick     if (DiagnosticIDs::isDefaultMappingAsError(PDAt.second.getDiagID()))
1607a9ac8606Spatrick       return true;
1608a9ac8606Spatrick   }
1609a9ac8606Spatrick   return false;
1610e5dd7070Spatrick }
1611e5dd7070Spatrick 
1612e5dd7070Spatrick // Print notes showing how we can reach FD starting from an a priori
1613e5dd7070Spatrick // known-callable function.
emitCallStackNotes(Sema & S,FunctionDecl * FD)1614e5dd7070Spatrick static void emitCallStackNotes(Sema &S, FunctionDecl *FD) {
1615e5dd7070Spatrick   auto FnIt = S.DeviceKnownEmittedFns.find(FD);
1616e5dd7070Spatrick   while (FnIt != S.DeviceKnownEmittedFns.end()) {
1617ec727ea7Spatrick     // Respect error limit.
1618ec727ea7Spatrick     if (S.Diags.hasFatalErrorOccurred())
1619ec727ea7Spatrick       return;
1620e5dd7070Spatrick     DiagnosticBuilder Builder(
1621e5dd7070Spatrick         S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
1622e5dd7070Spatrick     Builder << FnIt->second.FD;
1623e5dd7070Spatrick     FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD);
1624e5dd7070Spatrick   }
1625e5dd7070Spatrick }
1626e5dd7070Spatrick 
1627ec727ea7Spatrick namespace {
1628ec727ea7Spatrick 
1629ec727ea7Spatrick /// Helper class that emits deferred diagnostic messages if an entity directly
1630ec727ea7Spatrick /// or indirectly using the function that causes the deferred diagnostic
1631ec727ea7Spatrick /// messages is known to be emitted.
1632ec727ea7Spatrick ///
1633ec727ea7Spatrick /// During parsing of AST, certain diagnostic messages are recorded as deferred
1634ec727ea7Spatrick /// diagnostics since it is unknown whether the functions containing such
1635ec727ea7Spatrick /// diagnostics will be emitted. A list of potentially emitted functions and
1636ec727ea7Spatrick /// variables that may potentially trigger emission of functions are also
1637ec727ea7Spatrick /// recorded. DeferredDiagnosticsEmitter recursively visits used functions
1638ec727ea7Spatrick /// by each function to emit deferred diagnostics.
1639ec727ea7Spatrick ///
1640ec727ea7Spatrick /// During the visit, certain OpenMP directives or initializer of variables
1641ec727ea7Spatrick /// with certain OpenMP attributes will cause subsequent visiting of any
1642ec727ea7Spatrick /// functions enter a state which is called OpenMP device context in this
1643ec727ea7Spatrick /// implementation. The state is exited when the directive or initializer is
1644ec727ea7Spatrick /// exited. This state can change the emission states of subsequent uses
1645ec727ea7Spatrick /// of functions.
1646ec727ea7Spatrick ///
1647ec727ea7Spatrick /// Conceptually the functions or variables to be visited form a use graph
1648ec727ea7Spatrick /// where the parent node uses the child node. At any point of the visit,
1649ec727ea7Spatrick /// the tree nodes traversed from the tree root to the current node form a use
1650ec727ea7Spatrick /// stack. The emission state of the current node depends on two factors:
1651ec727ea7Spatrick ///    1. the emission state of the root node
1652ec727ea7Spatrick ///    2. whether the current node is in OpenMP device context
1653ec727ea7Spatrick /// If the function is decided to be emitted, its contained deferred diagnostics
1654ec727ea7Spatrick /// are emitted, together with the information about the use stack.
1655ec727ea7Spatrick ///
1656ec727ea7Spatrick class DeferredDiagnosticsEmitter
1657ec727ea7Spatrick     : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
1658ec727ea7Spatrick public:
1659ec727ea7Spatrick   typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited;
1660ec727ea7Spatrick 
1661ec727ea7Spatrick   // Whether the function is already in the current use-path.
1662a9ac8606Spatrick   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath;
1663ec727ea7Spatrick 
1664ec727ea7Spatrick   // The current use-path.
1665ec727ea7Spatrick   llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath;
1666ec727ea7Spatrick 
1667ec727ea7Spatrick   // Whether the visiting of the function has been done. Done[0] is for the
1668ec727ea7Spatrick   // case not in OpenMP device context. Done[1] is for the case in OpenMP
1669ec727ea7Spatrick   // device context. We need two sets because diagnostics emission may be
1670ec727ea7Spatrick   // different depending on whether it is in OpenMP device context.
1671a9ac8606Spatrick   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2];
1672ec727ea7Spatrick 
1673ec727ea7Spatrick   // Emission state of the root node of the current use graph.
1674ec727ea7Spatrick   bool ShouldEmitRootNode;
1675ec727ea7Spatrick 
1676ec727ea7Spatrick   // Current OpenMP device context level. It is initialized to 0 and each
1677ec727ea7Spatrick   // entering of device context increases it by 1 and each exit decreases
1678ec727ea7Spatrick   // it by 1. Non-zero value indicates it is currently in device context.
1679ec727ea7Spatrick   unsigned InOMPDeviceContext;
1680ec727ea7Spatrick 
DeferredDiagnosticsEmitter(Sema & S)1681ec727ea7Spatrick   DeferredDiagnosticsEmitter(Sema &S)
1682ec727ea7Spatrick       : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
1683ec727ea7Spatrick 
shouldVisitDiscardedStmt() const1684a9ac8606Spatrick   bool shouldVisitDiscardedStmt() const { return false; }
1685a9ac8606Spatrick 
VisitOMPTargetDirective(OMPTargetDirective * Node)1686ec727ea7Spatrick   void VisitOMPTargetDirective(OMPTargetDirective *Node) {
1687ec727ea7Spatrick     ++InOMPDeviceContext;
1688ec727ea7Spatrick     Inherited::VisitOMPTargetDirective(Node);
1689ec727ea7Spatrick     --InOMPDeviceContext;
1690ec727ea7Spatrick   }
1691ec727ea7Spatrick 
visitUsedDecl(SourceLocation Loc,Decl * D)1692ec727ea7Spatrick   void visitUsedDecl(SourceLocation Loc, Decl *D) {
1693ec727ea7Spatrick     if (isa<VarDecl>(D))
1694ec727ea7Spatrick       return;
1695ec727ea7Spatrick     if (auto *FD = dyn_cast<FunctionDecl>(D))
1696ec727ea7Spatrick       checkFunc(Loc, FD);
1697ec727ea7Spatrick     else
1698ec727ea7Spatrick       Inherited::visitUsedDecl(Loc, D);
1699ec727ea7Spatrick   }
1700ec727ea7Spatrick 
checkVar(VarDecl * VD)1701ec727ea7Spatrick   void checkVar(VarDecl *VD) {
1702ec727ea7Spatrick     assert(VD->isFileVarDecl() &&
1703ec727ea7Spatrick            "Should only check file-scope variables");
1704ec727ea7Spatrick     if (auto *Init = VD->getInit()) {
1705ec727ea7Spatrick       auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
1706ec727ea7Spatrick       bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
1707ec727ea7Spatrick                              *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
1708ec727ea7Spatrick       if (IsDev)
1709ec727ea7Spatrick         ++InOMPDeviceContext;
1710ec727ea7Spatrick       this->Visit(Init);
1711ec727ea7Spatrick       if (IsDev)
1712ec727ea7Spatrick         --InOMPDeviceContext;
1713ec727ea7Spatrick     }
1714ec727ea7Spatrick   }
1715ec727ea7Spatrick 
checkFunc(SourceLocation Loc,FunctionDecl * FD)1716ec727ea7Spatrick   void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
1717ec727ea7Spatrick     auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];
1718ec727ea7Spatrick     FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back();
1719ec727ea7Spatrick     if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||
1720ec727ea7Spatrick         S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD))
1721ec727ea7Spatrick       return;
1722ec727ea7Spatrick     // Finalize analysis of OpenMP-specific constructs.
1723a9ac8606Spatrick     if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 &&
1724a9ac8606Spatrick         (ShouldEmitRootNode || InOMPDeviceContext))
1725ec727ea7Spatrick       S.finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
1726ec727ea7Spatrick     if (Caller)
1727ec727ea7Spatrick       S.DeviceKnownEmittedFns[FD] = {Caller, Loc};
1728ec727ea7Spatrick     // Always emit deferred diagnostics for the direct users. This does not
1729ec727ea7Spatrick     // lead to explosion of diagnostics since each user is visited at most
1730ec727ea7Spatrick     // twice.
1731ec727ea7Spatrick     if (ShouldEmitRootNode || InOMPDeviceContext)
1732ec727ea7Spatrick       emitDeferredDiags(FD, Caller);
1733ec727ea7Spatrick     // Do not revisit a function if the function body has been completely
1734ec727ea7Spatrick     // visited before.
1735ec727ea7Spatrick     if (!Done.insert(FD).second)
1736ec727ea7Spatrick       return;
1737ec727ea7Spatrick     InUsePath.insert(FD);
1738ec727ea7Spatrick     UsePath.push_back(FD);
1739ec727ea7Spatrick     if (auto *S = FD->getBody()) {
1740ec727ea7Spatrick       this->Visit(S);
1741ec727ea7Spatrick     }
1742ec727ea7Spatrick     UsePath.pop_back();
1743ec727ea7Spatrick     InUsePath.erase(FD);
1744ec727ea7Spatrick   }
1745ec727ea7Spatrick 
checkRecordedDecl(Decl * D)1746ec727ea7Spatrick   void checkRecordedDecl(Decl *D) {
1747ec727ea7Spatrick     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1748ec727ea7Spatrick       ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
1749ec727ea7Spatrick                            Sema::FunctionEmissionStatus::Emitted;
1750ec727ea7Spatrick       checkFunc(SourceLocation(), FD);
1751ec727ea7Spatrick     } else
1752ec727ea7Spatrick       checkVar(cast<VarDecl>(D));
1753ec727ea7Spatrick   }
1754ec727ea7Spatrick 
1755ec727ea7Spatrick   // Emit any deferred diagnostics for FD
emitDeferredDiags(FunctionDecl * FD,bool ShowCallStack)1756ec727ea7Spatrick   void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) {
1757e5dd7070Spatrick     auto It = S.DeviceDeferredDiags.find(FD);
1758e5dd7070Spatrick     if (It == S.DeviceDeferredDiags.end())
1759e5dd7070Spatrick       return;
1760e5dd7070Spatrick     bool HasWarningOrError = false;
1761ec727ea7Spatrick     bool FirstDiag = true;
1762e5dd7070Spatrick     for (PartialDiagnosticAt &PDAt : It->second) {
1763ec727ea7Spatrick       // Respect error limit.
1764ec727ea7Spatrick       if (S.Diags.hasFatalErrorOccurred())
1765ec727ea7Spatrick         return;
1766e5dd7070Spatrick       const SourceLocation &Loc = PDAt.first;
1767e5dd7070Spatrick       const PartialDiagnostic &PD = PDAt.second;
1768ec727ea7Spatrick       HasWarningOrError |=
1769ec727ea7Spatrick           S.getDiagnostics().getDiagnosticLevel(PD.getDiagID(), Loc) >=
1770ec727ea7Spatrick           DiagnosticsEngine::Warning;
1771ec727ea7Spatrick       {
1772e5dd7070Spatrick         DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
1773e5dd7070Spatrick         PD.Emit(Builder);
1774e5dd7070Spatrick       }
1775ec727ea7Spatrick       // Emit the note on the first diagnostic in case too many diagnostics
1776ec727ea7Spatrick       // cause the note not emitted.
1777ec727ea7Spatrick       if (FirstDiag && HasWarningOrError && ShowCallStack) {
1778e5dd7070Spatrick         emitCallStackNotes(S, FD);
1779ec727ea7Spatrick         FirstDiag = false;
1780ec727ea7Spatrick       }
1781ec727ea7Spatrick     }
1782ec727ea7Spatrick   }
1783ec727ea7Spatrick };
1784ec727ea7Spatrick } // namespace
1785ec727ea7Spatrick 
emitDeferredDiags()1786ec727ea7Spatrick void Sema::emitDeferredDiags() {
1787ec727ea7Spatrick   if (ExternalSource)
1788ec727ea7Spatrick     ExternalSource->ReadDeclsToCheckForDeferredDiags(
1789ec727ea7Spatrick         DeclsToCheckForDeferredDiags);
1790ec727ea7Spatrick 
1791ec727ea7Spatrick   if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||
1792ec727ea7Spatrick       DeclsToCheckForDeferredDiags.empty())
1793ec727ea7Spatrick     return;
1794ec727ea7Spatrick 
1795ec727ea7Spatrick   DeferredDiagnosticsEmitter DDE(*this);
1796*12c85518Srobert   for (auto *D : DeclsToCheckForDeferredDiags)
1797ec727ea7Spatrick     DDE.checkRecordedDecl(D);
1798e5dd7070Spatrick }
1799e5dd7070Spatrick 
1800e5dd7070Spatrick // In CUDA, there are some constructs which may appear in semantically-valid
1801e5dd7070Spatrick // code, but trigger errors if we ever generate code for the function in which
1802e5dd7070Spatrick // they appear.  Essentially every construct you're not allowed to use on the
1803e5dd7070Spatrick // device falls into this category, because you are allowed to use these
1804e5dd7070Spatrick // constructs in a __host__ __device__ function, but only if that function is
1805e5dd7070Spatrick // never codegen'ed on the device.
1806e5dd7070Spatrick //
1807e5dd7070Spatrick // To handle semantic checking for these constructs, we keep track of the set of
1808e5dd7070Spatrick // functions we know will be emitted, either because we could tell a priori that
1809e5dd7070Spatrick // they would be emitted, or because they were transitively called by a
1810e5dd7070Spatrick // known-emitted function.
1811e5dd7070Spatrick //
1812e5dd7070Spatrick // We also keep a partial call graph of which not-known-emitted functions call
1813e5dd7070Spatrick // which other not-known-emitted functions.
1814e5dd7070Spatrick //
1815e5dd7070Spatrick // When we see something which is illegal if the current function is emitted
1816e5dd7070Spatrick // (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
1817e5dd7070Spatrick // CheckCUDACall), we first check if the current function is known-emitted.  If
1818e5dd7070Spatrick // so, we immediately output the diagnostic.
1819e5dd7070Spatrick //
1820e5dd7070Spatrick // Otherwise, we "defer" the diagnostic.  It sits in Sema::DeviceDeferredDiags
1821e5dd7070Spatrick // until we discover that the function is known-emitted, at which point we take
1822e5dd7070Spatrick // it out of this map and emit the diagnostic.
1823e5dd7070Spatrick 
SemaDiagnosticBuilder(Kind K,SourceLocation Loc,unsigned DiagID,FunctionDecl * Fn,Sema & S)1824a9ac8606Spatrick Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc,
1825a9ac8606Spatrick                                                    unsigned DiagID,
1826a9ac8606Spatrick                                                    FunctionDecl *Fn, Sema &S)
1827e5dd7070Spatrick     : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
1828e5dd7070Spatrick       ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
1829e5dd7070Spatrick   switch (K) {
1830e5dd7070Spatrick   case K_Nop:
1831e5dd7070Spatrick     break;
1832e5dd7070Spatrick   case K_Immediate:
1833e5dd7070Spatrick   case K_ImmediateWithCallStack:
1834a9ac8606Spatrick     ImmediateDiag.emplace(
1835a9ac8606Spatrick         ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));
1836e5dd7070Spatrick     break;
1837e5dd7070Spatrick   case K_Deferred:
1838e5dd7070Spatrick     assert(Fn && "Must have a function to attach the deferred diag to.");
1839e5dd7070Spatrick     auto &Diags = S.DeviceDeferredDiags[Fn];
1840e5dd7070Spatrick     PartialDiagId.emplace(Diags.size());
1841e5dd7070Spatrick     Diags.emplace_back(Loc, S.PDiag(DiagID));
1842e5dd7070Spatrick     break;
1843e5dd7070Spatrick   }
1844e5dd7070Spatrick }
1845e5dd7070Spatrick 
SemaDiagnosticBuilder(SemaDiagnosticBuilder && D)1846a9ac8606Spatrick Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D)
1847e5dd7070Spatrick     : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
1848e5dd7070Spatrick       ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
1849e5dd7070Spatrick       PartialDiagId(D.PartialDiagId) {
1850e5dd7070Spatrick   // Clean the previous diagnostics.
1851e5dd7070Spatrick   D.ShowCallStack = false;
1852e5dd7070Spatrick   D.ImmediateDiag.reset();
1853e5dd7070Spatrick   D.PartialDiagId.reset();
1854e5dd7070Spatrick }
1855e5dd7070Spatrick 
~SemaDiagnosticBuilder()1856a9ac8606Spatrick Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
1857e5dd7070Spatrick   if (ImmediateDiag) {
1858e5dd7070Spatrick     // Emit our diagnostic and, if it was a warning or error, output a callstack
1859e5dd7070Spatrick     // if Fn isn't a priori known-emitted.
1860e5dd7070Spatrick     bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
1861e5dd7070Spatrick                                 DiagID, Loc) >= DiagnosticsEngine::Warning;
1862e5dd7070Spatrick     ImmediateDiag.reset(); // Emit the immediate diag.
1863e5dd7070Spatrick     if (IsWarningOrError && ShowCallStack)
1864e5dd7070Spatrick       emitCallStackNotes(S, Fn);
1865e5dd7070Spatrick   } else {
1866e5dd7070Spatrick     assert((!PartialDiagId || ShowCallStack) &&
1867e5dd7070Spatrick            "Must always show call stack for deferred diags.");
1868e5dd7070Spatrick   }
1869e5dd7070Spatrick }
1870e5dd7070Spatrick 
1871a9ac8606Spatrick Sema::SemaDiagnosticBuilder
targetDiag(SourceLocation Loc,unsigned DiagID,FunctionDecl * FD)1872a9ac8606Spatrick Sema::targetDiag(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD) {
1873a9ac8606Spatrick   FD = FD ? FD : getCurFunctionDecl();
1874e5dd7070Spatrick   if (LangOpts.OpenMP)
1875a9ac8606Spatrick     return LangOpts.OpenMPIsDevice ? diagIfOpenMPDeviceCode(Loc, DiagID, FD)
1876a9ac8606Spatrick                                    : diagIfOpenMPHostCode(Loc, DiagID, FD);
1877e5dd7070Spatrick   if (getLangOpts().CUDA)
1878e5dd7070Spatrick     return getLangOpts().CUDAIsDevice ? CUDADiagIfDeviceCode(Loc, DiagID)
1879e5dd7070Spatrick                                       : CUDADiagIfHostCode(Loc, DiagID);
1880ec727ea7Spatrick 
1881ec727ea7Spatrick   if (getLangOpts().SYCLIsDevice)
1882ec727ea7Spatrick     return SYCLDiagIfDeviceCode(Loc, DiagID);
1883ec727ea7Spatrick 
1884a9ac8606Spatrick   return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, DiagID,
1885a9ac8606Spatrick                                FD, *this);
1886e5dd7070Spatrick }
1887e5dd7070Spatrick 
Diag(SourceLocation Loc,unsigned DiagID,bool DeferHint)1888a9ac8606Spatrick Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID,
1889a9ac8606Spatrick                                        bool DeferHint) {
1890a9ac8606Spatrick   bool IsError = Diags.getDiagnosticIDs()->isDefaultMappingAsError(DiagID);
1891a9ac8606Spatrick   bool ShouldDefer = getLangOpts().CUDA && LangOpts.GPUDeferDiag &&
1892a9ac8606Spatrick                      DiagnosticIDs::isDeferrable(DiagID) &&
1893a9ac8606Spatrick                      (DeferHint || DeferDiags || !IsError);
1894a9ac8606Spatrick   auto SetIsLastErrorImmediate = [&](bool Flag) {
1895a9ac8606Spatrick     if (IsError)
1896a9ac8606Spatrick       IsLastErrorImmediate = Flag;
1897a9ac8606Spatrick   };
1898a9ac8606Spatrick   if (!ShouldDefer) {
1899a9ac8606Spatrick     SetIsLastErrorImmediate(true);
1900a9ac8606Spatrick     return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc,
1901a9ac8606Spatrick                                  DiagID, getCurFunctionDecl(), *this);
1902a9ac8606Spatrick   }
1903a9ac8606Spatrick 
1904a9ac8606Spatrick   SemaDiagnosticBuilder DB = getLangOpts().CUDAIsDevice
1905a9ac8606Spatrick                                  ? CUDADiagIfDeviceCode(Loc, DiagID)
1906a9ac8606Spatrick                                  : CUDADiagIfHostCode(Loc, DiagID);
1907a9ac8606Spatrick   SetIsLastErrorImmediate(DB.isImmediate());
1908a9ac8606Spatrick   return DB;
1909a9ac8606Spatrick }
1910a9ac8606Spatrick 
checkTypeSupport(QualType Ty,SourceLocation Loc,ValueDecl * D)1911*12c85518Srobert void Sema::checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D) {
1912*12c85518Srobert   if (isUnevaluatedContext() || Ty.isNull())
1913ec727ea7Spatrick     return;
1914ec727ea7Spatrick 
1915*12c85518Srobert   // The original idea behind checkTypeSupport function is that unused
1916*12c85518Srobert   // declarations can be replaced with an array of bytes of the same size during
1917*12c85518Srobert   // codegen, such replacement doesn't seem to be possible for types without
1918*12c85518Srobert   // constant byte size like zero length arrays. So, do a deep check for SYCL.
1919*12c85518Srobert   if (D && LangOpts.SYCLIsDevice) {
1920*12c85518Srobert     llvm::DenseSet<QualType> Visited;
1921*12c85518Srobert     deepTypeCheckForSYCLDevice(Loc, Visited, D);
1922*12c85518Srobert   }
1923*12c85518Srobert 
1924ec727ea7Spatrick   Decl *C = cast<Decl>(getCurLexicalContext());
1925ec727ea7Spatrick 
1926ec727ea7Spatrick   // Memcpy operations for structs containing a member with unsupported type
1927ec727ea7Spatrick   // are ok, though.
1928ec727ea7Spatrick   if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
1929ec727ea7Spatrick     if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
1930ec727ea7Spatrick         MD->isTrivial())
1931ec727ea7Spatrick       return;
1932ec727ea7Spatrick 
1933ec727ea7Spatrick     if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
1934ec727ea7Spatrick       if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())
1935ec727ea7Spatrick         return;
1936ec727ea7Spatrick   }
1937ec727ea7Spatrick 
1938a9ac8606Spatrick   // Try to associate errors with the lexical context, if that is a function, or
1939a9ac8606Spatrick   // the value declaration otherwise.
1940*12c85518Srobert   FunctionDecl *FD = isa<FunctionDecl>(C) ? cast<FunctionDecl>(C)
1941*12c85518Srobert                                           : dyn_cast_or_null<FunctionDecl>(D);
1942*12c85518Srobert 
1943*12c85518Srobert   auto CheckDeviceType = [&](QualType Ty) {
1944ec727ea7Spatrick     if (Ty->isDependentType())
1945ec727ea7Spatrick       return;
1946ec727ea7Spatrick 
1947*12c85518Srobert     if (Ty->isBitIntType()) {
1948*12c85518Srobert       if (!Context.getTargetInfo().hasBitIntType()) {
1949*12c85518Srobert         PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
1950*12c85518Srobert         if (D)
1951*12c85518Srobert           PD << D;
1952*12c85518Srobert         else
1953*12c85518Srobert           PD << "expression";
1954*12c85518Srobert         targetDiag(Loc, PD, FD)
1955*12c85518Srobert             << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/
1956a9ac8606Spatrick             << Ty << Context.getTargetInfo().getTriple().str();
1957a9ac8606Spatrick       }
1958a9ac8606Spatrick       return;
1959a9ac8606Spatrick     }
1960a9ac8606Spatrick 
1961*12c85518Srobert     // Check if we are dealing with two 'long double' but with different
1962*12c85518Srobert     // semantics.
1963*12c85518Srobert     bool LongDoubleMismatched = false;
1964*12c85518Srobert     if (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128) {
1965*12c85518Srobert       const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(Ty);
1966*12c85518Srobert       if ((&Sem != &llvm::APFloat::PPCDoubleDouble() &&
1967ec727ea7Spatrick            !Context.getTargetInfo().hasFloat128Type()) ||
1968*12c85518Srobert           (&Sem == &llvm::APFloat::PPCDoubleDouble() &&
1969*12c85518Srobert            !Context.getTargetInfo().hasIbm128Type()))
1970*12c85518Srobert         LongDoubleMismatched = true;
1971*12c85518Srobert     }
1972*12c85518Srobert 
1973*12c85518Srobert     if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1974*12c85518Srobert         (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
1975*12c85518Srobert         (Ty->isIbm128Type() && !Context.getTargetInfo().hasIbm128Type()) ||
1976ec727ea7Spatrick         (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1977*12c85518Srobert          !Context.getTargetInfo().hasInt128Type()) ||
1978*12c85518Srobert         LongDoubleMismatched) {
1979*12c85518Srobert       PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
1980*12c85518Srobert       if (D)
1981*12c85518Srobert         PD << D;
1982*12c85518Srobert       else
1983*12c85518Srobert         PD << "expression";
1984*12c85518Srobert 
1985*12c85518Srobert       if (targetDiag(Loc, PD, FD)
1986*12c85518Srobert           << true /*show bit size*/
1987a9ac8606Spatrick           << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1988*12c85518Srobert           << false /*return*/ << Context.getTargetInfo().getTriple().str()) {
1989*12c85518Srobert         if (D)
1990a9ac8606Spatrick           D->setInvalidDecl();
1991*12c85518Srobert       }
1992*12c85518Srobert       if (D)
1993a9ac8606Spatrick         targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
1994ec727ea7Spatrick     }
1995ec727ea7Spatrick   };
1996ec727ea7Spatrick 
1997*12c85518Srobert   auto CheckType = [&](QualType Ty, bool IsRetTy = false) {
1998*12c85518Srobert     if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice) ||
1999*12c85518Srobert         LangOpts.CUDAIsDevice)
2000*12c85518Srobert       CheckDeviceType(Ty);
2001ec727ea7Spatrick 
2002*12c85518Srobert     QualType UnqualTy = Ty.getCanonicalType().getUnqualifiedType();
2003*12c85518Srobert     const TargetInfo &TI = Context.getTargetInfo();
2004*12c85518Srobert     if (!TI.hasLongDoubleType() && UnqualTy == Context.LongDoubleTy) {
2005*12c85518Srobert       PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2006*12c85518Srobert       if (D)
2007*12c85518Srobert         PD << D;
2008*12c85518Srobert       else
2009*12c85518Srobert         PD << "expression";
2010*12c85518Srobert 
2011*12c85518Srobert       if (Diag(Loc, PD, FD)
2012*12c85518Srobert           << false /*show bit size*/ << 0 << Ty << false /*return*/
2013*12c85518Srobert           << Context.getTargetInfo().getTriple().str()) {
2014*12c85518Srobert         if (D)
2015*12c85518Srobert           D->setInvalidDecl();
2016*12c85518Srobert       }
2017*12c85518Srobert       if (D)
2018*12c85518Srobert         targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2019*12c85518Srobert     }
2020*12c85518Srobert 
2021*12c85518Srobert     bool IsDouble = UnqualTy == Context.DoubleTy;
2022*12c85518Srobert     bool IsFloat = UnqualTy == Context.FloatTy;
2023*12c85518Srobert     if (IsRetTy && !TI.hasFPReturn() && (IsDouble || IsFloat)) {
2024*12c85518Srobert       PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2025*12c85518Srobert       if (D)
2026*12c85518Srobert         PD << D;
2027*12c85518Srobert       else
2028*12c85518Srobert         PD << "expression";
2029*12c85518Srobert 
2030*12c85518Srobert       if (Diag(Loc, PD, FD)
2031*12c85518Srobert           << false /*show bit size*/ << 0 << Ty << true /*return*/
2032*12c85518Srobert           << Context.getTargetInfo().getTriple().str()) {
2033*12c85518Srobert         if (D)
2034*12c85518Srobert           D->setInvalidDecl();
2035*12c85518Srobert       }
2036*12c85518Srobert       if (D)
2037*12c85518Srobert         targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2038*12c85518Srobert     }
2039*12c85518Srobert 
2040*12c85518Srobert     // Don't allow SVE types in functions without a SVE target.
2041*12c85518Srobert     if (Ty->isSVESizelessBuiltinType() && FD && FD->hasBody()) {
2042*12c85518Srobert       llvm::StringMap<bool> CallerFeatureMap;
2043*12c85518Srobert       Context.getFunctionFeatureMap(CallerFeatureMap, FD);
2044*12c85518Srobert       if (!Builtin::evaluateRequiredTargetFeatures(
2045*12c85518Srobert           "sve", CallerFeatureMap))
2046*12c85518Srobert         Diag(D->getLocation(), diag::err_sve_vector_in_non_sve_target) << Ty;
2047*12c85518Srobert     }
2048*12c85518Srobert   };
2049*12c85518Srobert 
2050*12c85518Srobert   CheckType(Ty);
2051ec727ea7Spatrick   if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
2052ec727ea7Spatrick     for (const auto &ParamTy : FPTy->param_types())
2053ec727ea7Spatrick       CheckType(ParamTy);
2054*12c85518Srobert     CheckType(FPTy->getReturnType(), /*IsRetTy=*/true);
2055ec727ea7Spatrick   }
2056a9ac8606Spatrick   if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty))
2057*12c85518Srobert     CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true);
2058ec727ea7Spatrick }
2059ec727ea7Spatrick 
2060e5dd7070Spatrick /// Looks through the macro-expansion chain for the given
2061e5dd7070Spatrick /// location, looking for a macro expansion with the given name.
2062e5dd7070Spatrick /// If one is found, returns true and sets the location to that
2063e5dd7070Spatrick /// expansion loc.
findMacroSpelling(SourceLocation & locref,StringRef name)2064e5dd7070Spatrick bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
2065e5dd7070Spatrick   SourceLocation loc = locref;
2066e5dd7070Spatrick   if (!loc.isMacroID()) return false;
2067e5dd7070Spatrick 
2068e5dd7070Spatrick   // There's no good way right now to look at the intermediate
2069e5dd7070Spatrick   // expansions, so just jump to the expansion location.
2070e5dd7070Spatrick   loc = getSourceManager().getExpansionLoc(loc);
2071e5dd7070Spatrick 
2072e5dd7070Spatrick   // If that's written with the name, stop here.
2073a9ac8606Spatrick   SmallString<16> buffer;
2074e5dd7070Spatrick   if (getPreprocessor().getSpelling(loc, buffer) == name) {
2075e5dd7070Spatrick     locref = loc;
2076e5dd7070Spatrick     return true;
2077e5dd7070Spatrick   }
2078e5dd7070Spatrick   return false;
2079e5dd7070Spatrick }
2080e5dd7070Spatrick 
2081e5dd7070Spatrick /// Determines the active Scope associated with the given declaration
2082e5dd7070Spatrick /// context.
2083e5dd7070Spatrick ///
2084e5dd7070Spatrick /// This routine maps a declaration context to the active Scope object that
2085e5dd7070Spatrick /// represents that declaration context in the parser. It is typically used
2086e5dd7070Spatrick /// from "scope-less" code (e.g., template instantiation, lazy creation of
2087e5dd7070Spatrick /// declarations) that injects a name for name-lookup purposes and, therefore,
2088e5dd7070Spatrick /// must update the Scope.
2089e5dd7070Spatrick ///
2090e5dd7070Spatrick /// \returns The scope corresponding to the given declaraion context, or NULL
2091e5dd7070Spatrick /// if no such scope is open.
getScopeForContext(DeclContext * Ctx)2092e5dd7070Spatrick Scope *Sema::getScopeForContext(DeclContext *Ctx) {
2093e5dd7070Spatrick 
2094e5dd7070Spatrick   if (!Ctx)
2095e5dd7070Spatrick     return nullptr;
2096e5dd7070Spatrick 
2097e5dd7070Spatrick   Ctx = Ctx->getPrimaryContext();
2098e5dd7070Spatrick   for (Scope *S = getCurScope(); S; S = S->getParent()) {
2099e5dd7070Spatrick     // Ignore scopes that cannot have declarations. This is important for
2100e5dd7070Spatrick     // out-of-line definitions of static class members.
2101e5dd7070Spatrick     if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
2102e5dd7070Spatrick       if (DeclContext *Entity = S->getEntity())
2103e5dd7070Spatrick         if (Ctx == Entity->getPrimaryContext())
2104e5dd7070Spatrick           return S;
2105e5dd7070Spatrick   }
2106e5dd7070Spatrick 
2107e5dd7070Spatrick   return nullptr;
2108e5dd7070Spatrick }
2109e5dd7070Spatrick 
2110e5dd7070Spatrick /// Enter a new function scope
PushFunctionScope()2111e5dd7070Spatrick void Sema::PushFunctionScope() {
2112e5dd7070Spatrick   if (FunctionScopes.empty() && CachedFunctionScope) {
2113e5dd7070Spatrick     // Use CachedFunctionScope to avoid allocating memory when possible.
2114e5dd7070Spatrick     CachedFunctionScope->Clear();
2115e5dd7070Spatrick     FunctionScopes.push_back(CachedFunctionScope.release());
2116e5dd7070Spatrick   } else {
2117e5dd7070Spatrick     FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
2118e5dd7070Spatrick   }
2119e5dd7070Spatrick   if (LangOpts.OpenMP)
2120e5dd7070Spatrick     pushOpenMPFunctionRegion();
2121e5dd7070Spatrick }
2122e5dd7070Spatrick 
PushBlockScope(Scope * BlockScope,BlockDecl * Block)2123e5dd7070Spatrick void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
2124e5dd7070Spatrick   FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
2125e5dd7070Spatrick                                               BlockScope, Block));
2126e5dd7070Spatrick }
2127e5dd7070Spatrick 
PushLambdaScope()2128e5dd7070Spatrick LambdaScopeInfo *Sema::PushLambdaScope() {
2129e5dd7070Spatrick   LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
2130e5dd7070Spatrick   FunctionScopes.push_back(LSI);
2131e5dd7070Spatrick   return LSI;
2132e5dd7070Spatrick }
2133e5dd7070Spatrick 
RecordParsingTemplateParameterDepth(unsigned Depth)2134e5dd7070Spatrick void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
2135e5dd7070Spatrick   if (LambdaScopeInfo *const LSI = getCurLambda()) {
2136e5dd7070Spatrick     LSI->AutoTemplateParameterDepth = Depth;
2137e5dd7070Spatrick     return;
2138e5dd7070Spatrick   }
2139e5dd7070Spatrick   llvm_unreachable(
2140e5dd7070Spatrick       "Remove assertion if intentionally called in a non-lambda context.");
2141e5dd7070Spatrick }
2142e5dd7070Spatrick 
2143e5dd7070Spatrick // Check that the type of the VarDecl has an accessible copy constructor and
2144e5dd7070Spatrick // resolve its destructor's exception specification.
2145a9ac8606Spatrick // This also performs initialization of block variables when they are moved
2146a9ac8606Spatrick // to the heap. It uses the same rules as applicable for implicit moves
2147a9ac8606Spatrick // according to the C++ standard in effect ([class.copy.elision]p3).
checkEscapingByref(VarDecl * VD,Sema & S)2148e5dd7070Spatrick static void checkEscapingByref(VarDecl *VD, Sema &S) {
2149e5dd7070Spatrick   QualType T = VD->getType();
2150e5dd7070Spatrick   EnterExpressionEvaluationContext scope(
2151e5dd7070Spatrick       S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2152e5dd7070Spatrick   SourceLocation Loc = VD->getLocation();
2153e5dd7070Spatrick   Expr *VarRef =
2154e5dd7070Spatrick       new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
2155a9ac8606Spatrick   ExprResult Result;
2156a9ac8606Spatrick   auto IE = InitializedEntity::InitializeBlock(Loc, T);
2157a9ac8606Spatrick   if (S.getLangOpts().CPlusPlus2b) {
2158a9ac8606Spatrick     auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr,
2159a9ac8606Spatrick                                        VK_XValue, FPOptionsOverride());
2160a9ac8606Spatrick     Result = S.PerformCopyInitialization(IE, SourceLocation(), E);
2161a9ac8606Spatrick   } else {
2162a9ac8606Spatrick     Result = S.PerformMoveOrCopyInitialization(
2163a9ac8606Spatrick         IE, Sema::NamedReturnInfo{VD, Sema::NamedReturnInfo::MoveEligible},
2164a9ac8606Spatrick         VarRef);
2165a9ac8606Spatrick   }
2166a9ac8606Spatrick 
2167e5dd7070Spatrick   if (!Result.isInvalid()) {
2168e5dd7070Spatrick     Result = S.MaybeCreateExprWithCleanups(Result);
2169e5dd7070Spatrick     Expr *Init = Result.getAs<Expr>();
2170e5dd7070Spatrick     S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));
2171e5dd7070Spatrick   }
2172e5dd7070Spatrick 
2173e5dd7070Spatrick   // The destructor's exception specification is needed when IRGen generates
2174e5dd7070Spatrick   // block copy/destroy functions. Resolve it here.
2175e5dd7070Spatrick   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2176e5dd7070Spatrick     if (CXXDestructorDecl *DD = RD->getDestructor()) {
2177e5dd7070Spatrick       auto *FPT = DD->getType()->getAs<FunctionProtoType>();
2178e5dd7070Spatrick       S.ResolveExceptionSpec(Loc, FPT);
2179e5dd7070Spatrick     }
2180e5dd7070Spatrick }
2181e5dd7070Spatrick 
markEscapingByrefs(const FunctionScopeInfo & FSI,Sema & S)2182e5dd7070Spatrick static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
2183e5dd7070Spatrick   // Set the EscapingByref flag of __block variables captured by
2184e5dd7070Spatrick   // escaping blocks.
2185e5dd7070Spatrick   for (const BlockDecl *BD : FSI.Blocks) {
2186e5dd7070Spatrick     for (const BlockDecl::Capture &BC : BD->captures()) {
2187e5dd7070Spatrick       VarDecl *VD = BC.getVariable();
2188e5dd7070Spatrick       if (VD->hasAttr<BlocksAttr>()) {
2189e5dd7070Spatrick         // Nothing to do if this is a __block variable captured by a
2190e5dd7070Spatrick         // non-escaping block.
2191e5dd7070Spatrick         if (BD->doesNotEscape())
2192e5dd7070Spatrick           continue;
2193e5dd7070Spatrick         VD->setEscapingByref();
2194e5dd7070Spatrick       }
2195e5dd7070Spatrick       // Check whether the captured variable is or contains an object of
2196e5dd7070Spatrick       // non-trivial C union type.
2197e5dd7070Spatrick       QualType CapType = BC.getVariable()->getType();
2198e5dd7070Spatrick       if (CapType.hasNonTrivialToPrimitiveDestructCUnion() ||
2199e5dd7070Spatrick           CapType.hasNonTrivialToPrimitiveCopyCUnion())
2200e5dd7070Spatrick         S.checkNonTrivialCUnion(BC.getVariable()->getType(),
2201e5dd7070Spatrick                                 BD->getCaretLocation(),
2202e5dd7070Spatrick                                 Sema::NTCUC_BlockCapture,
2203e5dd7070Spatrick                                 Sema::NTCUK_Destruct|Sema::NTCUK_Copy);
2204e5dd7070Spatrick     }
2205e5dd7070Spatrick   }
2206e5dd7070Spatrick 
2207e5dd7070Spatrick   for (VarDecl *VD : FSI.ByrefBlockVars) {
2208e5dd7070Spatrick     // __block variables might require us to capture a copy-initializer.
2209e5dd7070Spatrick     if (!VD->isEscapingByref())
2210e5dd7070Spatrick       continue;
2211e5dd7070Spatrick     // It's currently invalid to ever have a __block variable with an
2212e5dd7070Spatrick     // array type; should we diagnose that here?
2213e5dd7070Spatrick     // Regardless, we don't want to ignore array nesting when
2214e5dd7070Spatrick     // constructing this copy.
2215e5dd7070Spatrick     if (VD->getType()->isStructureOrClassType())
2216e5dd7070Spatrick       checkEscapingByref(VD, S);
2217e5dd7070Spatrick   }
2218e5dd7070Spatrick }
2219e5dd7070Spatrick 
2220e5dd7070Spatrick /// Pop a function (or block or lambda or captured region) scope from the stack.
2221e5dd7070Spatrick ///
2222e5dd7070Spatrick /// \param WP The warning policy to use for CFG-based warnings, or null if such
2223e5dd7070Spatrick ///        warnings should not be produced.
2224e5dd7070Spatrick /// \param D The declaration corresponding to this function scope, if producing
2225e5dd7070Spatrick ///        CFG-based warnings.
2226e5dd7070Spatrick /// \param BlockType The type of the block expression, if D is a BlockDecl.
2227e5dd7070Spatrick Sema::PoppedFunctionScopePtr
PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy * WP,const Decl * D,QualType BlockType)2228e5dd7070Spatrick Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
2229e5dd7070Spatrick                            const Decl *D, QualType BlockType) {
2230e5dd7070Spatrick   assert(!FunctionScopes.empty() && "mismatched push/pop!");
2231e5dd7070Spatrick 
2232e5dd7070Spatrick   markEscapingByrefs(*FunctionScopes.back(), *this);
2233e5dd7070Spatrick 
2234e5dd7070Spatrick   PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
2235e5dd7070Spatrick                                PoppedFunctionScopeDeleter(this));
2236e5dd7070Spatrick 
2237e5dd7070Spatrick   if (LangOpts.OpenMP)
2238e5dd7070Spatrick     popOpenMPFunctionRegion(Scope.get());
2239e5dd7070Spatrick 
2240e5dd7070Spatrick   // Issue any analysis-based warnings.
2241e5dd7070Spatrick   if (WP && D)
2242e5dd7070Spatrick     AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
2243e5dd7070Spatrick   else
2244e5dd7070Spatrick     for (const auto &PUD : Scope->PossiblyUnreachableDiags)
2245e5dd7070Spatrick       Diag(PUD.Loc, PUD.PD);
2246e5dd7070Spatrick 
2247e5dd7070Spatrick   return Scope;
2248e5dd7070Spatrick }
2249e5dd7070Spatrick 
2250e5dd7070Spatrick void Sema::PoppedFunctionScopeDeleter::
operator ()(sema::FunctionScopeInfo * Scope) const2251e5dd7070Spatrick operator()(sema::FunctionScopeInfo *Scope) const {
2252e5dd7070Spatrick   // Stash the function scope for later reuse if it's for a normal function.
2253e5dd7070Spatrick   if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
2254e5dd7070Spatrick     Self->CachedFunctionScope.reset(Scope);
2255e5dd7070Spatrick   else
2256e5dd7070Spatrick     delete Scope;
2257e5dd7070Spatrick }
2258e5dd7070Spatrick 
PushCompoundScope(bool IsStmtExpr)2259e5dd7070Spatrick void Sema::PushCompoundScope(bool IsStmtExpr) {
2260*12c85518Srobert   getCurFunction()->CompoundScopes.push_back(
2261*12c85518Srobert       CompoundScopeInfo(IsStmtExpr, getCurFPFeatures()));
2262e5dd7070Spatrick }
2263e5dd7070Spatrick 
PopCompoundScope()2264e5dd7070Spatrick void Sema::PopCompoundScope() {
2265e5dd7070Spatrick   FunctionScopeInfo *CurFunction = getCurFunction();
2266e5dd7070Spatrick   assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
2267e5dd7070Spatrick 
2268e5dd7070Spatrick   CurFunction->CompoundScopes.pop_back();
2269e5dd7070Spatrick }
2270e5dd7070Spatrick 
2271e5dd7070Spatrick /// Determine whether any errors occurred within this function/method/
2272e5dd7070Spatrick /// block.
hasAnyUnrecoverableErrorsInThisFunction() const2273e5dd7070Spatrick bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
2274ec727ea7Spatrick   return getCurFunction()->hasUnrecoverableErrorOccurred();
2275e5dd7070Spatrick }
2276e5dd7070Spatrick 
setFunctionHasBranchIntoScope()2277e5dd7070Spatrick void Sema::setFunctionHasBranchIntoScope() {
2278e5dd7070Spatrick   if (!FunctionScopes.empty())
2279e5dd7070Spatrick     FunctionScopes.back()->setHasBranchIntoScope();
2280e5dd7070Spatrick }
2281e5dd7070Spatrick 
setFunctionHasBranchProtectedScope()2282e5dd7070Spatrick void Sema::setFunctionHasBranchProtectedScope() {
2283e5dd7070Spatrick   if (!FunctionScopes.empty())
2284e5dd7070Spatrick     FunctionScopes.back()->setHasBranchProtectedScope();
2285e5dd7070Spatrick }
2286e5dd7070Spatrick 
setFunctionHasIndirectGoto()2287e5dd7070Spatrick void Sema::setFunctionHasIndirectGoto() {
2288e5dd7070Spatrick   if (!FunctionScopes.empty())
2289e5dd7070Spatrick     FunctionScopes.back()->setHasIndirectGoto();
2290e5dd7070Spatrick }
2291e5dd7070Spatrick 
setFunctionHasMustTail()2292a9ac8606Spatrick void Sema::setFunctionHasMustTail() {
2293a9ac8606Spatrick   if (!FunctionScopes.empty())
2294a9ac8606Spatrick     FunctionScopes.back()->setHasMustTail();
2295a9ac8606Spatrick }
2296a9ac8606Spatrick 
getCurBlock()2297e5dd7070Spatrick BlockScopeInfo *Sema::getCurBlock() {
2298e5dd7070Spatrick   if (FunctionScopes.empty())
2299e5dd7070Spatrick     return nullptr;
2300e5dd7070Spatrick 
2301e5dd7070Spatrick   auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
2302e5dd7070Spatrick   if (CurBSI && CurBSI->TheDecl &&
2303e5dd7070Spatrick       !CurBSI->TheDecl->Encloses(CurContext)) {
2304e5dd7070Spatrick     // We have switched contexts due to template instantiation.
2305e5dd7070Spatrick     assert(!CodeSynthesisContexts.empty());
2306e5dd7070Spatrick     return nullptr;
2307e5dd7070Spatrick   }
2308e5dd7070Spatrick 
2309e5dd7070Spatrick   return CurBSI;
2310e5dd7070Spatrick }
2311e5dd7070Spatrick 
getEnclosingFunction() const2312e5dd7070Spatrick FunctionScopeInfo *Sema::getEnclosingFunction() const {
2313e5dd7070Spatrick   if (FunctionScopes.empty())
2314e5dd7070Spatrick     return nullptr;
2315e5dd7070Spatrick 
2316e5dd7070Spatrick   for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
2317e5dd7070Spatrick     if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
2318e5dd7070Spatrick       continue;
2319e5dd7070Spatrick     return FunctionScopes[e];
2320e5dd7070Spatrick   }
2321e5dd7070Spatrick   return nullptr;
2322e5dd7070Spatrick }
2323e5dd7070Spatrick 
getEnclosingLambda() const2324e5dd7070Spatrick LambdaScopeInfo *Sema::getEnclosingLambda() const {
2325e5dd7070Spatrick   for (auto *Scope : llvm::reverse(FunctionScopes)) {
2326e5dd7070Spatrick     if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) {
2327e5dd7070Spatrick       if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext)) {
2328e5dd7070Spatrick         // We have switched contexts due to template instantiation.
2329e5dd7070Spatrick         // FIXME: We should swap out the FunctionScopes during code synthesis
2330e5dd7070Spatrick         // so that we don't need to check for this.
2331e5dd7070Spatrick         assert(!CodeSynthesisContexts.empty());
2332e5dd7070Spatrick         return nullptr;
2333e5dd7070Spatrick       }
2334e5dd7070Spatrick       return LSI;
2335e5dd7070Spatrick     }
2336e5dd7070Spatrick   }
2337e5dd7070Spatrick   return nullptr;
2338e5dd7070Spatrick }
2339e5dd7070Spatrick 
getCurLambda(bool IgnoreNonLambdaCapturingScope)2340e5dd7070Spatrick LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
2341e5dd7070Spatrick   if (FunctionScopes.empty())
2342e5dd7070Spatrick     return nullptr;
2343e5dd7070Spatrick 
2344e5dd7070Spatrick   auto I = FunctionScopes.rbegin();
2345e5dd7070Spatrick   if (IgnoreNonLambdaCapturingScope) {
2346e5dd7070Spatrick     auto E = FunctionScopes.rend();
2347e5dd7070Spatrick     while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
2348e5dd7070Spatrick       ++I;
2349e5dd7070Spatrick     if (I == E)
2350e5dd7070Spatrick       return nullptr;
2351e5dd7070Spatrick   }
2352e5dd7070Spatrick   auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
2353e5dd7070Spatrick   if (CurLSI && CurLSI->Lambda &&
2354e5dd7070Spatrick       !CurLSI->Lambda->Encloses(CurContext)) {
2355e5dd7070Spatrick     // We have switched contexts due to template instantiation.
2356e5dd7070Spatrick     assert(!CodeSynthesisContexts.empty());
2357e5dd7070Spatrick     return nullptr;
2358e5dd7070Spatrick   }
2359e5dd7070Spatrick 
2360e5dd7070Spatrick   return CurLSI;
2361e5dd7070Spatrick }
2362e5dd7070Spatrick 
2363e5dd7070Spatrick // We have a generic lambda if we parsed auto parameters, or we have
2364e5dd7070Spatrick // an associated template parameter list.
getCurGenericLambda()2365e5dd7070Spatrick LambdaScopeInfo *Sema::getCurGenericLambda() {
2366e5dd7070Spatrick   if (LambdaScopeInfo *LSI =  getCurLambda()) {
2367e5dd7070Spatrick     return (LSI->TemplateParams.size() ||
2368e5dd7070Spatrick                     LSI->GLTemplateParameterList) ? LSI : nullptr;
2369e5dd7070Spatrick   }
2370e5dd7070Spatrick   return nullptr;
2371e5dd7070Spatrick }
2372e5dd7070Spatrick 
2373e5dd7070Spatrick 
ActOnComment(SourceRange Comment)2374e5dd7070Spatrick void Sema::ActOnComment(SourceRange Comment) {
2375e5dd7070Spatrick   if (!LangOpts.RetainCommentsFromSystemHeaders &&
2376e5dd7070Spatrick       SourceMgr.isInSystemHeader(Comment.getBegin()))
2377e5dd7070Spatrick     return;
2378e5dd7070Spatrick   RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
2379e5dd7070Spatrick   if (RC.isAlmostTrailingComment()) {
2380e5dd7070Spatrick     SourceRange MagicMarkerRange(Comment.getBegin(),
2381e5dd7070Spatrick                                  Comment.getBegin().getLocWithOffset(3));
2382e5dd7070Spatrick     StringRef MagicMarkerText;
2383e5dd7070Spatrick     switch (RC.getKind()) {
2384e5dd7070Spatrick     case RawComment::RCK_OrdinaryBCPL:
2385e5dd7070Spatrick       MagicMarkerText = "///<";
2386e5dd7070Spatrick       break;
2387e5dd7070Spatrick     case RawComment::RCK_OrdinaryC:
2388e5dd7070Spatrick       MagicMarkerText = "/**<";
2389e5dd7070Spatrick       break;
2390e5dd7070Spatrick     default:
2391e5dd7070Spatrick       llvm_unreachable("if this is an almost Doxygen comment, "
2392e5dd7070Spatrick                        "it should be ordinary");
2393e5dd7070Spatrick     }
2394e5dd7070Spatrick     Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
2395e5dd7070Spatrick       FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
2396e5dd7070Spatrick   }
2397e5dd7070Spatrick   Context.addComment(RC);
2398e5dd7070Spatrick }
2399e5dd7070Spatrick 
2400e5dd7070Spatrick // Pin this vtable to this file.
~ExternalSemaSource()2401e5dd7070Spatrick ExternalSemaSource::~ExternalSemaSource() {}
2402e5dd7070Spatrick char ExternalSemaSource::ID;
2403e5dd7070Spatrick 
ReadMethodPool(Selector Sel)2404e5dd7070Spatrick void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
updateOutOfDateSelector(Selector Sel)2405e5dd7070Spatrick void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
2406e5dd7070Spatrick 
ReadKnownNamespaces(SmallVectorImpl<NamespaceDecl * > & Namespaces)2407e5dd7070Spatrick void ExternalSemaSource::ReadKnownNamespaces(
2408e5dd7070Spatrick                            SmallVectorImpl<NamespaceDecl *> &Namespaces) {
2409e5dd7070Spatrick }
2410e5dd7070Spatrick 
ReadUndefinedButUsed(llvm::MapVector<NamedDecl *,SourceLocation> & Undefined)2411e5dd7070Spatrick void ExternalSemaSource::ReadUndefinedButUsed(
2412e5dd7070Spatrick     llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
2413e5dd7070Spatrick 
ReadMismatchingDeleteExpressions(llvm::MapVector<FieldDecl *,llvm::SmallVector<std::pair<SourceLocation,bool>,4>> &)2414e5dd7070Spatrick void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
2415e5dd7070Spatrick     FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
2416e5dd7070Spatrick 
2417e5dd7070Spatrick /// Figure out if an expression could be turned into a call.
2418e5dd7070Spatrick ///
2419e5dd7070Spatrick /// Use this when trying to recover from an error where the programmer may have
2420e5dd7070Spatrick /// written just the name of a function instead of actually calling it.
2421e5dd7070Spatrick ///
2422e5dd7070Spatrick /// \param E - The expression to examine.
2423e5dd7070Spatrick /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
2424e5dd7070Spatrick ///  with no arguments, this parameter is set to the type returned by such a
2425e5dd7070Spatrick ///  call; otherwise, it is set to an empty QualType.
2426e5dd7070Spatrick /// \param OverloadSet - If the expression is an overloaded function
2427e5dd7070Spatrick ///  name, this parameter is populated with the decls of the various overloads.
tryExprAsCall(Expr & E,QualType & ZeroArgCallReturnTy,UnresolvedSetImpl & OverloadSet)2428e5dd7070Spatrick bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
2429e5dd7070Spatrick                          UnresolvedSetImpl &OverloadSet) {
2430e5dd7070Spatrick   ZeroArgCallReturnTy = QualType();
2431e5dd7070Spatrick   OverloadSet.clear();
2432e5dd7070Spatrick 
2433e5dd7070Spatrick   const OverloadExpr *Overloads = nullptr;
2434e5dd7070Spatrick   bool IsMemExpr = false;
2435e5dd7070Spatrick   if (E.getType() == Context.OverloadTy) {
2436e5dd7070Spatrick     OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
2437e5dd7070Spatrick 
2438e5dd7070Spatrick     // Ignore overloads that are pointer-to-member constants.
2439e5dd7070Spatrick     if (FR.HasFormOfMemberPointer)
2440e5dd7070Spatrick       return false;
2441e5dd7070Spatrick 
2442e5dd7070Spatrick     Overloads = FR.Expression;
2443e5dd7070Spatrick   } else if (E.getType() == Context.BoundMemberTy) {
2444e5dd7070Spatrick     Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
2445e5dd7070Spatrick     IsMemExpr = true;
2446e5dd7070Spatrick   }
2447e5dd7070Spatrick 
2448e5dd7070Spatrick   bool Ambiguous = false;
2449e5dd7070Spatrick   bool IsMV = false;
2450e5dd7070Spatrick 
2451e5dd7070Spatrick   if (Overloads) {
2452e5dd7070Spatrick     for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
2453e5dd7070Spatrick          DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
2454e5dd7070Spatrick       OverloadSet.addDecl(*it);
2455e5dd7070Spatrick 
2456e5dd7070Spatrick       // Check whether the function is a non-template, non-member which takes no
2457e5dd7070Spatrick       // arguments.
2458e5dd7070Spatrick       if (IsMemExpr)
2459e5dd7070Spatrick         continue;
2460e5dd7070Spatrick       if (const FunctionDecl *OverloadDecl
2461e5dd7070Spatrick             = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
2462e5dd7070Spatrick         if (OverloadDecl->getMinRequiredArguments() == 0) {
2463e5dd7070Spatrick           if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
2464e5dd7070Spatrick               (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
2465e5dd7070Spatrick                           OverloadDecl->isCPUSpecificMultiVersion()))) {
2466e5dd7070Spatrick             ZeroArgCallReturnTy = QualType();
2467e5dd7070Spatrick             Ambiguous = true;
2468e5dd7070Spatrick           } else {
2469e5dd7070Spatrick             ZeroArgCallReturnTy = OverloadDecl->getReturnType();
2470e5dd7070Spatrick             IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
2471e5dd7070Spatrick                    OverloadDecl->isCPUSpecificMultiVersion();
2472e5dd7070Spatrick           }
2473e5dd7070Spatrick         }
2474e5dd7070Spatrick       }
2475e5dd7070Spatrick     }
2476e5dd7070Spatrick 
2477e5dd7070Spatrick     // If it's not a member, use better machinery to try to resolve the call
2478e5dd7070Spatrick     if (!IsMemExpr)
2479e5dd7070Spatrick       return !ZeroArgCallReturnTy.isNull();
2480e5dd7070Spatrick   }
2481e5dd7070Spatrick 
2482e5dd7070Spatrick   // Attempt to call the member with no arguments - this will correctly handle
2483e5dd7070Spatrick   // member templates with defaults/deduction of template arguments, overloads
2484e5dd7070Spatrick   // with default arguments, etc.
2485e5dd7070Spatrick   if (IsMemExpr && !E.isTypeDependent()) {
2486e5dd7070Spatrick     Sema::TentativeAnalysisScope Trap(*this);
2487e5dd7070Spatrick     ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
2488*12c85518Srobert                                              std::nullopt, SourceLocation());
2489e5dd7070Spatrick     if (R.isUsable()) {
2490e5dd7070Spatrick       ZeroArgCallReturnTy = R.get()->getType();
2491e5dd7070Spatrick       return true;
2492e5dd7070Spatrick     }
2493e5dd7070Spatrick     return false;
2494e5dd7070Spatrick   }
2495e5dd7070Spatrick 
2496e5dd7070Spatrick   if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
2497e5dd7070Spatrick     if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
2498e5dd7070Spatrick       if (Fun->getMinRequiredArguments() == 0)
2499e5dd7070Spatrick         ZeroArgCallReturnTy = Fun->getReturnType();
2500e5dd7070Spatrick       return true;
2501e5dd7070Spatrick     }
2502e5dd7070Spatrick   }
2503e5dd7070Spatrick 
2504e5dd7070Spatrick   // We don't have an expression that's convenient to get a FunctionDecl from,
2505e5dd7070Spatrick   // but we can at least check if the type is "function of 0 arguments".
2506e5dd7070Spatrick   QualType ExprTy = E.getType();
2507e5dd7070Spatrick   const FunctionType *FunTy = nullptr;
2508e5dd7070Spatrick   QualType PointeeTy = ExprTy->getPointeeType();
2509e5dd7070Spatrick   if (!PointeeTy.isNull())
2510e5dd7070Spatrick     FunTy = PointeeTy->getAs<FunctionType>();
2511e5dd7070Spatrick   if (!FunTy)
2512e5dd7070Spatrick     FunTy = ExprTy->getAs<FunctionType>();
2513e5dd7070Spatrick 
2514e5dd7070Spatrick   if (const FunctionProtoType *FPT =
2515e5dd7070Spatrick       dyn_cast_or_null<FunctionProtoType>(FunTy)) {
2516e5dd7070Spatrick     if (FPT->getNumParams() == 0)
2517e5dd7070Spatrick       ZeroArgCallReturnTy = FunTy->getReturnType();
2518e5dd7070Spatrick     return true;
2519e5dd7070Spatrick   }
2520e5dd7070Spatrick   return false;
2521e5dd7070Spatrick }
2522e5dd7070Spatrick 
2523e5dd7070Spatrick /// Give notes for a set of overloads.
2524e5dd7070Spatrick ///
2525e5dd7070Spatrick /// A companion to tryExprAsCall. In cases when the name that the programmer
2526e5dd7070Spatrick /// wrote was an overloaded function, we may be able to make some guesses about
2527e5dd7070Spatrick /// plausible overloads based on their return types; such guesses can be handed
2528e5dd7070Spatrick /// off to this method to be emitted as notes.
2529e5dd7070Spatrick ///
2530e5dd7070Spatrick /// \param Overloads - The overloads to note.
2531e5dd7070Spatrick /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
2532e5dd7070Spatrick ///  -fshow-overloads=best, this is the location to attach to the note about too
2533e5dd7070Spatrick ///  many candidates. Typically this will be the location of the original
2534e5dd7070Spatrick ///  ill-formed expression.
noteOverloads(Sema & S,const UnresolvedSetImpl & Overloads,const SourceLocation FinalNoteLoc)2535e5dd7070Spatrick static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
2536e5dd7070Spatrick                           const SourceLocation FinalNoteLoc) {
2537a9ac8606Spatrick   unsigned ShownOverloads = 0;
2538a9ac8606Spatrick   unsigned SuppressedOverloads = 0;
2539e5dd7070Spatrick   for (UnresolvedSetImpl::iterator It = Overloads.begin(),
2540e5dd7070Spatrick        DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2541a9ac8606Spatrick     if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) {
2542e5dd7070Spatrick       ++SuppressedOverloads;
2543e5dd7070Spatrick       continue;
2544e5dd7070Spatrick     }
2545e5dd7070Spatrick 
2546e5dd7070Spatrick     NamedDecl *Fn = (*It)->getUnderlyingDecl();
2547e5dd7070Spatrick     // Don't print overloads for non-default multiversioned functions.
2548e5dd7070Spatrick     if (const auto *FD = Fn->getAsFunction()) {
2549e5dd7070Spatrick       if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
2550e5dd7070Spatrick           !FD->getAttr<TargetAttr>()->isDefaultVersion())
2551e5dd7070Spatrick         continue;
2552*12c85518Srobert       if (FD->isMultiVersion() && FD->hasAttr<TargetVersionAttr>() &&
2553*12c85518Srobert           !FD->getAttr<TargetVersionAttr>()->isDefaultVersion())
2554*12c85518Srobert         continue;
2555e5dd7070Spatrick     }
2556e5dd7070Spatrick     S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
2557e5dd7070Spatrick     ++ShownOverloads;
2558e5dd7070Spatrick   }
2559e5dd7070Spatrick 
2560a9ac8606Spatrick   S.Diags.overloadCandidatesShown(ShownOverloads);
2561a9ac8606Spatrick 
2562e5dd7070Spatrick   if (SuppressedOverloads)
2563e5dd7070Spatrick     S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
2564e5dd7070Spatrick       << SuppressedOverloads;
2565e5dd7070Spatrick }
2566e5dd7070Spatrick 
notePlausibleOverloads(Sema & S,SourceLocation Loc,const UnresolvedSetImpl & Overloads,bool (* IsPlausibleResult)(QualType))2567e5dd7070Spatrick static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
2568e5dd7070Spatrick                                    const UnresolvedSetImpl &Overloads,
2569e5dd7070Spatrick                                    bool (*IsPlausibleResult)(QualType)) {
2570e5dd7070Spatrick   if (!IsPlausibleResult)
2571e5dd7070Spatrick     return noteOverloads(S, Overloads, Loc);
2572e5dd7070Spatrick 
2573e5dd7070Spatrick   UnresolvedSet<2> PlausibleOverloads;
2574e5dd7070Spatrick   for (OverloadExpr::decls_iterator It = Overloads.begin(),
2575e5dd7070Spatrick          DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2576e5dd7070Spatrick     const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
2577e5dd7070Spatrick     QualType OverloadResultTy = OverloadDecl->getReturnType();
2578e5dd7070Spatrick     if (IsPlausibleResult(OverloadResultTy))
2579e5dd7070Spatrick       PlausibleOverloads.addDecl(It.getDecl());
2580e5dd7070Spatrick   }
2581e5dd7070Spatrick   noteOverloads(S, PlausibleOverloads, Loc);
2582e5dd7070Spatrick }
2583e5dd7070Spatrick 
2584e5dd7070Spatrick /// Determine whether the given expression can be called by just
2585e5dd7070Spatrick /// putting parentheses after it.  Notably, expressions with unary
2586e5dd7070Spatrick /// operators can't be because the unary operator will start parsing
2587e5dd7070Spatrick /// outside the call.
IsCallableWithAppend(Expr * E)2588e5dd7070Spatrick static bool IsCallableWithAppend(Expr *E) {
2589e5dd7070Spatrick   E = E->IgnoreImplicit();
2590e5dd7070Spatrick   return (!isa<CStyleCastExpr>(E) &&
2591e5dd7070Spatrick           !isa<UnaryOperator>(E) &&
2592e5dd7070Spatrick           !isa<BinaryOperator>(E) &&
2593e5dd7070Spatrick           !isa<CXXOperatorCallExpr>(E));
2594e5dd7070Spatrick }
2595e5dd7070Spatrick 
IsCPUDispatchCPUSpecificMultiVersion(const Expr * E)2596e5dd7070Spatrick static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {
2597e5dd7070Spatrick   if (const auto *UO = dyn_cast<UnaryOperator>(E))
2598e5dd7070Spatrick     E = UO->getSubExpr();
2599e5dd7070Spatrick 
2600e5dd7070Spatrick   if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2601e5dd7070Spatrick     if (ULE->getNumDecls() == 0)
2602e5dd7070Spatrick       return false;
2603e5dd7070Spatrick 
2604e5dd7070Spatrick     const NamedDecl *ND = *ULE->decls_begin();
2605e5dd7070Spatrick     if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2606e5dd7070Spatrick       return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();
2607e5dd7070Spatrick   }
2608e5dd7070Spatrick   return false;
2609e5dd7070Spatrick }
2610e5dd7070Spatrick 
tryToRecoverWithCall(ExprResult & E,const PartialDiagnostic & PD,bool ForceComplain,bool (* IsPlausibleResult)(QualType))2611e5dd7070Spatrick bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
2612e5dd7070Spatrick                                 bool ForceComplain,
2613e5dd7070Spatrick                                 bool (*IsPlausibleResult)(QualType)) {
2614e5dd7070Spatrick   SourceLocation Loc = E.get()->getExprLoc();
2615e5dd7070Spatrick   SourceRange Range = E.get()->getSourceRange();
2616e5dd7070Spatrick   UnresolvedSet<4> Overloads;
2617*12c85518Srobert 
2618*12c85518Srobert   // If this is a SFINAE context, don't try anything that might trigger ADL
2619*12c85518Srobert   // prematurely.
2620*12c85518Srobert   if (!isSFINAEContext()) {
2621*12c85518Srobert     QualType ZeroArgCallTy;
2622e5dd7070Spatrick     if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
2623e5dd7070Spatrick         !ZeroArgCallTy.isNull() &&
2624e5dd7070Spatrick         (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
2625e5dd7070Spatrick       // At this point, we know E is potentially callable with 0
2626e5dd7070Spatrick       // arguments and that it returns something of a reasonable type,
2627e5dd7070Spatrick       // so we can emit a fixit and carry on pretending that E was
2628e5dd7070Spatrick       // actually a CallExpr.
2629e5dd7070Spatrick       SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
2630e5dd7070Spatrick       bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2631e5dd7070Spatrick       Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
2632e5dd7070Spatrick                     << (IsCallableWithAppend(E.get())
2633*12c85518Srobert                             ? FixItHint::CreateInsertion(ParenInsertionLoc,
2634*12c85518Srobert                                                          "()")
2635e5dd7070Spatrick                             : FixItHint());
2636e5dd7070Spatrick       if (!IsMV)
2637e5dd7070Spatrick         notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2638e5dd7070Spatrick 
2639e5dd7070Spatrick       // FIXME: Try this before emitting the fixit, and suppress diagnostics
2640e5dd7070Spatrick       // while doing so.
2641*12c85518Srobert       E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), std::nullopt,
2642e5dd7070Spatrick                         Range.getEnd().getLocWithOffset(1));
2643e5dd7070Spatrick       return true;
2644e5dd7070Spatrick     }
2645*12c85518Srobert   }
2646e5dd7070Spatrick   if (!ForceComplain) return false;
2647e5dd7070Spatrick 
2648e5dd7070Spatrick   bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2649e5dd7070Spatrick   Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
2650e5dd7070Spatrick   if (!IsMV)
2651e5dd7070Spatrick     notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2652e5dd7070Spatrick   E = ExprError();
2653e5dd7070Spatrick   return true;
2654e5dd7070Spatrick }
2655e5dd7070Spatrick 
getSuperIdentifier() const2656e5dd7070Spatrick IdentifierInfo *Sema::getSuperIdentifier() const {
2657e5dd7070Spatrick   if (!Ident_super)
2658e5dd7070Spatrick     Ident_super = &Context.Idents.get("super");
2659e5dd7070Spatrick   return Ident_super;
2660e5dd7070Spatrick }
2661e5dd7070Spatrick 
getFloat128Identifier() const2662e5dd7070Spatrick IdentifierInfo *Sema::getFloat128Identifier() const {
2663e5dd7070Spatrick   if (!Ident___float128)
2664e5dd7070Spatrick     Ident___float128 = &Context.Idents.get("__float128");
2665e5dd7070Spatrick   return Ident___float128;
2666e5dd7070Spatrick }
2667e5dd7070Spatrick 
PushCapturedRegionScope(Scope * S,CapturedDecl * CD,RecordDecl * RD,CapturedRegionKind K,unsigned OpenMPCaptureLevel)2668e5dd7070Spatrick void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
2669e5dd7070Spatrick                                    CapturedRegionKind K,
2670e5dd7070Spatrick                                    unsigned OpenMPCaptureLevel) {
2671e5dd7070Spatrick   auto *CSI = new CapturedRegionScopeInfo(
2672e5dd7070Spatrick       getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
2673e5dd7070Spatrick       (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0,
2674e5dd7070Spatrick       OpenMPCaptureLevel);
2675e5dd7070Spatrick   CSI->ReturnType = Context.VoidTy;
2676e5dd7070Spatrick   FunctionScopes.push_back(CSI);
2677e5dd7070Spatrick }
2678e5dd7070Spatrick 
getCurCapturedRegion()2679e5dd7070Spatrick CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
2680e5dd7070Spatrick   if (FunctionScopes.empty())
2681e5dd7070Spatrick     return nullptr;
2682e5dd7070Spatrick 
2683e5dd7070Spatrick   return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
2684e5dd7070Spatrick }
2685e5dd7070Spatrick 
2686e5dd7070Spatrick const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
getMismatchingDeleteExpressions() const2687e5dd7070Spatrick Sema::getMismatchingDeleteExpressions() const {
2688e5dd7070Spatrick   return DeleteExprs;
2689e5dd7070Spatrick }
2690*12c85518Srobert 
FPFeaturesStateRAII(Sema & S)2691*12c85518Srobert Sema::FPFeaturesStateRAII::FPFeaturesStateRAII(Sema &S)
2692*12c85518Srobert     : S(S), OldFPFeaturesState(S.CurFPFeatures),
2693*12c85518Srobert       OldOverrides(S.FpPragmaStack.CurrentValue),
2694*12c85518Srobert       OldEvalMethod(S.PP.getCurrentFPEvalMethod()),
2695*12c85518Srobert       OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {}
2696*12c85518Srobert 
~FPFeaturesStateRAII()2697*12c85518Srobert Sema::FPFeaturesStateRAII::~FPFeaturesStateRAII() {
2698*12c85518Srobert   S.CurFPFeatures = OldFPFeaturesState;
2699*12c85518Srobert   S.FpPragmaStack.CurrentValue = OldOverrides;
2700*12c85518Srobert   S.PP.setCurrentFPEvalMethod(OldFPPragmaLocation, OldEvalMethod);
2701*12c85518Srobert }
2702*12c85518Srobert 
isDeclaratorFunctionLike(Declarator & D)2703*12c85518Srobert bool Sema::isDeclaratorFunctionLike(Declarator &D) {
2704*12c85518Srobert   assert(D.getCXXScopeSpec().isSet() &&
2705*12c85518Srobert          "can only be called for qualified names");
2706*12c85518Srobert 
2707*12c85518Srobert   auto LR = LookupResult(*this, D.getIdentifier(), D.getBeginLoc(),
2708*12c85518Srobert                          LookupOrdinaryName, forRedeclarationInCurContext());
2709*12c85518Srobert   DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(),
2710*12c85518Srobert                                        !D.getDeclSpec().isFriendSpecified());
2711*12c85518Srobert   if (!DC)
2712*12c85518Srobert     return false;
2713*12c85518Srobert 
2714*12c85518Srobert   LookupQualifiedName(LR, DC);
2715*12c85518Srobert   bool Result = std::all_of(LR.begin(), LR.end(), [](Decl *Dcl) {
2716*12c85518Srobert     if (NamedDecl *ND = dyn_cast<NamedDecl>(Dcl)) {
2717*12c85518Srobert       ND = ND->getUnderlyingDecl();
2718*12c85518Srobert       return isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
2719*12c85518Srobert              isa<UsingDecl>(ND);
2720*12c85518Srobert     }
2721*12c85518Srobert     return false;
2722*12c85518Srobert   });
2723*12c85518Srobert   return Result;
2724*12c85518Srobert }
2725