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