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