]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/Sema.cpp
Merge llvm, clang, lld and lldb trunk r300890, and update build glue.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / Sema.cpp
1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the actions class which performs semantic analysis and
11 // builds an AST out of a parse stream.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclFriend.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/HeaderSearch.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Sema/CXXFieldCollector.h"
29 #include "clang/Sema/DelayedDiagnostic.h"
30 #include "clang/Sema/ExternalSemaSource.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/MultiplexExternalSemaSource.h"
33 #include "clang/Sema/ObjCMethodList.h"
34 #include "clang/Sema/PrettyDeclStackTrace.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 "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/SmallSet.h"
42 using namespace clang;
43 using namespace sema;
44
45 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
46   return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
47 }
48
49 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
50
51 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
52                                        const Preprocessor &PP) {
53   PrintingPolicy Policy = Context.getPrintingPolicy();
54   // Our printing policy is copied over the ASTContext printing policy whenever
55   // a diagnostic is emitted, so recompute it.
56   Policy.Bool = Context.getLangOpts().Bool;
57   if (!Policy.Bool) {
58     if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
59       Policy.Bool = BoolMacro->isObjectLike() &&
60                     BoolMacro->getNumTokens() == 1 &&
61                     BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
62     }
63   }
64
65   return Policy;
66 }
67
68 void Sema::ActOnTranslationUnitScope(Scope *S) {
69   TUScope = S;
70   PushDeclContext(S, Context.getTranslationUnitDecl());
71 }
72
73 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
74            TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
75     : ExternalSource(nullptr), isMultiplexExternalSource(false),
76       FPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
77       Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
78       SourceMgr(PP.getSourceManager()), CollectStats(false),
79       CodeCompleter(CodeCompleter), CurContext(nullptr),
80       OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
81       MSPointerToMemberRepresentationMethod(
82           LangOpts.getMSPointerToMemberRepresentationMethod()),
83       VtorDispStack(MSVtorDispAttr::Mode(LangOpts.VtorDispMode)), PackStack(0),
84       DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
85       CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr),
86       PragmaAttributeCurrentTargetDecl(nullptr),
87       IsBuildingRecoveryCallExpr(false), Cleanup{}, LateTemplateParser(nullptr),
88       LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
89       StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
90       CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr), NSNumberDecl(nullptr),
91       NSValueDecl(nullptr), NSStringDecl(nullptr),
92       StringWithUTF8StringMethod(nullptr),
93       ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
94       ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
95       DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
96       TUKind(TUKind), NumSFINAEErrors(0), CachedFakeTopLevelModule(nullptr),
97       AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
98       NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
99       CurrentInstantiationScope(nullptr), DisableTypoCorrection(false),
100       TyposCorrected(0), AnalysisWarnings(*this),
101       ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
102       CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
103   TUScope = nullptr;
104
105   LoadedExternalKnownNamespaces = false;
106   for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
107     NSNumberLiteralMethods[I] = nullptr;
108
109   if (getLangOpts().ObjC1)
110     NSAPIObj.reset(new NSAPI(Context));
111
112   if (getLangOpts().CPlusPlus)
113     FieldCollector.reset(new CXXFieldCollector());
114
115   // Tell diagnostics how to render things from the AST library.
116   Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
117
118   ExprEvalContexts.emplace_back(
119       ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
120       nullptr, false);
121
122   FunctionScopes.push_back(new FunctionScopeInfo(Diags));
123
124   // Initilization of data sharing attributes stack for OpenMP
125   InitDataSharingAttributesStack();
126 }
127
128 void Sema::addImplicitTypedef(StringRef Name, QualType T) {
129   DeclarationName DN = &Context.Idents.get(Name);
130   if (IdResolver.begin(DN) == IdResolver.end())
131     PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
132 }
133
134 void Sema::Initialize() {
135   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
136     SC->InitializeSema(*this);
137
138   // Tell the external Sema source about this Sema object.
139   if (ExternalSemaSource *ExternalSema
140       = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
141     ExternalSema->InitializeSema(*this);
142
143   // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
144   // will not be able to merge any duplicate __va_list_tag decls correctly.
145   VAListTagName = PP.getIdentifierInfo("__va_list_tag");
146
147   if (!TUScope)
148     return;
149
150   // Initialize predefined 128-bit integer types, if needed.
151   if (Context.getTargetInfo().hasInt128Type()) {
152     // If either of the 128-bit integer types are unavailable to name lookup,
153     // define them now.
154     DeclarationName Int128 = &Context.Idents.get("__int128_t");
155     if (IdResolver.begin(Int128) == IdResolver.end())
156       PushOnScopeChains(Context.getInt128Decl(), TUScope);
157
158     DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
159     if (IdResolver.begin(UInt128) == IdResolver.end())
160       PushOnScopeChains(Context.getUInt128Decl(), TUScope);
161   }
162
163
164   // Initialize predefined Objective-C types:
165   if (getLangOpts().ObjC1) {
166     // If 'SEL' does not yet refer to any declarations, make it refer to the
167     // predefined 'SEL'.
168     DeclarationName SEL = &Context.Idents.get("SEL");
169     if (IdResolver.begin(SEL) == IdResolver.end())
170       PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
171
172     // If 'id' does not yet refer to any declarations, make it refer to the
173     // predefined 'id'.
174     DeclarationName Id = &Context.Idents.get("id");
175     if (IdResolver.begin(Id) == IdResolver.end())
176       PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
177
178     // Create the built-in typedef for 'Class'.
179     DeclarationName Class = &Context.Idents.get("Class");
180     if (IdResolver.begin(Class) == IdResolver.end())
181       PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
182
183     // Create the built-in forward declaratino for 'Protocol'.
184     DeclarationName Protocol = &Context.Idents.get("Protocol");
185     if (IdResolver.begin(Protocol) == IdResolver.end())
186       PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
187   }
188
189   // Create the internal type for the *StringMakeConstantString builtins.
190   DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
191   if (IdResolver.begin(ConstantString) == IdResolver.end())
192     PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
193
194   // Initialize Microsoft "predefined C++ types".
195   if (getLangOpts().MSVCCompat) {
196     if (getLangOpts().CPlusPlus &&
197         IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
198       PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
199                         TUScope);
200
201     addImplicitTypedef("size_t", Context.getSizeType());
202   }
203
204   // Initialize predefined OpenCL types and supported extensions and (optional)
205   // core features.
206   if (getLangOpts().OpenCL) {
207     getOpenCLOptions().addSupport(Context.getTargetInfo().getSupportedOpenCLOpts());
208     getOpenCLOptions().enableSupportedCore(getLangOpts().OpenCLVersion);
209     addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
210     addImplicitTypedef("event_t", Context.OCLEventTy);
211     if (getLangOpts().OpenCLVersion >= 200) {
212       addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
213       addImplicitTypedef("queue_t", Context.OCLQueueTy);
214       addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
215       addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
216       addImplicitTypedef("atomic_uint",
217                          Context.getAtomicType(Context.UnsignedIntTy));
218       auto AtomicLongT = Context.getAtomicType(Context.LongTy);
219       addImplicitTypedef("atomic_long", AtomicLongT);
220       auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
221       addImplicitTypedef("atomic_ulong", AtomicULongT);
222       addImplicitTypedef("atomic_float",
223                          Context.getAtomicType(Context.FloatTy));
224       auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
225       addImplicitTypedef("atomic_double", AtomicDoubleT);
226       // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
227       // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
228       addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
229       auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
230       addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
231       auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
232       addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
233       auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
234       addImplicitTypedef("atomic_size_t", AtomicSizeT);
235       auto AtomicPtrDiffT = Context.getAtomicType(Context.getPointerDiffType());
236       addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
237
238       // OpenCL v2.0 s6.13.11.6:
239       // - The atomic_long and atomic_ulong types are supported if the
240       //   cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
241       //   extensions are supported.
242       // - The atomic_double type is only supported if double precision
243       //   is supported and the cl_khr_int64_base_atomics and
244       //   cl_khr_int64_extended_atomics extensions are supported.
245       // - If the device address space is 64-bits, the data types
246       //   atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
247       //   atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
248       //   cl_khr_int64_extended_atomics extensions are supported.
249       std::vector<QualType> Atomic64BitTypes;
250       Atomic64BitTypes.push_back(AtomicLongT);
251       Atomic64BitTypes.push_back(AtomicULongT);
252       Atomic64BitTypes.push_back(AtomicDoubleT);
253       if (Context.getTypeSize(AtomicSizeT) == 64) {
254         Atomic64BitTypes.push_back(AtomicSizeT);
255         Atomic64BitTypes.push_back(AtomicIntPtrT);
256         Atomic64BitTypes.push_back(AtomicUIntPtrT);
257         Atomic64BitTypes.push_back(AtomicPtrDiffT);
258       }
259       for (auto &I : Atomic64BitTypes)
260         setOpenCLExtensionForType(I,
261             "cl_khr_int64_base_atomics cl_khr_int64_extended_atomics");
262
263       setOpenCLExtensionForType(AtomicDoubleT, "cl_khr_fp64");
264     }
265
266     setOpenCLExtensionForType(Context.DoubleTy, "cl_khr_fp64");
267
268 #define GENERIC_IMAGE_TYPE_EXT(Type, Id, Ext) \
269     setOpenCLExtensionForType(Context.Id, Ext);
270 #include "clang/Basic/OpenCLImageTypes.def"
271     };
272
273   if (Context.getTargetInfo().hasBuiltinMSVaList()) {
274     DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
275     if (IdResolver.begin(MSVaList) == IdResolver.end())
276       PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
277   }
278
279   DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
280   if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
281     PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
282 }
283
284 Sema::~Sema() {
285   if (VisContext) FreeVisContext();
286   // Kill all the active scopes.
287   for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
288     delete FunctionScopes[I];
289   if (FunctionScopes.size() == 1)
290     delete FunctionScopes[0];
291
292   // Tell the SemaConsumer to forget about us; we're going out of scope.
293   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
294     SC->ForgetSema();
295
296   // Detach from the external Sema source.
297   if (ExternalSemaSource *ExternalSema
298         = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
299     ExternalSema->ForgetSema();
300
301   // If Sema's ExternalSource is the multiplexer - we own it.
302   if (isMultiplexExternalSource)
303     delete ExternalSource;
304
305   threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
306
307   // Destroys data sharing attributes stack for OpenMP
308   DestroyDataSharingAttributesStack();
309
310   assert(DelayedTypos.empty() && "Uncorrected typos!");
311 }
312
313 /// makeUnavailableInSystemHeader - There is an error in the current
314 /// context.  If we're still in a system header, and we can plausibly
315 /// make the relevant declaration unavailable instead of erroring, do
316 /// so and return true.
317 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
318                                       UnavailableAttr::ImplicitReason reason) {
319   // If we're not in a function, it's an error.
320   FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
321   if (!fn) return false;
322
323   // If we're in template instantiation, it's an error.
324   if (inTemplateInstantiation())
325     return false;
326
327   // If that function's not in a system header, it's an error.
328   if (!Context.getSourceManager().isInSystemHeader(loc))
329     return false;
330
331   // If the function is already unavailable, it's not an error.
332   if (fn->hasAttr<UnavailableAttr>()) return true;
333
334   fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
335   return true;
336 }
337
338 ASTMutationListener *Sema::getASTMutationListener() const {
339   return getASTConsumer().GetASTMutationListener();
340 }
341
342 ///\brief Registers an external source. If an external source already exists,
343 /// creates a multiplex external source and appends to it.
344 ///
345 ///\param[in] E - A non-null external sema source.
346 ///
347 void Sema::addExternalSource(ExternalSemaSource *E) {
348   assert(E && "Cannot use with NULL ptr");
349
350   if (!ExternalSource) {
351     ExternalSource = E;
352     return;
353   }
354
355   if (isMultiplexExternalSource)
356     static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
357   else {
358     ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
359     isMultiplexExternalSource = true;
360   }
361 }
362
363 /// \brief Print out statistics about the semantic analysis.
364 void Sema::PrintStats() const {
365   llvm::errs() << "\n*** Semantic Analysis Stats:\n";
366   llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
367
368   BumpAlloc.PrintStats();
369   AnalysisWarnings.PrintStats();
370 }
371
372 void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
373                                                QualType SrcType,
374                                                SourceLocation Loc) {
375   Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
376   if (!ExprNullability || *ExprNullability != NullabilityKind::Nullable)
377     return;
378
379   Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
380   if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
381     return;
382
383   Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
384 }
385
386 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
387 /// If there is already an implicit cast, merge into the existing one.
388 /// The result is of the given category.
389 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
390                                    CastKind Kind, ExprValueKind VK,
391                                    const CXXCastPath *BasePath,
392                                    CheckedConversionKind CCK) {
393 #ifndef NDEBUG
394   if (VK == VK_RValue && !E->isRValue()) {
395     switch (Kind) {
396     default:
397       llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
398                        "kind");
399     case CK_LValueToRValue:
400     case CK_ArrayToPointerDecay:
401     case CK_FunctionToPointerDecay:
402     case CK_ToVoid:
403       break;
404     }
405   }
406   assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
407 #endif
408
409   diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getLocStart());
410
411   QualType ExprTy = Context.getCanonicalType(E->getType());
412   QualType TypeTy = Context.getCanonicalType(Ty);
413
414   if (ExprTy == TypeTy)
415     return E;
416
417   // C++1z [conv.array]: The temporary materialization conversion is applied.
418   // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
419   if (Kind == CK_ArrayToPointerDecay && getLangOpts().CPlusPlus &&
420       E->getValueKind() == VK_RValue) {
421     // The temporary is an lvalue in C++98 and an xvalue otherwise.
422     ExprResult Materialized = CreateMaterializeTemporaryExpr(
423         E->getType(), E, !getLangOpts().CPlusPlus11);
424     if (Materialized.isInvalid())
425       return ExprError();
426     E = Materialized.get();
427   }
428
429   if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
430     if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
431       ImpCast->setType(Ty);
432       ImpCast->setValueKind(VK);
433       return E;
434     }
435   }
436
437   return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
438 }
439
440 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
441 /// to the conversion from scalar type ScalarTy to the Boolean type.
442 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
443   switch (ScalarTy->getScalarTypeKind()) {
444   case Type::STK_Bool: return CK_NoOp;
445   case Type::STK_CPointer: return CK_PointerToBoolean;
446   case Type::STK_BlockPointer: return CK_PointerToBoolean;
447   case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
448   case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
449   case Type::STK_Integral: return CK_IntegralToBoolean;
450   case Type::STK_Floating: return CK_FloatingToBoolean;
451   case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
452   case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
453   }
454   return CK_Invalid;
455 }
456
457 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
458 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
459   if (D->getMostRecentDecl()->isUsed())
460     return true;
461
462   if (D->isExternallyVisible())
463     return true;
464
465   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
466     // UnusedFileScopedDecls stores the first declaration.
467     // The declaration may have become definition so check again.
468     const FunctionDecl *DeclToCheck;
469     if (FD->hasBody(DeclToCheck))
470       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
471
472     // Later redecls may add new information resulting in not having to warn,
473     // so check again.
474     DeclToCheck = FD->getMostRecentDecl();
475     if (DeclToCheck != FD)
476       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
477   }
478
479   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
480     // If a variable usable in constant expressions is referenced,
481     // don't warn if it isn't used: if the value of a variable is required
482     // for the computation of a constant expression, it doesn't make sense to
483     // warn even if the variable isn't odr-used.  (isReferenced doesn't
484     // precisely reflect that, but it's a decent approximation.)
485     if (VD->isReferenced() &&
486         VD->isUsableInConstantExpressions(SemaRef->Context))
487       return true;
488
489     // UnusedFileScopedDecls stores the first declaration.
490     // The declaration may have become definition so check again.
491     const VarDecl *DeclToCheck = VD->getDefinition();
492     if (DeclToCheck)
493       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
494
495     // Later redecls may add new information resulting in not having to warn,
496     // so check again.
497     DeclToCheck = VD->getMostRecentDecl();
498     if (DeclToCheck != VD)
499       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
500   }
501
502   return false;
503 }
504
505 /// Obtains a sorted list of functions and variables that are undefined but
506 /// ODR-used.
507 void Sema::getUndefinedButUsed(
508     SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
509   for (const auto &UndefinedUse : UndefinedButUsed) {
510     NamedDecl *ND = UndefinedUse.first;
511
512     // Ignore attributes that have become invalid.
513     if (ND->isInvalidDecl()) continue;
514
515     // __attribute__((weakref)) is basically a definition.
516     if (ND->hasAttr<WeakRefAttr>()) continue;
517
518     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
519       if (FD->isDefined())
520         continue;
521       if (FD->isExternallyVisible() &&
522           !FD->getMostRecentDecl()->isInlined())
523         continue;
524     } else {
525       auto *VD = cast<VarDecl>(ND);
526       if (VD->hasDefinition() != VarDecl::DeclarationOnly)
527         continue;
528       if (VD->isExternallyVisible() && !VD->getMostRecentDecl()->isInline())
529         continue;
530     }
531
532     Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
533   }
534 }
535
536 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
537 /// or that are inline.
538 static void checkUndefinedButUsed(Sema &S) {
539   if (S.UndefinedButUsed.empty()) return;
540
541   // Collect all the still-undefined entities with internal linkage.
542   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
543   S.getUndefinedButUsed(Undefined);
544   if (Undefined.empty()) return;
545
546   for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
547          I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
548     NamedDecl *ND = I->first;
549
550     if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
551       // An exported function will always be emitted when defined, so even if
552       // the function is inline, it doesn't have to be emitted in this TU. An
553       // imported function implies that it has been exported somewhere else.
554       continue;
555     }
556
557     if (!ND->isExternallyVisible()) {
558       S.Diag(ND->getLocation(), diag::warn_undefined_internal)
559         << isa<VarDecl>(ND) << ND;
560     } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
561       (void)FD;
562       assert(FD->getMostRecentDecl()->isInlined() &&
563              "used object requires definition but isn't inline or internal?");
564       // FIXME: This is ill-formed; we should reject.
565       S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND;
566     } else {
567       assert(cast<VarDecl>(ND)->getMostRecentDecl()->isInline() &&
568              "used var requires definition but isn't inline or internal?");
569       S.Diag(ND->getLocation(), diag::err_undefined_inline_var) << ND;
570     }
571     if (I->second.isValid())
572       S.Diag(I->second, diag::note_used_here);
573   }
574
575   S.UndefinedButUsed.clear();
576 }
577
578 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
579   if (!ExternalSource)
580     return;
581
582   SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
583   ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
584   for (auto &WeakID : WeakIDs)
585     WeakUndeclaredIdentifiers.insert(WeakID);
586 }
587
588
589 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
590
591 /// \brief Returns true, if all methods and nested classes of the given
592 /// CXXRecordDecl are defined in this translation unit.
593 ///
594 /// Should only be called from ActOnEndOfTranslationUnit so that all
595 /// definitions are actually read.
596 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
597                                             RecordCompleteMap &MNCComplete) {
598   RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
599   if (Cache != MNCComplete.end())
600     return Cache->second;
601   if (!RD->isCompleteDefinition())
602     return false;
603   bool Complete = true;
604   for (DeclContext::decl_iterator I = RD->decls_begin(),
605                                   E = RD->decls_end();
606        I != E && Complete; ++I) {
607     if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
608       Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M));
609     else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
610       // If the template function is marked as late template parsed at this
611       // point, it has not been instantiated and therefore we have not
612       // performed semantic analysis on it yet, so we cannot know if the type
613       // can be considered complete.
614       Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
615                   F->getTemplatedDecl()->isDefined();
616     else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
617       if (R->isInjectedClassName())
618         continue;
619       if (R->hasDefinition())
620         Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
621                                                    MNCComplete);
622       else
623         Complete = false;
624     }
625   }
626   MNCComplete[RD] = Complete;
627   return Complete;
628 }
629
630 /// \brief Returns true, if the given CXXRecordDecl is fully defined in this
631 /// translation unit, i.e. all methods are defined or pure virtual and all
632 /// friends, friend functions and nested classes are fully defined in this
633 /// translation unit.
634 ///
635 /// Should only be called from ActOnEndOfTranslationUnit so that all
636 /// definitions are actually read.
637 static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
638                                  RecordCompleteMap &RecordsComplete,
639                                  RecordCompleteMap &MNCComplete) {
640   RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
641   if (Cache != RecordsComplete.end())
642     return Cache->second;
643   bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
644   for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
645                                       E = RD->friend_end();
646        I != E && Complete; ++I) {
647     // Check if friend classes and methods are complete.
648     if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
649       // Friend classes are available as the TypeSourceInfo of the FriendDecl.
650       if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
651         Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
652       else
653         Complete = false;
654     } else {
655       // Friend functions are available through the NamedDecl of FriendDecl.
656       if (const FunctionDecl *FD =
657           dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
658         Complete = FD->isDefined();
659       else
660         // This is a template friend, give up.
661         Complete = false;
662     }
663   }
664   RecordsComplete[RD] = Complete;
665   return Complete;
666 }
667
668 void Sema::emitAndClearUnusedLocalTypedefWarnings() {
669   if (ExternalSource)
670     ExternalSource->ReadUnusedLocalTypedefNameCandidates(
671         UnusedLocalTypedefNameCandidates);
672   for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
673     if (TD->isReferenced())
674       continue;
675     Diag(TD->getLocation(), diag::warn_unused_local_typedef)
676         << isa<TypeAliasDecl>(TD) << TD->getDeclName();
677   }
678   UnusedLocalTypedefNameCandidates.clear();
679 }
680
681 /// ActOnEndOfTranslationUnit - This is called at the very end of the
682 /// translation unit when EOF is reached and all but the top-level scope is
683 /// popped.
684 void Sema::ActOnEndOfTranslationUnit() {
685   assert(DelayedDiagnostics.getCurrentPool() == nullptr
686          && "reached end of translation unit with a pool attached?");
687
688   // If code completion is enabled, don't perform any end-of-translation-unit
689   // work.
690   if (PP.isCodeCompletionEnabled())
691     return;
692
693   // Complete translation units and modules define vtables and perform implicit
694   // instantiations. PCH files do not.
695   if (TUKind != TU_Prefix) {
696     DiagnoseUseOfUnimplementedSelectors();
697
698     // If DefinedUsedVTables ends up marking any virtual member functions it
699     // might lead to more pending template instantiations, which we then need
700     // to instantiate.
701     DefineUsedVTables();
702
703     // C++: Perform implicit template instantiations.
704     //
705     // FIXME: When we perform these implicit instantiations, we do not
706     // carefully keep track of the point of instantiation (C++ [temp.point]).
707     // This means that name lookup that occurs within the template
708     // instantiation will always happen at the end of the translation unit,
709     // so it will find some names that are not required to be found. This is
710     // valid, but we could do better by diagnosing if an instantiation uses a
711     // name that was not visible at its first point of instantiation.
712     if (ExternalSource) {
713       // Load pending instantiations from the external source.
714       SmallVector<PendingImplicitInstantiation, 4> Pending;
715       ExternalSource->ReadPendingInstantiations(Pending);
716       PendingInstantiations.insert(PendingInstantiations.begin(),
717                                    Pending.begin(), Pending.end());
718     }
719     PerformPendingInstantiations();
720
721     if (LateTemplateParserCleanup)
722       LateTemplateParserCleanup(OpaqueParser);
723
724     CheckDelayedMemberExceptionSpecs();
725   }
726
727   DiagnoseUnterminatedPragmaAttribute();
728
729   // All delayed member exception specs should be checked or we end up accepting
730   // incompatible declarations.
731   // FIXME: This is wrong for TUKind == TU_Prefix. In that case, we need to
732   // write out the lists to the AST file (if any).
733   assert(DelayedDefaultedMemberExceptionSpecs.empty());
734   assert(DelayedExceptionSpecChecks.empty());
735
736   // All dllexport classes should have been processed already.
737   assert(DelayedDllExportClasses.empty());
738
739   // Remove file scoped decls that turned out to be used.
740   UnusedFileScopedDecls.erase(
741       std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
742                      UnusedFileScopedDecls.end(),
743                      [this](const DeclaratorDecl *DD) {
744                        return ShouldRemoveFromUnused(this, DD);
745                      }),
746       UnusedFileScopedDecls.end());
747
748   if (TUKind == TU_Prefix) {
749     // Translation unit prefixes don't need any of the checking below.
750     if (!PP.isIncrementalProcessingEnabled())
751       TUScope = nullptr;
752     return;
753   }
754
755   // Check for #pragma weak identifiers that were never declared
756   LoadExternalWeakUndeclaredIdentifiers();
757   for (auto WeakID : WeakUndeclaredIdentifiers) {
758     if (WeakID.second.getUsed())
759       continue;
760
761     Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
762                                       LookupOrdinaryName);
763     if (PrevDecl != nullptr &&
764         !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
765       Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
766           << "'weak'" << ExpectedVariableOrFunction;
767     else
768       Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
769           << WeakID.first;
770   }
771
772   if (LangOpts.CPlusPlus11 &&
773       !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
774     CheckDelegatingCtorCycles();
775
776   if (!Diags.hasErrorOccurred()) {
777     if (ExternalSource)
778       ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
779     checkUndefinedButUsed(*this);
780   }
781
782   if (TUKind == TU_Module) {
783     // If we are building a module, resolve all of the exported declarations
784     // now.
785     if (Module *CurrentModule = PP.getCurrentModule()) {
786       ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
787
788       SmallVector<Module *, 2> Stack;
789       Stack.push_back(CurrentModule);
790       while (!Stack.empty()) {
791         Module *Mod = Stack.pop_back_val();
792
793         // Resolve the exported declarations and conflicts.
794         // FIXME: Actually complain, once we figure out how to teach the
795         // diagnostic client to deal with complaints in the module map at this
796         // point.
797         ModMap.resolveExports(Mod, /*Complain=*/false);
798         ModMap.resolveUses(Mod, /*Complain=*/false);
799         ModMap.resolveConflicts(Mod, /*Complain=*/false);
800
801         // Queue the submodules, so their exports will also be resolved.
802         Stack.append(Mod->submodule_begin(), Mod->submodule_end());
803       }
804     }
805
806     // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
807     // modules when they are built, not every time they are used.
808     emitAndClearUnusedLocalTypedefWarnings();
809
810     // Modules don't need any of the checking below.
811     TUScope = nullptr;
812     return;
813   }
814
815   // C99 6.9.2p2:
816   //   A declaration of an identifier for an object that has file
817   //   scope without an initializer, and without a storage-class
818   //   specifier or with the storage-class specifier static,
819   //   constitutes a tentative definition. If a translation unit
820   //   contains one or more tentative definitions for an identifier,
821   //   and the translation unit contains no external definition for
822   //   that identifier, then the behavior is exactly as if the
823   //   translation unit contains a file scope declaration of that
824   //   identifier, with the composite type as of the end of the
825   //   translation unit, with an initializer equal to 0.
826   llvm::SmallSet<VarDecl *, 32> Seen;
827   for (TentativeDefinitionsType::iterator
828             T = TentativeDefinitions.begin(ExternalSource),
829          TEnd = TentativeDefinitions.end();
830        T != TEnd; ++T)
831   {
832     VarDecl *VD = (*T)->getActingDefinition();
833
834     // If the tentative definition was completed, getActingDefinition() returns
835     // null. If we've already seen this variable before, insert()'s second
836     // return value is false.
837     if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
838       continue;
839
840     if (const IncompleteArrayType *ArrayT
841         = Context.getAsIncompleteArrayType(VD->getType())) {
842       // Set the length of the array to 1 (C99 6.9.2p5).
843       Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
844       llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
845       QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
846                                                 One, ArrayType::Normal, 0);
847       VD->setType(T);
848     } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
849                                    diag::err_tentative_def_incomplete_type))
850       VD->setInvalidDecl();
851
852     // No initialization is performed for a tentative definition.
853     CheckCompleteVariableDeclaration(VD);
854
855     // Notify the consumer that we've completed a tentative definition.
856     if (!VD->isInvalidDecl())
857       Consumer.CompleteTentativeDefinition(VD);
858
859   }
860
861   // If there were errors, disable 'unused' warnings since they will mostly be
862   // noise.
863   if (!Diags.hasErrorOccurred()) {
864     // Output warning for unused file scoped decls.
865     for (UnusedFileScopedDeclsType::iterator
866            I = UnusedFileScopedDecls.begin(ExternalSource),
867            E = UnusedFileScopedDecls.end(); I != E; ++I) {
868       if (ShouldRemoveFromUnused(this, *I))
869         continue;
870
871       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
872         const FunctionDecl *DiagD;
873         if (!FD->hasBody(DiagD))
874           DiagD = FD;
875         if (DiagD->isDeleted())
876           continue; // Deleted functions are supposed to be unused.
877         if (DiagD->isReferenced()) {
878           if (isa<CXXMethodDecl>(DiagD))
879             Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
880                   << DiagD->getDeclName();
881           else {
882             if (FD->getStorageClass() == SC_Static &&
883                 !FD->isInlineSpecified() &&
884                 !SourceMgr.isInMainFile(
885                    SourceMgr.getExpansionLoc(FD->getLocation())))
886               Diag(DiagD->getLocation(),
887                    diag::warn_unneeded_static_internal_decl)
888                   << DiagD->getDeclName();
889             else
890               Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
891                    << /*function*/0 << DiagD->getDeclName();
892           }
893         } else {
894           Diag(DiagD->getLocation(),
895                isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
896                                          : diag::warn_unused_function)
897                 << DiagD->getDeclName();
898         }
899       } else {
900         const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
901         if (!DiagD)
902           DiagD = cast<VarDecl>(*I);
903         if (DiagD->isReferenced()) {
904           Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
905                 << /*variable*/1 << DiagD->getDeclName();
906         } else if (DiagD->getType().isConstQualified()) {
907           const SourceManager &SM = SourceMgr;
908           if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
909               !PP.getLangOpts().IsHeaderFile)
910             Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
911                 << DiagD->getDeclName();
912         } else {
913           Diag(DiagD->getLocation(), diag::warn_unused_variable)
914               << DiagD->getDeclName();
915         }
916       }
917     }
918
919     emitAndClearUnusedLocalTypedefWarnings();
920   }
921
922   if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
923     RecordCompleteMap RecordsComplete;
924     RecordCompleteMap MNCComplete;
925     for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
926          E = UnusedPrivateFields.end(); I != E; ++I) {
927       const NamedDecl *D = *I;
928       const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
929       if (RD && !RD->isUnion() &&
930           IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
931         Diag(D->getLocation(), diag::warn_unused_private_field)
932               << D->getDeclName();
933       }
934     }
935   }
936
937   if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
938     if (ExternalSource)
939       ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
940     for (const auto &DeletedFieldInfo : DeleteExprs) {
941       for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
942         AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
943                                   DeleteExprLoc.second);
944       }
945     }
946   }
947
948   // Check we've noticed that we're no longer parsing the initializer for every
949   // variable. If we miss cases, then at best we have a performance issue and
950   // at worst a rejects-valid bug.
951   assert(ParsingInitForAutoVars.empty() &&
952          "Didn't unmark var as having its initializer parsed");
953
954   if (!PP.isIncrementalProcessingEnabled())
955     TUScope = nullptr;
956 }
957
958
959 //===----------------------------------------------------------------------===//
960 // Helper functions.
961 //===----------------------------------------------------------------------===//
962
963 DeclContext *Sema::getFunctionLevelDeclContext() {
964   DeclContext *DC = CurContext;
965
966   while (true) {
967     if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
968       DC = DC->getParent();
969     } else if (isa<CXXMethodDecl>(DC) &&
970                cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
971                cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
972       DC = DC->getParent()->getParent();
973     }
974     else break;
975   }
976
977   return DC;
978 }
979
980 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
981 /// to the function decl for the function being parsed.  If we're currently
982 /// in a 'block', this returns the containing context.
983 FunctionDecl *Sema::getCurFunctionDecl() {
984   DeclContext *DC = getFunctionLevelDeclContext();
985   return dyn_cast<FunctionDecl>(DC);
986 }
987
988 ObjCMethodDecl *Sema::getCurMethodDecl() {
989   DeclContext *DC = getFunctionLevelDeclContext();
990   while (isa<RecordDecl>(DC))
991     DC = DC->getParent();
992   return dyn_cast<ObjCMethodDecl>(DC);
993 }
994
995 NamedDecl *Sema::getCurFunctionOrMethodDecl() {
996   DeclContext *DC = getFunctionLevelDeclContext();
997   if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
998     return cast<NamedDecl>(DC);
999   return nullptr;
1000 }
1001
1002 void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1003   // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1004   // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1005   // been made more painfully obvious by the refactor that introduced this
1006   // function, but it is possible that the incoming argument can be
1007   // eliminated. If it truly cannot be (for example, there is some reentrancy
1008   // issue I am not seeing yet), then there should at least be a clarifying
1009   // comment somewhere.
1010   if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
1011     switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
1012               Diags.getCurrentDiagID())) {
1013     case DiagnosticIDs::SFINAE_Report:
1014       // We'll report the diagnostic below.
1015       break;
1016
1017     case DiagnosticIDs::SFINAE_SubstitutionFailure:
1018       // Count this failure so that we know that template argument deduction
1019       // has failed.
1020       ++NumSFINAEErrors;
1021
1022       // Make a copy of this suppressed diagnostic and store it with the
1023       // template-deduction information.
1024       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1025         Diagnostic DiagInfo(&Diags);
1026         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1027                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1028       }
1029
1030       Diags.setLastDiagnosticIgnored();
1031       Diags.Clear();
1032       return;
1033
1034     case DiagnosticIDs::SFINAE_AccessControl: {
1035       // Per C++ Core Issue 1170, access control is part of SFINAE.
1036       // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1037       // make access control a part of SFINAE for the purposes of checking
1038       // type traits.
1039       if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
1040         break;
1041
1042       SourceLocation Loc = Diags.getCurrentDiagLoc();
1043
1044       // Suppress this diagnostic.
1045       ++NumSFINAEErrors;
1046
1047       // Make a copy of this suppressed diagnostic and store it with the
1048       // template-deduction information.
1049       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1050         Diagnostic DiagInfo(&Diags);
1051         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1052                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1053       }
1054
1055       Diags.setLastDiagnosticIgnored();
1056       Diags.Clear();
1057
1058       // Now the diagnostic state is clear, produce a C++98 compatibility
1059       // warning.
1060       Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1061
1062       // The last diagnostic which Sema produced was ignored. Suppress any
1063       // notes attached to it.
1064       Diags.setLastDiagnosticIgnored();
1065       return;
1066     }
1067
1068     case DiagnosticIDs::SFINAE_Suppress:
1069       // Make a copy of this suppressed diagnostic and store it with the
1070       // template-deduction information;
1071       if (*Info) {
1072         Diagnostic DiagInfo(&Diags);
1073         (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1074                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1075       }
1076
1077       // Suppress this diagnostic.
1078       Diags.setLastDiagnosticIgnored();
1079       Diags.Clear();
1080       return;
1081     }
1082   }
1083
1084   // Set up the context's printing policy based on our current state.
1085   Context.setPrintingPolicy(getPrintingPolicy());
1086
1087   // Emit the diagnostic.
1088   if (!Diags.EmitCurrentDiagnostic())
1089     return;
1090
1091   // If this is not a note, and we're in a template instantiation
1092   // that is different from the last template instantiation where
1093   // we emitted an error, print a template instantiation
1094   // backtrace.
1095   if (!DiagnosticIDs::isBuiltinNote(DiagID))
1096     PrintContextStack();
1097 }
1098
1099 Sema::SemaDiagnosticBuilder
1100 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
1101   SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
1102   PD.Emit(Builder);
1103
1104   return Builder;
1105 }
1106
1107 /// \brief Looks through the macro-expansion chain for the given
1108 /// location, looking for a macro expansion with the given name.
1109 /// If one is found, returns true and sets the location to that
1110 /// expansion loc.
1111 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
1112   SourceLocation loc = locref;
1113   if (!loc.isMacroID()) return false;
1114
1115   // There's no good way right now to look at the intermediate
1116   // expansions, so just jump to the expansion location.
1117   loc = getSourceManager().getExpansionLoc(loc);
1118
1119   // If that's written with the name, stop here.
1120   SmallVector<char, 16> buffer;
1121   if (getPreprocessor().getSpelling(loc, buffer) == name) {
1122     locref = loc;
1123     return true;
1124   }
1125   return false;
1126 }
1127
1128 /// \brief Determines the active Scope associated with the given declaration
1129 /// context.
1130 ///
1131 /// This routine maps a declaration context to the active Scope object that
1132 /// represents that declaration context in the parser. It is typically used
1133 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1134 /// declarations) that injects a name for name-lookup purposes and, therefore,
1135 /// must update the Scope.
1136 ///
1137 /// \returns The scope corresponding to the given declaraion context, or NULL
1138 /// if no such scope is open.
1139 Scope *Sema::getScopeForContext(DeclContext *Ctx) {
1140
1141   if (!Ctx)
1142     return nullptr;
1143
1144   Ctx = Ctx->getPrimaryContext();
1145   for (Scope *S = getCurScope(); S; S = S->getParent()) {
1146     // Ignore scopes that cannot have declarations. This is important for
1147     // out-of-line definitions of static class members.
1148     if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
1149       if (DeclContext *Entity = S->getEntity())
1150         if (Ctx == Entity->getPrimaryContext())
1151           return S;
1152   }
1153
1154   return nullptr;
1155 }
1156
1157 /// \brief Enter a new function scope
1158 void Sema::PushFunctionScope() {
1159   if (FunctionScopes.size() == 1) {
1160     // Use the "top" function scope rather than having to allocate
1161     // memory for a new scope.
1162     FunctionScopes.back()->Clear();
1163     FunctionScopes.push_back(FunctionScopes.back());
1164     return;
1165   }
1166
1167   FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
1168 }
1169
1170 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
1171   FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
1172                                               BlockScope, Block));
1173 }
1174
1175 LambdaScopeInfo *Sema::PushLambdaScope() {
1176   LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
1177   FunctionScopes.push_back(LSI);
1178   return LSI;
1179 }
1180
1181 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
1182   if (LambdaScopeInfo *const LSI = getCurLambda()) {
1183     LSI->AutoTemplateParameterDepth = Depth;
1184     return;
1185   } 
1186   llvm_unreachable( 
1187       "Remove assertion if intentionally called in a non-lambda context.");
1188 }
1189
1190 void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
1191                                 const Decl *D, const BlockExpr *blkExpr) {
1192   FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
1193   assert(!FunctionScopes.empty() && "mismatched push/pop!");
1194
1195   // Issue any analysis-based warnings.
1196   if (WP && D)
1197     AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
1198   else
1199     for (const auto &PUD : Scope->PossiblyUnreachableDiags)
1200       Diag(PUD.Loc, PUD.PD);
1201
1202   if (FunctionScopes.back() != Scope)
1203     delete Scope;
1204 }
1205
1206 void Sema::PushCompoundScope() {
1207   getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo());
1208 }
1209
1210 void Sema::PopCompoundScope() {
1211   FunctionScopeInfo *CurFunction = getCurFunction();
1212   assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
1213
1214   CurFunction->CompoundScopes.pop_back();
1215 }
1216
1217 /// \brief Determine whether any errors occurred within this function/method/
1218 /// block.
1219 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
1220   return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
1221 }
1222
1223 BlockScopeInfo *Sema::getCurBlock() {
1224   if (FunctionScopes.empty())
1225     return nullptr;
1226
1227   auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
1228   if (CurBSI && CurBSI->TheDecl &&
1229       !CurBSI->TheDecl->Encloses(CurContext)) {
1230     // We have switched contexts due to template instantiation.
1231     assert(!CodeSynthesisContexts.empty());
1232     return nullptr;
1233   }
1234
1235   return CurBSI;
1236 }
1237
1238 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
1239   if (FunctionScopes.empty())
1240     return nullptr;
1241
1242   auto I = FunctionScopes.rbegin();
1243   if (IgnoreNonLambdaCapturingScope) {
1244     auto E = FunctionScopes.rend();
1245     while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
1246       ++I;
1247     if (I == E)
1248       return nullptr;
1249   }
1250   auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
1251   if (CurLSI && CurLSI->Lambda &&
1252       !CurLSI->Lambda->Encloses(CurContext)) {
1253     // We have switched contexts due to template instantiation.
1254     assert(!CodeSynthesisContexts.empty());
1255     return nullptr;
1256   }
1257
1258   return CurLSI;
1259 }
1260 // We have a generic lambda if we parsed auto parameters, or we have 
1261 // an associated template parameter list.
1262 LambdaScopeInfo *Sema::getCurGenericLambda() {
1263   if (LambdaScopeInfo *LSI =  getCurLambda()) {
1264     return (LSI->AutoTemplateParams.size() ||
1265                     LSI->GLTemplateParameterList) ? LSI : nullptr;
1266   }
1267   return nullptr;
1268 }
1269
1270
1271 void Sema::ActOnComment(SourceRange Comment) {
1272   if (!LangOpts.RetainCommentsFromSystemHeaders &&
1273       SourceMgr.isInSystemHeader(Comment.getBegin()))
1274     return;
1275   RawComment RC(SourceMgr, Comment, false,
1276                 LangOpts.CommentOpts.ParseAllComments);
1277   if (RC.isAlmostTrailingComment()) {
1278     SourceRange MagicMarkerRange(Comment.getBegin(),
1279                                  Comment.getBegin().getLocWithOffset(3));
1280     StringRef MagicMarkerText;
1281     switch (RC.getKind()) {
1282     case RawComment::RCK_OrdinaryBCPL:
1283       MagicMarkerText = "///<";
1284       break;
1285     case RawComment::RCK_OrdinaryC:
1286       MagicMarkerText = "/**<";
1287       break;
1288     default:
1289       llvm_unreachable("if this is an almost Doxygen comment, "
1290                        "it should be ordinary");
1291     }
1292     Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
1293       FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
1294   }
1295   Context.addComment(RC);
1296 }
1297
1298 // Pin this vtable to this file.
1299 ExternalSemaSource::~ExternalSemaSource() {}
1300
1301 void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
1302 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
1303
1304 void ExternalSemaSource::ReadKnownNamespaces(
1305                            SmallVectorImpl<NamespaceDecl *> &Namespaces) {
1306 }
1307
1308 void ExternalSemaSource::ReadUndefinedButUsed(
1309     llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
1310
1311 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
1312     FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
1313
1314 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
1315   SourceLocation Loc = this->Loc;
1316   if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
1317   if (Loc.isValid()) {
1318     Loc.print(OS, S.getSourceManager());
1319     OS << ": ";
1320   }
1321   OS << Message;
1322
1323   if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
1324     OS << " '";
1325     ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(), true);
1326     OS << "'";
1327   }
1328
1329   OS << '\n';
1330 }
1331
1332 /// \brief Figure out if an expression could be turned into a call.
1333 ///
1334 /// Use this when trying to recover from an error where the programmer may have
1335 /// written just the name of a function instead of actually calling it.
1336 ///
1337 /// \param E - The expression to examine.
1338 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1339 ///  with no arguments, this parameter is set to the type returned by such a
1340 ///  call; otherwise, it is set to an empty QualType.
1341 /// \param OverloadSet - If the expression is an overloaded function
1342 ///  name, this parameter is populated with the decls of the various overloads.
1343 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1344                          UnresolvedSetImpl &OverloadSet) {
1345   ZeroArgCallReturnTy = QualType();
1346   OverloadSet.clear();
1347
1348   const OverloadExpr *Overloads = nullptr;
1349   bool IsMemExpr = false;
1350   if (E.getType() == Context.OverloadTy) {
1351     OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
1352
1353     // Ignore overloads that are pointer-to-member constants.
1354     if (FR.HasFormOfMemberPointer)
1355       return false;
1356
1357     Overloads = FR.Expression;
1358   } else if (E.getType() == Context.BoundMemberTy) {
1359     Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
1360     IsMemExpr = true;
1361   }
1362
1363   bool Ambiguous = false;
1364
1365   if (Overloads) {
1366     for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
1367          DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
1368       OverloadSet.addDecl(*it);
1369
1370       // Check whether the function is a non-template, non-member which takes no
1371       // arguments.
1372       if (IsMemExpr)
1373         continue;
1374       if (const FunctionDecl *OverloadDecl
1375             = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
1376         if (OverloadDecl->getMinRequiredArguments() == 0) {
1377           if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
1378             ZeroArgCallReturnTy = QualType();
1379             Ambiguous = true;
1380           } else
1381             ZeroArgCallReturnTy = OverloadDecl->getReturnType();
1382         }
1383       }
1384     }
1385
1386     // If it's not a member, use better machinery to try to resolve the call
1387     if (!IsMemExpr)
1388       return !ZeroArgCallReturnTy.isNull();
1389   }
1390
1391   // Attempt to call the member with no arguments - this will correctly handle
1392   // member templates with defaults/deduction of template arguments, overloads
1393   // with default arguments, etc.
1394   if (IsMemExpr && !E.isTypeDependent()) {
1395     bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
1396     getDiagnostics().setSuppressAllDiagnostics(true);
1397     ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
1398                                              None, SourceLocation());
1399     getDiagnostics().setSuppressAllDiagnostics(Suppress);
1400     if (R.isUsable()) {
1401       ZeroArgCallReturnTy = R.get()->getType();
1402       return true;
1403     }
1404     return false;
1405   }
1406
1407   if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
1408     if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
1409       if (Fun->getMinRequiredArguments() == 0)
1410         ZeroArgCallReturnTy = Fun->getReturnType();
1411       return true;
1412     }
1413   }
1414
1415   // We don't have an expression that's convenient to get a FunctionDecl from,
1416   // but we can at least check if the type is "function of 0 arguments".
1417   QualType ExprTy = E.getType();
1418   const FunctionType *FunTy = nullptr;
1419   QualType PointeeTy = ExprTy->getPointeeType();
1420   if (!PointeeTy.isNull())
1421     FunTy = PointeeTy->getAs<FunctionType>();
1422   if (!FunTy)
1423     FunTy = ExprTy->getAs<FunctionType>();
1424
1425   if (const FunctionProtoType *FPT =
1426       dyn_cast_or_null<FunctionProtoType>(FunTy)) {
1427     if (FPT->getNumParams() == 0)
1428       ZeroArgCallReturnTy = FunTy->getReturnType();
1429     return true;
1430   }
1431   return false;
1432 }
1433
1434 /// \brief Give notes for a set of overloads.
1435 ///
1436 /// A companion to tryExprAsCall. In cases when the name that the programmer
1437 /// wrote was an overloaded function, we may be able to make some guesses about
1438 /// plausible overloads based on their return types; such guesses can be handed
1439 /// off to this method to be emitted as notes.
1440 ///
1441 /// \param Overloads - The overloads to note.
1442 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
1443 ///  -fshow-overloads=best, this is the location to attach to the note about too
1444 ///  many candidates. Typically this will be the location of the original
1445 ///  ill-formed expression.
1446 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
1447                           const SourceLocation FinalNoteLoc) {
1448   int ShownOverloads = 0;
1449   int SuppressedOverloads = 0;
1450   for (UnresolvedSetImpl::iterator It = Overloads.begin(),
1451        DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1452     // FIXME: Magic number for max shown overloads stolen from
1453     // OverloadCandidateSet::NoteCandidates.
1454     if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
1455       ++SuppressedOverloads;
1456       continue;
1457     }
1458
1459     NamedDecl *Fn = (*It)->getUnderlyingDecl();
1460     S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
1461     ++ShownOverloads;
1462   }
1463
1464   if (SuppressedOverloads)
1465     S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
1466       << SuppressedOverloads;
1467 }
1468
1469 static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
1470                                    const UnresolvedSetImpl &Overloads,
1471                                    bool (*IsPlausibleResult)(QualType)) {
1472   if (!IsPlausibleResult)
1473     return noteOverloads(S, Overloads, Loc);
1474
1475   UnresolvedSet<2> PlausibleOverloads;
1476   for (OverloadExpr::decls_iterator It = Overloads.begin(),
1477          DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1478     const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1479     QualType OverloadResultTy = OverloadDecl->getReturnType();
1480     if (IsPlausibleResult(OverloadResultTy))
1481       PlausibleOverloads.addDecl(It.getDecl());
1482   }
1483   noteOverloads(S, PlausibleOverloads, Loc);
1484 }
1485
1486 /// Determine whether the given expression can be called by just
1487 /// putting parentheses after it.  Notably, expressions with unary
1488 /// operators can't be because the unary operator will start parsing
1489 /// outside the call.
1490 static bool IsCallableWithAppend(Expr *E) {
1491   E = E->IgnoreImplicit();
1492   return (!isa<CStyleCastExpr>(E) &&
1493           !isa<UnaryOperator>(E) &&
1494           !isa<BinaryOperator>(E) &&
1495           !isa<CXXOperatorCallExpr>(E));
1496 }
1497
1498 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1499                                 bool ForceComplain,
1500                                 bool (*IsPlausibleResult)(QualType)) {
1501   SourceLocation Loc = E.get()->getExprLoc();
1502   SourceRange Range = E.get()->getSourceRange();
1503
1504   QualType ZeroArgCallTy;
1505   UnresolvedSet<4> Overloads;
1506   if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
1507       !ZeroArgCallTy.isNull() &&
1508       (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
1509     // At this point, we know E is potentially callable with 0
1510     // arguments and that it returns something of a reasonable type,
1511     // so we can emit a fixit and carry on pretending that E was
1512     // actually a CallExpr.
1513     SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
1514     Diag(Loc, PD)
1515       << /*zero-arg*/ 1 << Range
1516       << (IsCallableWithAppend(E.get())
1517           ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
1518           : FixItHint());
1519     notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1520
1521     // FIXME: Try this before emitting the fixit, and suppress diagnostics
1522     // while doing so.
1523     E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None,
1524                       Range.getEnd().getLocWithOffset(1));
1525     return true;
1526   }
1527
1528   if (!ForceComplain) return false;
1529
1530   Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
1531   notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1532   E = ExprError();
1533   return true;
1534 }
1535
1536 IdentifierInfo *Sema::getSuperIdentifier() const {
1537   if (!Ident_super)
1538     Ident_super = &Context.Idents.get("super");
1539   return Ident_super;
1540 }
1541
1542 IdentifierInfo *Sema::getFloat128Identifier() const {
1543   if (!Ident___float128)
1544     Ident___float128 = &Context.Idents.get("__float128");
1545   return Ident___float128;
1546 }
1547
1548 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
1549                                    CapturedRegionKind K) {
1550   CapturingScopeInfo *CSI = new CapturedRegionScopeInfo(
1551       getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
1552       (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0);
1553   CSI->ReturnType = Context.VoidTy;
1554   FunctionScopes.push_back(CSI);
1555 }
1556
1557 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
1558   if (FunctionScopes.empty())
1559     return nullptr;
1560
1561   return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
1562 }
1563
1564 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
1565 Sema::getMismatchingDeleteExpressions() const {
1566   return DeleteExprs;
1567 }
1568
1569 void Sema::setOpenCLExtensionForType(QualType T, llvm::StringRef ExtStr) {
1570   if (ExtStr.empty())
1571     return;
1572   llvm::SmallVector<StringRef, 1> Exts;
1573   ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
1574   auto CanT = T.getCanonicalType().getTypePtr();
1575   for (auto &I : Exts)
1576     OpenCLTypeExtMap[CanT].insert(I.str());
1577 }
1578
1579 void Sema::setOpenCLExtensionForDecl(Decl *FD, StringRef ExtStr) {
1580   llvm::SmallVector<StringRef, 1> Exts;
1581   ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
1582   if (Exts.empty())
1583     return;
1584   for (auto &I : Exts)
1585     OpenCLDeclExtMap[FD].insert(I.str());
1586 }
1587
1588 void Sema::setCurrentOpenCLExtensionForType(QualType T) {
1589   if (CurrOpenCLExtension.empty())
1590     return;
1591   setOpenCLExtensionForType(T, CurrOpenCLExtension);
1592 }
1593
1594 void Sema::setCurrentOpenCLExtensionForDecl(Decl *D) {
1595   if (CurrOpenCLExtension.empty())
1596     return;
1597   setOpenCLExtensionForDecl(D, CurrOpenCLExtension);
1598 }
1599
1600 bool Sema::isOpenCLDisabledDecl(Decl *FD) {
1601   auto Loc = OpenCLDeclExtMap.find(FD);
1602   if (Loc == OpenCLDeclExtMap.end())
1603     return false;
1604   for (auto &I : Loc->second) {
1605     if (!getOpenCLOptions().isEnabled(I))
1606       return true;
1607   }
1608   return false;
1609 }
1610
1611 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
1612 bool Sema::checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc,
1613                                          DiagInfoT DiagInfo, MapT &Map,
1614                                          unsigned Selector,
1615                                          SourceRange SrcRange) {
1616   auto Loc = Map.find(D);
1617   if (Loc == Map.end())
1618     return false;
1619   bool Disabled = false;
1620   for (auto &I : Loc->second) {
1621     if (I != CurrOpenCLExtension && !getOpenCLOptions().isEnabled(I)) {
1622       Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo
1623                                                          << I << SrcRange;
1624       Disabled = true;
1625     }
1626   }
1627   return Disabled;
1628 }
1629
1630 bool Sema::checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType QT) {
1631   // Check extensions for declared types.
1632   Decl *Decl = nullptr;
1633   if (auto TypedefT = dyn_cast<TypedefType>(QT.getTypePtr()))
1634     Decl = TypedefT->getDecl();
1635   if (auto TagT = dyn_cast<TagType>(QT.getCanonicalType().getTypePtr()))
1636     Decl = TagT->getDecl();
1637   auto Loc = DS.getTypeSpecTypeLoc();
1638   if (checkOpenCLDisabledTypeOrDecl(Decl, Loc, QT, OpenCLDeclExtMap))
1639     return true;
1640
1641   // Check extensions for builtin types.
1642   return checkOpenCLDisabledTypeOrDecl(QT.getCanonicalType().getTypePtr(), Loc,
1643                                        QT, OpenCLTypeExtMap);
1644 }
1645
1646 bool Sema::checkOpenCLDisabledDecl(const Decl &D, const Expr &E) {
1647   return checkOpenCLDisabledTypeOrDecl(&D, E.getLocStart(), "",
1648                                        OpenCLDeclExtMap, 1, D.getSourceRange());
1649 }