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