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