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