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