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