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