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