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