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