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