xref: /llvm-project-15.0.7/clang/lib/Sema/Sema.cpp (revision 17d7551e)
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/Sema/DelayedDiagnostic.h"
17 #include "TargetAttributesSema.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/APFloat.h"
21 #include "clang/Sema/CXXFieldCollector.h"
22 #include "clang/Sema/TemplateDeduction.h"
23 #include "clang/Sema/ExternalSemaSource.h"
24 #include "clang/Sema/ObjCMethodList.h"
25 #include "clang/Sema/PrettyDeclStackTrace.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "clang/Sema/SemaConsumer.h"
29 #include "clang/AST/ASTContext.h"
30 #include "clang/AST/ASTDiagnostic.h"
31 #include "clang/AST/DeclCXX.h"
32 #include "clang/AST/DeclObjC.h"
33 #include "clang/AST/Expr.h"
34 #include "clang/AST/ExprCXX.h"
35 #include "clang/AST/StmtCXX.h"
36 #include "clang/Lex/HeaderSearch.h"
37 #include "clang/Lex/Preprocessor.h"
38 #include "clang/Basic/FileManager.h"
39 #include "clang/Basic/PartialDiagnostic.h"
40 #include "clang/Basic/TargetInfo.h"
41 using namespace clang;
42 using namespace sema;
43 
44 FunctionScopeInfo::~FunctionScopeInfo() { }
45 
46 void FunctionScopeInfo::Clear() {
47   HasBranchProtectedScope = false;
48   HasBranchIntoScope = false;
49   HasIndirectGoto = false;
50 
51   SwitchStack.clear();
52   Returns.clear();
53   ErrorTrap.reset();
54   PossiblyUnreachableDiags.clear();
55 }
56 
57 BlockScopeInfo::~BlockScopeInfo() { }
58 LambdaScopeInfo::~LambdaScopeInfo() { }
59 
60 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
61                                        const Preprocessor &PP) {
62   PrintingPolicy Policy = Context.getPrintingPolicy();
63   Policy.Bool = Context.getLangOptions().Bool;
64   if (!Policy.Bool) {
65     if (MacroInfo *BoolMacro = PP.getMacroInfo(&Context.Idents.get("bool"))) {
66       Policy.Bool = BoolMacro->isObjectLike() &&
67         BoolMacro->getNumTokens() == 1 &&
68         BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
69     }
70   }
71 
72   return Policy;
73 }
74 
75 void Sema::ActOnTranslationUnitScope(Scope *S) {
76   TUScope = S;
77   PushDeclContext(S, Context.getTranslationUnitDecl());
78 
79   VAListTagName = PP.getIdentifierInfo("__va_list_tag");
80 }
81 
82 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
83            TranslationUnitKind TUKind,
84            CodeCompleteConsumer *CodeCompleter)
85   : TheTargetAttributesSema(0), FPFeatures(pp.getLangOptions()),
86     LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
87     Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
88     CollectStats(false), ExternalSource(0), CodeCompleter(CodeCompleter),
89     CurContext(0), OriginalLexicalContext(0),
90     PackContext(0), MSStructPragmaOn(false), VisContext(0),
91     ExprNeedsCleanups(false), LateTemplateParser(0), OpaqueParser(0),
92     IdResolver(pp), StdInitializerList(0), CXXTypeInfoDecl(0), MSVCGuidDecl(0),
93     GlobalNewDeleteDeclared(false),
94     ObjCShouldCallSuperDealloc(false),
95     ObjCShouldCallSuperFinalize(false),
96     TUKind(TUKind),
97     NumSFINAEErrors(0), SuppressAccessChecking(false),
98     AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
99     NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
100     CurrentInstantiationScope(0), TyposCorrected(0),
101     AnalysisWarnings(*this)
102 {
103   TUScope = 0;
104   LoadedExternalKnownNamespaces = false;
105 
106   if (getLangOptions().CPlusPlus)
107     FieldCollector.reset(new CXXFieldCollector());
108 
109   // Tell diagnostics how to render things from the AST library.
110   PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
111                                        &Context);
112 
113   ExprEvalContexts.push_back(
114         ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0,
115                                           false, 0, false));
116 
117   FunctionScopes.push_back(new FunctionScopeInfo(Diags));
118 }
119 
120 void Sema::Initialize() {
121   // Tell the AST consumer about this Sema object.
122   Consumer.Initialize(Context);
123 
124   // FIXME: Isn't this redundant with the initialization above?
125   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
126     SC->InitializeSema(*this);
127 
128   // Tell the external Sema source about this Sema object.
129   if (ExternalSemaSource *ExternalSema
130       = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
131     ExternalSema->InitializeSema(*this);
132 
133   // Initialize predefined 128-bit integer types, if needed.
134   if (PP.getTargetInfo().getPointerWidth(0) >= 64) {
135     // If either of the 128-bit integer types are unavailable to name lookup,
136     // define them now.
137     DeclarationName Int128 = &Context.Idents.get("__int128_t");
138     if (IdResolver.begin(Int128) == IdResolver.end())
139       PushOnScopeChains(Context.getInt128Decl(), TUScope);
140 
141     DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
142     if (IdResolver.begin(UInt128) == IdResolver.end())
143       PushOnScopeChains(Context.getUInt128Decl(), TUScope);
144   }
145 
146 
147   // Initialize predefined Objective-C types:
148   if (PP.getLangOptions().ObjC1) {
149     // If 'SEL' does not yet refer to any declarations, make it refer to the
150     // predefined 'SEL'.
151     DeclarationName SEL = &Context.Idents.get("SEL");
152     if (IdResolver.begin(SEL) == IdResolver.end())
153       PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
154 
155     // If 'id' does not yet refer to any declarations, make it refer to the
156     // predefined 'id'.
157     DeclarationName Id = &Context.Idents.get("id");
158     if (IdResolver.begin(Id) == IdResolver.end())
159       PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
160 
161     // Create the built-in typedef for 'Class'.
162     DeclarationName Class = &Context.Idents.get("Class");
163     if (IdResolver.begin(Class) == IdResolver.end())
164       PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
165 
166     // Create the built-in forward declaratino for 'Protocol'.
167     DeclarationName Protocol = &Context.Idents.get("Protocol");
168     if (IdResolver.begin(Protocol) == IdResolver.end())
169       PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
170   }
171 }
172 
173 Sema::~Sema() {
174   if (PackContext) FreePackedContext();
175   if (VisContext) FreeVisContext();
176   delete TheTargetAttributesSema;
177   MSStructPragmaOn = false;
178   // Kill all the active scopes.
179   for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
180     delete FunctionScopes[I];
181   if (FunctionScopes.size() == 1)
182     delete FunctionScopes[0];
183 
184   // Tell the SemaConsumer to forget about us; we're going out of scope.
185   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
186     SC->ForgetSema();
187 
188   // Detach from the external Sema source.
189   if (ExternalSemaSource *ExternalSema
190         = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
191     ExternalSema->ForgetSema();
192 }
193 
194 
195 /// makeUnavailableInSystemHeader - There is an error in the current
196 /// context.  If we're still in a system header, and we can plausibly
197 /// make the relevant declaration unavailable instead of erroring, do
198 /// so and return true.
199 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
200                                          StringRef msg) {
201   // If we're not in a function, it's an error.
202   FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
203   if (!fn) return false;
204 
205   // If we're in template instantiation, it's an error.
206   if (!ActiveTemplateInstantiations.empty())
207     return false;
208 
209   // If that function's not in a system header, it's an error.
210   if (!Context.getSourceManager().isInSystemHeader(loc))
211     return false;
212 
213   // If the function is already unavailable, it's not an error.
214   if (fn->hasAttr<UnavailableAttr>()) return true;
215 
216   fn->addAttr(new (Context) UnavailableAttr(loc, Context, msg));
217   return true;
218 }
219 
220 ASTMutationListener *Sema::getASTMutationListener() const {
221   return getASTConsumer().GetASTMutationListener();
222 }
223 
224 /// \brief Print out statistics about the semantic analysis.
225 void Sema::PrintStats() const {
226   llvm::errs() << "\n*** Semantic Analysis Stats:\n";
227   llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
228 
229   BumpAlloc.PrintStats();
230   AnalysisWarnings.PrintStats();
231 }
232 
233 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
234 /// If there is already an implicit cast, merge into the existing one.
235 /// The result is of the given category.
236 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
237                                    CastKind Kind, ExprValueKind VK,
238                                    const CXXCastPath *BasePath,
239                                    CheckedConversionKind CCK) {
240 #ifndef NDEBUG
241   if (VK == VK_RValue && !E->isRValue()) {
242     switch (Kind) {
243     default:
244       assert(0 && "can't implicitly cast lvalue to rvalue with this cast kind");
245     case CK_LValueToRValue:
246     case CK_ArrayToPointerDecay:
247     case CK_FunctionToPointerDecay:
248     case CK_ToVoid:
249       break;
250     }
251   }
252   assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
253 #endif
254 
255   QualType ExprTy = Context.getCanonicalType(E->getType());
256   QualType TypeTy = Context.getCanonicalType(Ty);
257 
258   if (ExprTy == TypeTy)
259     return Owned(E);
260 
261   if (getLangOptions().ObjCAutoRefCount)
262     CheckObjCARCConversion(SourceRange(), Ty, E, CCK);
263 
264   // If this is a derived-to-base cast to a through a virtual base, we
265   // need a vtable.
266   if (Kind == CK_DerivedToBase &&
267       BasePathInvolvesVirtualBase(*BasePath)) {
268     QualType T = E->getType();
269     if (const PointerType *Pointer = T->getAs<PointerType>())
270       T = Pointer->getPointeeType();
271     if (const RecordType *RecordTy = T->getAs<RecordType>())
272       MarkVTableUsed(E->getLocStart(),
273                      cast<CXXRecordDecl>(RecordTy->getDecl()));
274   }
275 
276   if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
277     if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
278       ImpCast->setType(Ty);
279       ImpCast->setValueKind(VK);
280       return Owned(E);
281     }
282   }
283 
284   return Owned(ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK));
285 }
286 
287 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
288 /// to the conversion from scalar type ScalarTy to the Boolean type.
289 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
290   switch (ScalarTy->getScalarTypeKind()) {
291   case Type::STK_Bool: return CK_NoOp;
292   case Type::STK_CPointer: return CK_PointerToBoolean;
293   case Type::STK_BlockPointer: return CK_PointerToBoolean;
294   case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
295   case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
296   case Type::STK_Integral: return CK_IntegralToBoolean;
297   case Type::STK_Floating: return CK_FloatingToBoolean;
298   case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
299   case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
300   }
301   return CK_Invalid;
302 }
303 
304 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
305 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
306   if (D->isUsed())
307     return true;
308 
309   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
310     // UnusedFileScopedDecls stores the first declaration.
311     // The declaration may have become definition so check again.
312     const FunctionDecl *DeclToCheck;
313     if (FD->hasBody(DeclToCheck))
314       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
315 
316     // Later redecls may add new information resulting in not having to warn,
317     // so check again.
318     DeclToCheck = FD->getMostRecentDecl();
319     if (DeclToCheck != FD)
320       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
321   }
322 
323   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
324     // UnusedFileScopedDecls stores the first declaration.
325     // The declaration may have become definition so check again.
326     const VarDecl *DeclToCheck = VD->getDefinition();
327     if (DeclToCheck)
328       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
329 
330     // Later redecls may add new information resulting in not having to warn,
331     // so check again.
332     DeclToCheck = VD->getMostRecentDecl();
333     if (DeclToCheck != VD)
334       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
335   }
336 
337   return false;
338 }
339 
340 namespace {
341   struct UndefinedInternal {
342     NamedDecl *decl;
343     FullSourceLoc useLoc;
344 
345     UndefinedInternal(NamedDecl *decl, FullSourceLoc useLoc)
346       : decl(decl), useLoc(useLoc) {}
347   };
348 
349   bool operator<(const UndefinedInternal &l, const UndefinedInternal &r) {
350     return l.useLoc.isBeforeInTranslationUnitThan(r.useLoc);
351   }
352 }
353 
354 /// checkUndefinedInternals - Check for undefined objects with internal linkage.
355 static void checkUndefinedInternals(Sema &S) {
356   if (S.UndefinedInternals.empty()) return;
357 
358   // Collect all the still-undefined entities with internal linkage.
359   SmallVector<UndefinedInternal, 16> undefined;
360   for (llvm::DenseMap<NamedDecl*,SourceLocation>::iterator
361          i = S.UndefinedInternals.begin(), e = S.UndefinedInternals.end();
362        i != e; ++i) {
363     NamedDecl *decl = i->first;
364 
365     // Ignore attributes that have become invalid.
366     if (decl->isInvalidDecl()) continue;
367 
368     // __attribute__((weakref)) is basically a definition.
369     if (decl->hasAttr<WeakRefAttr>()) continue;
370 
371     if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
372       if (fn->isPure() || fn->hasBody())
373         continue;
374     } else {
375       if (cast<VarDecl>(decl)->hasDefinition() != VarDecl::DeclarationOnly)
376         continue;
377     }
378 
379     // We build a FullSourceLoc so that we can sort with array_pod_sort.
380     FullSourceLoc loc(i->second, S.Context.getSourceManager());
381     undefined.push_back(UndefinedInternal(decl, loc));
382   }
383 
384   if (undefined.empty()) return;
385 
386   // Sort (in order of use site) so that we're not (as) dependent on
387   // the iteration order through an llvm::DenseMap.
388   llvm::array_pod_sort(undefined.begin(), undefined.end());
389 
390   for (SmallVectorImpl<UndefinedInternal>::iterator
391          i = undefined.begin(), e = undefined.end(); i != e; ++i) {
392     NamedDecl *decl = i->decl;
393     S.Diag(decl->getLocation(), diag::warn_undefined_internal)
394       << isa<VarDecl>(decl) << decl;
395     S.Diag(i->useLoc, diag::note_used_here);
396   }
397 }
398 
399 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
400   if (!ExternalSource)
401     return;
402 
403   SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
404   ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
405   for (unsigned I = 0, N = WeakIDs.size(); I != N; ++I) {
406     llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator Pos
407       = WeakUndeclaredIdentifiers.find(WeakIDs[I].first);
408     if (Pos != WeakUndeclaredIdentifiers.end())
409       continue;
410 
411     WeakUndeclaredIdentifiers.insert(WeakIDs[I]);
412   }
413 }
414 
415 /// ActOnEndOfTranslationUnit - This is called at the very end of the
416 /// translation unit when EOF is reached and all but the top-level scope is
417 /// popped.
418 void Sema::ActOnEndOfTranslationUnit() {
419   // Only complete translation units define vtables and perform implicit
420   // instantiations.
421   if (TUKind == TU_Complete) {
422     DiagnoseUseOfUnimplementedSelectors();
423 
424     // If any dynamic classes have their key function defined within
425     // this translation unit, then those vtables are considered "used" and must
426     // be emitted.
427     for (DynamicClassesType::iterator I = DynamicClasses.begin(ExternalSource),
428                                       E = DynamicClasses.end();
429          I != E; ++I) {
430       assert(!(*I)->isDependentType() &&
431              "Should not see dependent types here!");
432       if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(*I)) {
433         const FunctionDecl *Definition = 0;
434         if (KeyFunction->hasBody(Definition))
435           MarkVTableUsed(Definition->getLocation(), *I, true);
436       }
437     }
438 
439     // If DefinedUsedVTables ends up marking any virtual member functions it
440     // might lead to more pending template instantiations, which we then need
441     // to instantiate.
442     DefineUsedVTables();
443 
444     // C++: Perform implicit template instantiations.
445     //
446     // FIXME: When we perform these implicit instantiations, we do not
447     // carefully keep track of the point of instantiation (C++ [temp.point]).
448     // This means that name lookup that occurs within the template
449     // instantiation will always happen at the end of the translation unit,
450     // so it will find some names that should not be found. Although this is
451     // common behavior for C++ compilers, it is technically wrong. In the
452     // future, we either need to be able to filter the results of name lookup
453     // or we need to perform template instantiations earlier.
454     PerformPendingInstantiations();
455   }
456 
457   // Remove file scoped decls that turned out to be used.
458   UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(0,
459                                                                          true),
460                                              UnusedFileScopedDecls.end(),
461                               std::bind1st(std::ptr_fun(ShouldRemoveFromUnused),
462                                            this)),
463                               UnusedFileScopedDecls.end());
464 
465   if (TUKind == TU_Prefix) {
466     // Translation unit prefixes don't need any of the checking below.
467     TUScope = 0;
468     return;
469   }
470 
471   // Check for #pragma weak identifiers that were never declared
472   // FIXME: This will cause diagnostics to be emitted in a non-determinstic
473   // order!  Iterating over a densemap like this is bad.
474   LoadExternalWeakUndeclaredIdentifiers();
475   for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
476        I = WeakUndeclaredIdentifiers.begin(),
477        E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
478     if (I->second.getUsed()) continue;
479 
480     Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
481       << I->first;
482   }
483 
484   if (TUKind == TU_Module) {
485     // If we are building a module, resolve all of the exported declarations
486     // now.
487     if (Module *CurrentModule = PP.getCurrentModule()) {
488       ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
489 
490       llvm::SmallVector<Module *, 2> Stack;
491       Stack.push_back(CurrentModule);
492       while (!Stack.empty()) {
493         Module *Mod = Stack.back();
494         Stack.pop_back();
495 
496         // Resolve the exported declarations.
497         // FIXME: Actually complain, once we figure out how to teach the
498         // diagnostic client to deal with complains in the module map at this
499         // point.
500         ModMap.resolveExports(Mod, /*Complain=*/false);
501 
502         // Queue the submodules, so their exports will also be resolved.
503         for (Module::submodule_iterator Sub = Mod->submodule_begin(),
504                                      SubEnd = Mod->submodule_end();
505              Sub != SubEnd; ++Sub) {
506           Stack.push_back(*Sub);
507         }
508       }
509     }
510 
511     // Modules don't need any of the checking below.
512     TUScope = 0;
513     return;
514   }
515 
516   // C99 6.9.2p2:
517   //   A declaration of an identifier for an object that has file
518   //   scope without an initializer, and without a storage-class
519   //   specifier or with the storage-class specifier static,
520   //   constitutes a tentative definition. If a translation unit
521   //   contains one or more tentative definitions for an identifier,
522   //   and the translation unit contains no external definition for
523   //   that identifier, then the behavior is exactly as if the
524   //   translation unit contains a file scope declaration of that
525   //   identifier, with the composite type as of the end of the
526   //   translation unit, with an initializer equal to 0.
527   llvm::SmallSet<VarDecl *, 32> Seen;
528   for (TentativeDefinitionsType::iterator
529             T = TentativeDefinitions.begin(ExternalSource),
530          TEnd = TentativeDefinitions.end();
531        T != TEnd; ++T)
532   {
533     VarDecl *VD = (*T)->getActingDefinition();
534 
535     // If the tentative definition was completed, getActingDefinition() returns
536     // null. If we've already seen this variable before, insert()'s second
537     // return value is false.
538     if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
539       continue;
540 
541     if (const IncompleteArrayType *ArrayT
542         = Context.getAsIncompleteArrayType(VD->getType())) {
543       if (RequireCompleteType(VD->getLocation(),
544                               ArrayT->getElementType(),
545                               diag::err_tentative_def_incomplete_type_arr)) {
546         VD->setInvalidDecl();
547         continue;
548       }
549 
550       // Set the length of the array to 1 (C99 6.9.2p5).
551       Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
552       llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
553       QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
554                                                 One, ArrayType::Normal, 0);
555       VD->setType(T);
556     } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
557                                    diag::err_tentative_def_incomplete_type))
558       VD->setInvalidDecl();
559 
560     // Notify the consumer that we've completed a tentative definition.
561     if (!VD->isInvalidDecl())
562       Consumer.CompleteTentativeDefinition(VD);
563 
564   }
565 
566   if (LangOpts.CPlusPlus0x &&
567       Diags.getDiagnosticLevel(diag::warn_delegating_ctor_cycle,
568                                SourceLocation())
569         != DiagnosticsEngine::Ignored)
570     CheckDelegatingCtorCycles();
571 
572   // If there were errors, disable 'unused' warnings since they will mostly be
573   // noise.
574   if (!Diags.hasErrorOccurred()) {
575     // Output warning for unused file scoped decls.
576     for (UnusedFileScopedDeclsType::iterator
577            I = UnusedFileScopedDecls.begin(ExternalSource),
578            E = UnusedFileScopedDecls.end(); I != E; ++I) {
579       if (ShouldRemoveFromUnused(this, *I))
580         continue;
581 
582       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
583         const FunctionDecl *DiagD;
584         if (!FD->hasBody(DiagD))
585           DiagD = FD;
586         if (DiagD->isDeleted())
587           continue; // Deleted functions are supposed to be unused.
588         if (DiagD->isReferenced()) {
589           if (isa<CXXMethodDecl>(DiagD))
590             Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
591                   << DiagD->getDeclName();
592           else
593             Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
594                   << /*function*/0 << DiagD->getDeclName();
595         } else {
596           Diag(DiagD->getLocation(),
597                isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
598                                          : diag::warn_unused_function)
599                 << DiagD->getDeclName();
600         }
601       } else {
602         const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
603         if (!DiagD)
604           DiagD = cast<VarDecl>(*I);
605         if (DiagD->isReferenced()) {
606           Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
607                 << /*variable*/1 << DiagD->getDeclName();
608         } else {
609           Diag(DiagD->getLocation(), diag::warn_unused_variable)
610                 << DiagD->getDeclName();
611         }
612       }
613     }
614 
615     checkUndefinedInternals(*this);
616   }
617 
618   // Check we've noticed that we're no longer parsing the initializer for every
619   // variable. If we miss cases, then at best we have a performance issue and
620   // at worst a rejects-valid bug.
621   assert(ParsingInitForAutoVars.empty() &&
622          "Didn't unmark var as having its initializer parsed");
623 
624   TUScope = 0;
625 }
626 
627 
628 //===----------------------------------------------------------------------===//
629 // Helper functions.
630 //===----------------------------------------------------------------------===//
631 
632 DeclContext *Sema::getFunctionLevelDeclContext() {
633   DeclContext *DC = CurContext;
634 
635   while (true) {
636     if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC)) {
637       DC = DC->getParent();
638     } else if (isa<CXXMethodDecl>(DC) &&
639                cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
640                cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
641       DC = DC->getParent()->getParent();
642     }
643     else break;
644   }
645 
646   return DC;
647 }
648 
649 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
650 /// to the function decl for the function being parsed.  If we're currently
651 /// in a 'block', this returns the containing context.
652 FunctionDecl *Sema::getCurFunctionDecl() {
653   DeclContext *DC = getFunctionLevelDeclContext();
654   return dyn_cast<FunctionDecl>(DC);
655 }
656 
657 ObjCMethodDecl *Sema::getCurMethodDecl() {
658   DeclContext *DC = getFunctionLevelDeclContext();
659   return dyn_cast<ObjCMethodDecl>(DC);
660 }
661 
662 NamedDecl *Sema::getCurFunctionOrMethodDecl() {
663   DeclContext *DC = getFunctionLevelDeclContext();
664   if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
665     return cast<NamedDecl>(DC);
666   return 0;
667 }
668 
669 Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
670   if (!isActive())
671     return;
672 
673   if (llvm::Optional<TemplateDeductionInfo*> Info = SemaRef.isSFINAEContext()) {
674     switch (DiagnosticIDs::getDiagnosticSFINAEResponse(getDiagID())) {
675     case DiagnosticIDs::SFINAE_Report:
676       // We'll report the diagnostic below.
677       break;
678 
679     case DiagnosticIDs::SFINAE_SubstitutionFailure:
680       // Count this failure so that we know that template argument deduction
681       // has failed.
682       ++SemaRef.NumSFINAEErrors;
683       SemaRef.Diags.setLastDiagnosticIgnored();
684       SemaRef.Diags.Clear();
685       Clear();
686       return;
687 
688     case DiagnosticIDs::SFINAE_AccessControl: {
689       // Per C++ Core Issue 1170, access control is part of SFINAE.
690       // Additionally, the AccessCheckingSFINAE flag can be used to temporary
691       // make access control a part of SFINAE for the purposes of checking
692       // type traits.
693       if (!SemaRef.AccessCheckingSFINAE &&
694           !SemaRef.getLangOptions().CPlusPlus0x)
695         break;
696 
697       SourceLocation Loc = getLocation();
698 
699       // Suppress this diagnostic.
700       ++SemaRef.NumSFINAEErrors;
701       SemaRef.Diags.setLastDiagnosticIgnored();
702       SemaRef.Diags.Clear();
703       Clear();
704 
705       // Now the diagnostic state is clear, produce a C++98 compatibility
706       // warning.
707       SemaRef.Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
708 
709       // The last diagnostic which Sema produced was ignored. Suppress any
710       // notes attached to it.
711       SemaRef.Diags.setLastDiagnosticIgnored();
712       return;
713     }
714 
715     case DiagnosticIDs::SFINAE_Suppress:
716       // Make a copy of this suppressed diagnostic and store it with the
717       // template-deduction information;
718       FlushCounts();
719       Diagnostic DiagInfo(&SemaRef.Diags);
720 
721       if (*Info)
722         (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
723                         PartialDiagnostic(DiagInfo,
724                                           SemaRef.Context.getDiagAllocator()));
725 
726       // Suppress this diagnostic.
727       SemaRef.Diags.setLastDiagnosticIgnored();
728       SemaRef.Diags.Clear();
729       Clear();
730       return;
731     }
732   }
733 
734   // Set up the context's printing policy based on our current state.
735   SemaRef.Context.setPrintingPolicy(SemaRef.getPrintingPolicy());
736 
737   // Emit the diagnostic.
738   if (!this->Emit())
739     return;
740 
741   // If this is not a note, and we're in a template instantiation
742   // that is different from the last template instantiation where
743   // we emitted an error, print a template instantiation
744   // backtrace.
745   if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
746       !SemaRef.ActiveTemplateInstantiations.empty() &&
747       SemaRef.ActiveTemplateInstantiations.back()
748         != SemaRef.LastTemplateInstantiationErrorContext) {
749     SemaRef.PrintInstantiationStack();
750     SemaRef.LastTemplateInstantiationErrorContext
751       = SemaRef.ActiveTemplateInstantiations.back();
752   }
753 }
754 
755 Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
756   DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
757   return SemaDiagnosticBuilder(DB, *this, DiagID);
758 }
759 
760 Sema::SemaDiagnosticBuilder
761 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
762   SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
763   PD.Emit(Builder);
764 
765   return Builder;
766 }
767 
768 /// \brief Looks through the macro-expansion chain for the given
769 /// location, looking for a macro expansion with the given name.
770 /// If one is found, returns true and sets the location to that
771 /// expansion loc.
772 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
773   SourceLocation loc = locref;
774   if (!loc.isMacroID()) return false;
775 
776   // There's no good way right now to look at the intermediate
777   // expansions, so just jump to the expansion location.
778   loc = getSourceManager().getExpansionLoc(loc);
779 
780   // If that's written with the name, stop here.
781   SmallVector<char, 16> buffer;
782   if (getPreprocessor().getSpelling(loc, buffer) == name) {
783     locref = loc;
784     return true;
785   }
786   return false;
787 }
788 
789 /// \brief Determines the active Scope associated with the given declaration
790 /// context.
791 ///
792 /// This routine maps a declaration context to the active Scope object that
793 /// represents that declaration context in the parser. It is typically used
794 /// from "scope-less" code (e.g., template instantiation, lazy creation of
795 /// declarations) that injects a name for name-lookup purposes and, therefore,
796 /// must update the Scope.
797 ///
798 /// \returns The scope corresponding to the given declaraion context, or NULL
799 /// if no such scope is open.
800 Scope *Sema::getScopeForContext(DeclContext *Ctx) {
801 
802   if (!Ctx)
803     return 0;
804 
805   Ctx = Ctx->getPrimaryContext();
806   for (Scope *S = getCurScope(); S; S = S->getParent()) {
807     // Ignore scopes that cannot have declarations. This is important for
808     // out-of-line definitions of static class members.
809     if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
810       if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
811         if (Ctx == Entity->getPrimaryContext())
812           return S;
813   }
814 
815   return 0;
816 }
817 
818 /// \brief Enter a new function scope
819 void Sema::PushFunctionScope() {
820   if (FunctionScopes.size() == 1) {
821     // Use the "top" function scope rather than having to allocate
822     // memory for a new scope.
823     FunctionScopes.back()->Clear();
824     FunctionScopes.push_back(FunctionScopes.back());
825     return;
826   }
827 
828   FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
829 }
830 
831 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
832   FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
833                                               BlockScope, Block));
834 }
835 
836 void Sema::PushLambdaScope(CXXRecordDecl *Lambda,
837                            CXXMethodDecl *CallOperator) {
838   FunctionScopes.push_back(new LambdaScopeInfo(getDiagnostics(), Lambda,
839                                                CallOperator));
840 }
841 
842 void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
843                                 const Decl *D, const BlockExpr *blkExpr) {
844   FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
845   assert(!FunctionScopes.empty() && "mismatched push/pop!");
846 
847   // Issue any analysis-based warnings.
848   if (WP && D)
849     AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
850   else {
851     for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
852          i = Scope->PossiblyUnreachableDiags.begin(),
853          e = Scope->PossiblyUnreachableDiags.end();
854          i != e; ++i) {
855       const sema::PossiblyUnreachableDiag &D = *i;
856       Diag(D.Loc, D.PD);
857     }
858   }
859 
860   if (FunctionScopes.back() != Scope) {
861     delete Scope;
862   }
863 }
864 
865 void Sema::PushCompoundScope() {
866   getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo());
867 }
868 
869 void Sema::PopCompoundScope() {
870   FunctionScopeInfo *CurFunction = getCurFunction();
871   assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
872 
873   CurFunction->CompoundScopes.pop_back();
874 }
875 
876 /// \brief Determine whether any errors occurred within this function/method/
877 /// block.
878 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
879   return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
880 }
881 
882 BlockScopeInfo *Sema::getCurBlock() {
883   if (FunctionScopes.empty())
884     return 0;
885 
886   return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
887 }
888 
889 LambdaScopeInfo *Sema::getCurLambda() {
890   if (FunctionScopes.empty())
891     return 0;
892 
893   return dyn_cast<LambdaScopeInfo>(FunctionScopes.back());
894 }
895 
896 // Pin this vtable to this file.
897 ExternalSemaSource::~ExternalSemaSource() {}
898 
899 void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
900 
901 void ExternalSemaSource::ReadKnownNamespaces(
902                            SmallVectorImpl<NamespaceDecl *> &Namespaces) {
903 }
904 
905 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
906   SourceLocation Loc = this->Loc;
907   if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
908   if (Loc.isValid()) {
909     Loc.print(OS, S.getSourceManager());
910     OS << ": ";
911   }
912   OS << Message;
913 
914   if (TheDecl && isa<NamedDecl>(TheDecl)) {
915     std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
916     if (!Name.empty())
917       OS << " '" << Name << '\'';
918   }
919 
920   OS << '\n';
921 }
922 
923 /// \brief Figure out if an expression could be turned into a call.
924 ///
925 /// Use this when trying to recover from an error where the programmer may have
926 /// written just the name of a function instead of actually calling it.
927 ///
928 /// \param E - The expression to examine.
929 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
930 ///  with no arguments, this parameter is set to the type returned by such a
931 ///  call; otherwise, it is set to an empty QualType.
932 /// \param OverloadSet - If the expression is an overloaded function
933 ///  name, this parameter is populated with the decls of the various overloads.
934 bool Sema::isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy,
935                           UnresolvedSetImpl &OverloadSet) {
936   ZeroArgCallReturnTy = QualType();
937   OverloadSet.clear();
938 
939   if (E.getType() == Context.OverloadTy) {
940     OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
941     const OverloadExpr *Overloads = FR.Expression;
942 
943     for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
944          DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
945       OverloadSet.addDecl(*it);
946 
947       // Check whether the function is a non-template which takes no
948       // arguments.
949       if (const FunctionDecl *OverloadDecl
950             = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
951         if (OverloadDecl->getMinRequiredArguments() == 0)
952           ZeroArgCallReturnTy = OverloadDecl->getResultType();
953       }
954     }
955 
956     // Ignore overloads that are pointer-to-member constants.
957     if (FR.HasFormOfMemberPointer)
958       return false;
959 
960     return true;
961   }
962 
963   if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
964     if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
965       if (Fun->getMinRequiredArguments() == 0)
966         ZeroArgCallReturnTy = Fun->getResultType();
967       return true;
968     }
969   }
970 
971   // We don't have an expression that's convenient to get a FunctionDecl from,
972   // but we can at least check if the type is "function of 0 arguments".
973   QualType ExprTy = E.getType();
974   const FunctionType *FunTy = NULL;
975   QualType PointeeTy = ExprTy->getPointeeType();
976   if (!PointeeTy.isNull())
977     FunTy = PointeeTy->getAs<FunctionType>();
978   if (!FunTy)
979     FunTy = ExprTy->getAs<FunctionType>();
980   if (!FunTy && ExprTy == Context.BoundMemberTy) {
981     // Look for the bound-member type.  If it's still overloaded, give up,
982     // although we probably should have fallen into the OverloadExpr case above
983     // if we actually have an overloaded bound member.
984     QualType BoundMemberTy = Expr::findBoundMemberType(&E);
985     if (!BoundMemberTy.isNull())
986       FunTy = BoundMemberTy->castAs<FunctionType>();
987   }
988 
989   if (const FunctionProtoType *FPT =
990       dyn_cast_or_null<FunctionProtoType>(FunTy)) {
991     if (FPT->getNumArgs() == 0)
992       ZeroArgCallReturnTy = FunTy->getResultType();
993     return true;
994   }
995   return false;
996 }
997 
998 /// \brief Give notes for a set of overloads.
999 ///
1000 /// A companion to isExprCallable. In cases when the name that the programmer
1001 /// wrote was an overloaded function, we may be able to make some guesses about
1002 /// plausible overloads based on their return types; such guesses can be handed
1003 /// off to this method to be emitted as notes.
1004 ///
1005 /// \param Overloads - The overloads to note.
1006 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
1007 ///  -fshow-overloads=best, this is the location to attach to the note about too
1008 ///  many candidates. Typically this will be the location of the original
1009 ///  ill-formed expression.
1010 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
1011                           const SourceLocation FinalNoteLoc) {
1012   int ShownOverloads = 0;
1013   int SuppressedOverloads = 0;
1014   for (UnresolvedSetImpl::iterator It = Overloads.begin(),
1015        DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1016     // FIXME: Magic number for max shown overloads stolen from
1017     // OverloadCandidateSet::NoteCandidates.
1018     if (ShownOverloads >= 4 &&
1019         S.Diags.getShowOverloads() == DiagnosticsEngine::Ovl_Best) {
1020       ++SuppressedOverloads;
1021       continue;
1022     }
1023 
1024     NamedDecl *Fn = (*It)->getUnderlyingDecl();
1025     S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
1026     ++ShownOverloads;
1027   }
1028 
1029   if (SuppressedOverloads)
1030     S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
1031       << SuppressedOverloads;
1032 }
1033 
1034 static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
1035                                    const UnresolvedSetImpl &Overloads,
1036                                    bool (*IsPlausibleResult)(QualType)) {
1037   if (!IsPlausibleResult)
1038     return noteOverloads(S, Overloads, Loc);
1039 
1040   UnresolvedSet<2> PlausibleOverloads;
1041   for (OverloadExpr::decls_iterator It = Overloads.begin(),
1042          DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1043     const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1044     QualType OverloadResultTy = OverloadDecl->getResultType();
1045     if (IsPlausibleResult(OverloadResultTy))
1046       PlausibleOverloads.addDecl(It.getDecl());
1047   }
1048   noteOverloads(S, PlausibleOverloads, Loc);
1049 }
1050 
1051 /// Determine whether the given expression can be called by just
1052 /// putting parentheses after it.  Notably, expressions with unary
1053 /// operators can't be because the unary operator will start parsing
1054 /// outside the call.
1055 static bool IsCallableWithAppend(Expr *E) {
1056   E = E->IgnoreImplicit();
1057   return (!isa<CStyleCastExpr>(E) &&
1058           !isa<UnaryOperator>(E) &&
1059           !isa<BinaryOperator>(E) &&
1060           !isa<CXXOperatorCallExpr>(E));
1061 }
1062 
1063 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1064                                 bool ForceComplain,
1065                                 bool (*IsPlausibleResult)(QualType)) {
1066   SourceLocation Loc = E.get()->getExprLoc();
1067   SourceRange Range = E.get()->getSourceRange();
1068 
1069   QualType ZeroArgCallTy;
1070   UnresolvedSet<4> Overloads;
1071   if (isExprCallable(*E.get(), ZeroArgCallTy, Overloads) &&
1072       !ZeroArgCallTy.isNull() &&
1073       (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
1074     // At this point, we know E is potentially callable with 0
1075     // arguments and that it returns something of a reasonable type,
1076     // so we can emit a fixit and carry on pretending that E was
1077     // actually a CallExpr.
1078     SourceLocation ParenInsertionLoc =
1079       PP.getLocForEndOfToken(Range.getEnd());
1080     Diag(Loc, PD)
1081       << /*zero-arg*/ 1 << Range
1082       << (IsCallableWithAppend(E.get())
1083           ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
1084           : FixItHint());
1085     notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1086 
1087     // FIXME: Try this before emitting the fixit, and suppress diagnostics
1088     // while doing so.
1089     E = ActOnCallExpr(0, E.take(), ParenInsertionLoc,
1090                       MultiExprArg(*this, 0, 0),
1091                       ParenInsertionLoc.getLocWithOffset(1));
1092     return true;
1093   }
1094 
1095   if (!ForceComplain) return false;
1096 
1097   Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
1098   notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1099   E = ExprError();
1100   return true;
1101 }
1102