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