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