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