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