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