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