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