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