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