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