Sema.cpp revision 7822ee3ef9f0d5cfd289258614ac31be70097449
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/PartialDiagnostic.h"
38#include "clang/Basic/TargetInfo.h"
39using namespace clang;
40using namespace sema;
41
42FunctionScopeInfo::~FunctionScopeInfo() { }
43
44void FunctionScopeInfo::Clear() {
45  HasBranchProtectedScope = false;
46  HasBranchIntoScope = false;
47  HasIndirectGoto = false;
48
49  SwitchStack.clear();
50  Returns.clear();
51  ErrorTrap.reset();
52  PossiblyUnreachableDiags.clear();
53}
54
55BlockScopeInfo::~BlockScopeInfo() { }
56
57void Sema::ActOnTranslationUnitScope(Scope *S) {
58  TUScope = S;
59  PushDeclContext(S, Context.getTranslationUnitDecl());
60
61  VAListTagName = PP.getIdentifierInfo("__va_list_tag");
62
63  if (!Context.isInt128Installed() && // May be set by ASTReader.
64      PP.getTargetInfo().getPointerWidth(0) >= 64) {
65    TypeSourceInfo *TInfo;
66
67    // Install [u]int128_t for 64-bit targets.
68    TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty);
69    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
70                                          SourceLocation(),
71                                          SourceLocation(),
72                                          &Context.Idents.get("__int128_t"),
73                                          TInfo), TUScope);
74
75    TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty);
76    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
77                                          SourceLocation(),
78                                          SourceLocation(),
79                                          &Context.Idents.get("__uint128_t"),
80                                          TInfo), TUScope);
81    Context.setInt128Installed();
82  }
83
84
85  if (!PP.getLangOptions().ObjC1) return;
86
87  // Built-in ObjC types may already be set by ASTReader (hence isNull checks).
88  if (Context.getObjCSelType().isNull()) {
89    // Create the built-in typedef for 'SEL'.
90    QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy);
91    TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT);
92    TypedefDecl *SelTypedef
93      = TypedefDecl::Create(Context, CurContext,
94                            SourceLocation(), SourceLocation(),
95                            &Context.Idents.get("SEL"), SelInfo);
96    PushOnScopeChains(SelTypedef, TUScope);
97    Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
98    Context.ObjCSelRedefinitionType = Context.getObjCSelType();
99  }
100
101  // Synthesize "@class Protocol;
102  if (Context.getObjCProtoType().isNull()) {
103    ObjCInterfaceDecl *ProtocolDecl =
104      ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
105                                &Context.Idents.get("Protocol"),
106                                SourceLocation(), true);
107    Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
108    PushOnScopeChains(ProtocolDecl, TUScope, false);
109  }
110  // Create the built-in typedef for 'id'.
111  if (Context.getObjCIdType().isNull()) {
112    QualType T = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 0, 0);
113    T = Context.getObjCObjectPointerType(T);
114    TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(T);
115    TypedefDecl *IdTypedef
116      = TypedefDecl::Create(Context, CurContext,
117                            SourceLocation(), SourceLocation(),
118                            &Context.Idents.get("id"), IdInfo);
119    PushOnScopeChains(IdTypedef, TUScope);
120    Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
121    Context.ObjCIdRedefinitionType = Context.getObjCIdType();
122  }
123  // Create the built-in typedef for 'Class'.
124  if (Context.getObjCClassType().isNull()) {
125    QualType T = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 0, 0);
126    T = Context.getObjCObjectPointerType(T);
127    TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(T);
128    TypedefDecl *ClassTypedef
129      = TypedefDecl::Create(Context, CurContext,
130                            SourceLocation(), SourceLocation(),
131                            &Context.Idents.get("Class"), ClassInfo);
132    PushOnScopeChains(ClassTypedef, TUScope);
133    Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
134    Context.ObjCClassRedefinitionType = Context.getObjCClassType();
135  }
136}
137
138Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
139           bool CompleteTranslationUnit,
140           CodeCompleteConsumer *CodeCompleter)
141  : TheTargetAttributesSema(0), FPFeatures(pp.getLangOptions()),
142    LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
143    Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
144    ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0),
145    PackContext(0), MSStructPragmaOn(false), VisContext(0),
146    LateTemplateParser(0), OpaqueParser(0),
147    IdResolver(pp.getLangOptions()), CXXTypeInfoDecl(0), MSVCGuidDecl(0),
148    GlobalNewDeleteDeclared(false),
149    CompleteTranslationUnit(CompleteTranslationUnit),
150    NumSFINAEErrors(0), SuppressAccessChecking(false),
151    AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
152    NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
153    CurrentInstantiationScope(0), TyposCorrected(0),
154    AnalysisWarnings(*this)
155{
156  TUScope = 0;
157  if (getLangOptions().CPlusPlus)
158    FieldCollector.reset(new CXXFieldCollector());
159
160  // Tell diagnostics how to render things from the AST library.
161  PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
162                                       &Context);
163
164  ExprEvalContexts.push_back(
165                  ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0));
166
167  FunctionScopes.push_back(new FunctionScopeInfo(Diags));
168}
169
170void Sema::Initialize() {
171  // Tell the AST consumer about this Sema object.
172  Consumer.Initialize(Context);
173
174  // FIXME: Isn't this redundant with the initialization above?
175  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
176    SC->InitializeSema(*this);
177
178  // Tell the external Sema source about this Sema object.
179  if (ExternalSemaSource *ExternalSema
180      = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
181    ExternalSema->InitializeSema(*this);
182}
183
184Sema::~Sema() {
185  if (PackContext) FreePackedContext();
186  if (VisContext) FreeVisContext();
187  delete TheTargetAttributesSema;
188  MSStructPragmaOn = false;
189  // Kill all the active scopes.
190  for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
191    delete FunctionScopes[I];
192  if (FunctionScopes.size() == 1)
193    delete FunctionScopes[0];
194
195  // Tell the SemaConsumer to forget about us; we're going out of scope.
196  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
197    SC->ForgetSema();
198
199  // Detach from the external Sema source.
200  if (ExternalSemaSource *ExternalSema
201        = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
202    ExternalSema->ForgetSema();
203}
204
205ASTMutationListener *Sema::getASTMutationListener() const {
206  return getASTConsumer().GetASTMutationListener();
207}
208
209/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
210/// If there is already an implicit cast, merge into the existing one.
211/// The result is of the given category.
212ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
213                                   CastKind Kind, ExprValueKind VK,
214                                   const CXXCastPath *BasePath) {
215  QualType ExprTy = Context.getCanonicalType(E->getType());
216  QualType TypeTy = Context.getCanonicalType(Ty);
217
218  if (ExprTy == TypeTy)
219    return Owned(E);
220
221  // If this is a derived-to-base cast to a through a virtual base, we
222  // need a vtable.
223  if (Kind == CK_DerivedToBase &&
224      BasePathInvolvesVirtualBase(*BasePath)) {
225    QualType T = E->getType();
226    if (const PointerType *Pointer = T->getAs<PointerType>())
227      T = Pointer->getPointeeType();
228    if (const RecordType *RecordTy = T->getAs<RecordType>())
229      MarkVTableUsed(E->getLocStart(),
230                     cast<CXXRecordDecl>(RecordTy->getDecl()));
231  }
232
233  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
234    if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
235      ImpCast->setType(Ty);
236      ImpCast->setValueKind(VK);
237      return Owned(E);
238    }
239  }
240
241  return Owned(ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK));
242}
243
244/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
245/// to the conversion from scalar type ScalarTy to the Boolean type.
246CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
247  switch (ScalarTy->getScalarTypeKind()) {
248  case Type::STK_Bool: return CK_NoOp;
249  case Type::STK_Pointer: return CK_PointerToBoolean;
250  case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
251  case Type::STK_Integral: return CK_IntegralToBoolean;
252  case Type::STK_Floating: return CK_FloatingToBoolean;
253  case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
254  case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
255  }
256  return CK_Invalid;
257}
258
259ExprValueKind Sema::CastCategory(Expr *E) {
260  Expr::Classification Classification = E->Classify(Context);
261  return Classification.isRValue() ? VK_RValue :
262      (Classification.isLValue() ? VK_LValue : VK_XValue);
263}
264
265/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
266static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
267  if (D->isUsed())
268    return true;
269
270  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
271    // UnusedFileScopedDecls stores the first declaration.
272    // The declaration may have become definition so check again.
273    const FunctionDecl *DeclToCheck;
274    if (FD->hasBody(DeclToCheck))
275      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
276
277    // Later redecls may add new information resulting in not having to warn,
278    // so check again.
279    DeclToCheck = FD->getMostRecentDeclaration();
280    if (DeclToCheck != FD)
281      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
282  }
283
284  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285    // UnusedFileScopedDecls stores the first declaration.
286    // The declaration may have become definition so check again.
287    const VarDecl *DeclToCheck = VD->getDefinition();
288    if (DeclToCheck)
289      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
290
291    // Later redecls may add new information resulting in not having to warn,
292    // so check again.
293    DeclToCheck = VD->getMostRecentDeclaration();
294    if (DeclToCheck != VD)
295      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
296  }
297
298  return false;
299}
300
301namespace {
302  struct UndefinedInternal {
303    NamedDecl *decl;
304    FullSourceLoc useLoc;
305
306    UndefinedInternal(NamedDecl *decl, FullSourceLoc useLoc)
307      : decl(decl), useLoc(useLoc) {}
308  };
309
310  bool operator<(const UndefinedInternal &l, const UndefinedInternal &r) {
311    return l.useLoc.isBeforeInTranslationUnitThan(r.useLoc);
312  }
313}
314
315/// checkUndefinedInternals - Check for undefined objects with internal linkage.
316static void checkUndefinedInternals(Sema &S) {
317  if (S.UndefinedInternals.empty()) return;
318
319  // Collect all the still-undefined entities with internal linkage.
320  llvm::SmallVector<UndefinedInternal, 16> undefined;
321  for (llvm::DenseMap<NamedDecl*,SourceLocation>::iterator
322         i = S.UndefinedInternals.begin(), e = S.UndefinedInternals.end();
323       i != e; ++i) {
324    NamedDecl *decl = i->first;
325
326    // Ignore attributes that have become invalid.
327    if (decl->isInvalidDecl()) continue;
328
329    // __attribute__((weakref)) is basically a definition.
330    if (decl->hasAttr<WeakRefAttr>()) continue;
331
332    if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
333      if (fn->isPure() || fn->hasBody())
334        continue;
335    } else {
336      if (cast<VarDecl>(decl)->hasDefinition() != VarDecl::DeclarationOnly)
337        continue;
338    }
339
340    // We build a FullSourceLoc so that we can sort with array_pod_sort.
341    FullSourceLoc loc(i->second, S.Context.getSourceManager());
342    undefined.push_back(UndefinedInternal(decl, loc));
343  }
344
345  if (undefined.empty()) return;
346
347  // Sort (in order of use site) so that we're not (as) dependent on
348  // the iteration order through an llvm::DenseMap.
349  llvm::array_pod_sort(undefined.begin(), undefined.end());
350
351  for (llvm::SmallVectorImpl<UndefinedInternal>::iterator
352         i = undefined.begin(), e = undefined.end(); i != e; ++i) {
353    NamedDecl *decl = i->decl;
354    S.Diag(decl->getLocation(), diag::warn_undefined_internal)
355      << isa<VarDecl>(decl) << decl;
356    S.Diag(i->useLoc, diag::note_used_here);
357  }
358}
359
360/// ActOnEndOfTranslationUnit - This is called at the very end of the
361/// translation unit when EOF is reached and all but the top-level scope is
362/// popped.
363void Sema::ActOnEndOfTranslationUnit() {
364  // At PCH writing, implicit instantiations and VTable handling info are
365  // stored and performed when the PCH is included.
366  if (CompleteTranslationUnit) {
367    // If any dynamic classes have their key function defined within
368    // this translation unit, then those vtables are considered "used" and must
369    // be emitted.
370    for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
371      assert(!DynamicClasses[I]->isDependentType() &&
372             "Should not see dependent types here!");
373      if (const CXXMethodDecl *KeyFunction
374          = Context.getKeyFunction(DynamicClasses[I])) {
375        const FunctionDecl *Definition = 0;
376        if (KeyFunction->hasBody(Definition))
377          MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
378      }
379    }
380
381    bool SomethingChanged;
382    do {
383      SomethingChanged = false;
384
385      // If DefinedUsedVTables ends up marking any virtual member functions it
386      // might lead to more pending template instantiations, which we then need
387      // to instantiate.
388      if (DefineUsedVTables())
389        SomethingChanged = true;
390
391      // C++: Perform implicit template instantiations.
392      //
393      // FIXME: When we perform these implicit instantiations, we do not
394      // carefully keep track of the point of instantiation (C++ [temp.point]).
395      // This means that name lookup that occurs within the template
396      // instantiation will always happen at the end of the translation unit,
397      // so it will find some names that should not be found. Although this is
398      // common behavior for C++ compilers, it is technically wrong. In the
399      // future, we either need to be able to filter the results of name lookup
400      // or we need to perform template instantiations earlier.
401      if (PerformPendingInstantiations())
402        SomethingChanged = true;
403
404    } while (SomethingChanged);
405  }
406
407  // Remove file scoped decls that turned out to be used.
408  UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(),
409                                             UnusedFileScopedDecls.end(),
410                              std::bind1st(std::ptr_fun(ShouldRemoveFromUnused),
411                                           this)),
412                              UnusedFileScopedDecls.end());
413
414  if (!CompleteTranslationUnit) {
415    TUScope = 0;
416    return;
417  }
418
419  // Check for #pragma weak identifiers that were never declared
420  // FIXME: This will cause diagnostics to be emitted in a non-determinstic
421  // order!  Iterating over a densemap like this is bad.
422  for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
423       I = WeakUndeclaredIdentifiers.begin(),
424       E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
425    if (I->second.getUsed()) continue;
426
427    Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
428      << I->first;
429  }
430
431  // C99 6.9.2p2:
432  //   A declaration of an identifier for an object that has file
433  //   scope without an initializer, and without a storage-class
434  //   specifier or with the storage-class specifier static,
435  //   constitutes a tentative definition. If a translation unit
436  //   contains one or more tentative definitions for an identifier,
437  //   and the translation unit contains no external definition for
438  //   that identifier, then the behavior is exactly as if the
439  //   translation unit contains a file scope declaration of that
440  //   identifier, with the composite type as of the end of the
441  //   translation unit, with an initializer equal to 0.
442  llvm::SmallSet<VarDecl *, 32> Seen;
443  for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) {
444    VarDecl *VD = TentativeDefinitions[i]->getActingDefinition();
445
446    // If the tentative definition was completed, getActingDefinition() returns
447    // null. If we've already seen this variable before, insert()'s second
448    // return value is false.
449    if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
450      continue;
451
452    if (const IncompleteArrayType *ArrayT
453        = Context.getAsIncompleteArrayType(VD->getType())) {
454      if (RequireCompleteType(VD->getLocation(),
455                              ArrayT->getElementType(),
456                              diag::err_tentative_def_incomplete_type_arr)) {
457        VD->setInvalidDecl();
458        continue;
459      }
460
461      // Set the length of the array to 1 (C99 6.9.2p5).
462      Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
463      llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
464      QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
465                                                One, ArrayType::Normal, 0);
466      VD->setType(T);
467    } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
468                                   diag::err_tentative_def_incomplete_type))
469      VD->setInvalidDecl();
470
471    // Notify the consumer that we've completed a tentative definition.
472    if (!VD->isInvalidDecl())
473      Consumer.CompleteTentativeDefinition(VD);
474
475  }
476
477  if (LangOpts.CPlusPlus0x &&
478      Diags.getDiagnosticLevel(diag::warn_delegating_ctor_cycle,
479                               SourceLocation())
480        != Diagnostic::Ignored)
481    CheckDelegatingCtorCycles();
482
483  // If there were errors, disable 'unused' warnings since they will mostly be
484  // noise.
485  if (!Diags.hasErrorOccurred()) {
486    // Output warning for unused file scoped decls.
487    for (llvm::SmallVectorImpl<const DeclaratorDecl*>::iterator
488           I = UnusedFileScopedDecls.begin(),
489           E = UnusedFileScopedDecls.end(); I != E; ++I) {
490      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
491        const FunctionDecl *DiagD;
492        if (!FD->hasBody(DiagD))
493          DiagD = FD;
494        if (DiagD->isDeleted())
495          continue; // Deleted functions are supposed to be unused.
496        if (DiagD->isReferenced()) {
497          if (isa<CXXMethodDecl>(DiagD))
498            Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
499                  << DiagD->getDeclName();
500          else
501            Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
502                  << /*function*/0 << DiagD->getDeclName();
503        } else {
504          Diag(DiagD->getLocation(),
505               isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
506                                         : diag::warn_unused_function)
507                << DiagD->getDeclName();
508        }
509      } else {
510        const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
511        if (!DiagD)
512          DiagD = cast<VarDecl>(*I);
513        if (DiagD->isReferenced()) {
514          Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
515                << /*variable*/1 << DiagD->getDeclName();
516        } else {
517          Diag(DiagD->getLocation(), diag::warn_unused_variable)
518                << DiagD->getDeclName();
519        }
520      }
521    }
522
523    checkUndefinedInternals(*this);
524  }
525
526  // Check we've noticed that we're no longer parsing the initializer for every
527  // variable. If we miss cases, then at best we have a performance issue and
528  // at worst a rejects-valid bug.
529  assert(ParsingInitForAutoVars.empty() &&
530         "Didn't unmark var as having its initializer parsed");
531
532  TUScope = 0;
533}
534
535
536//===----------------------------------------------------------------------===//
537// Helper functions.
538//===----------------------------------------------------------------------===//
539
540DeclContext *Sema::getFunctionLevelDeclContext() {
541  DeclContext *DC = CurContext;
542
543  while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC))
544    DC = DC->getParent();
545
546  return DC;
547}
548
549/// getCurFunctionDecl - If inside of a function body, this returns a pointer
550/// to the function decl for the function being parsed.  If we're currently
551/// in a 'block', this returns the containing context.
552FunctionDecl *Sema::getCurFunctionDecl() {
553  DeclContext *DC = getFunctionLevelDeclContext();
554  return dyn_cast<FunctionDecl>(DC);
555}
556
557ObjCMethodDecl *Sema::getCurMethodDecl() {
558  DeclContext *DC = getFunctionLevelDeclContext();
559  return dyn_cast<ObjCMethodDecl>(DC);
560}
561
562NamedDecl *Sema::getCurFunctionOrMethodDecl() {
563  DeclContext *DC = getFunctionLevelDeclContext();
564  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
565    return cast<NamedDecl>(DC);
566  return 0;
567}
568
569Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
570  if (!isActive())
571    return;
572
573  if (llvm::Optional<TemplateDeductionInfo*> Info = SemaRef.isSFINAEContext()) {
574    switch (DiagnosticIDs::getDiagnosticSFINAEResponse(getDiagID())) {
575    case DiagnosticIDs::SFINAE_Report:
576      // Fall through; we'll report the diagnostic below.
577      break;
578
579    case DiagnosticIDs::SFINAE_AccessControl:
580      // Per C++ Core Issue 1170, access control is part of SFINAE.
581      // Additionally, the AccessCheckingSFINAE flag can be used to temporary
582      // make access control a part of SFINAE for the purposes of checking
583      // type traits.
584      if (!SemaRef.AccessCheckingSFINAE &&
585          !SemaRef.getLangOptions().CPlusPlus0x)
586        break;
587
588    case DiagnosticIDs::SFINAE_SubstitutionFailure:
589      // Count this failure so that we know that template argument deduction
590      // has failed.
591      ++SemaRef.NumSFINAEErrors;
592      SemaRef.Diags.setLastDiagnosticIgnored();
593      SemaRef.Diags.Clear();
594      Clear();
595      return;
596
597    case DiagnosticIDs::SFINAE_Suppress:
598      // Make a copy of this suppressed diagnostic and store it with the
599      // template-deduction information;
600      FlushCounts();
601      DiagnosticInfo DiagInfo(&SemaRef.Diags);
602
603      if (*Info)
604        (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
605                        PartialDiagnostic(DiagInfo,
606                                          SemaRef.Context.getDiagAllocator()));
607
608      // Suppress this diagnostic.
609      SemaRef.Diags.setLastDiagnosticIgnored();
610      SemaRef.Diags.Clear();
611      Clear();
612      return;
613    }
614  }
615
616  // Emit the diagnostic.
617  if (!this->Emit())
618    return;
619
620  // If this is not a note, and we're in a template instantiation
621  // that is different from the last template instantiation where
622  // we emitted an error, print a template instantiation
623  // backtrace.
624  if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
625      !SemaRef.ActiveTemplateInstantiations.empty() &&
626      SemaRef.ActiveTemplateInstantiations.back()
627        != SemaRef.LastTemplateInstantiationErrorContext) {
628    SemaRef.PrintInstantiationStack();
629    SemaRef.LastTemplateInstantiationErrorContext
630      = SemaRef.ActiveTemplateInstantiations.back();
631  }
632}
633
634Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
635  DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
636  return SemaDiagnosticBuilder(DB, *this, DiagID);
637}
638
639Sema::SemaDiagnosticBuilder
640Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
641  SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
642  PD.Emit(Builder);
643
644  return Builder;
645}
646
647/// \brief Looks through the macro-instantiation chain for the given
648/// location, looking for a macro instantiation with the given name.
649/// If one is found, returns true and sets the location to that
650/// instantiation loc.
651bool Sema::findMacroSpelling(SourceLocation &locref, llvm::StringRef name) {
652  SourceLocation loc = locref;
653  if (!loc.isMacroID()) return false;
654
655  // There's no good way right now to look at the intermediate
656  // instantiations, so just jump to the instantiation location.
657  loc = getSourceManager().getInstantiationLoc(loc);
658
659  // If that's written with the name, stop here.
660  llvm::SmallVector<char, 16> buffer;
661  if (getPreprocessor().getSpelling(loc, buffer) == name) {
662    locref = loc;
663    return true;
664  }
665  return false;
666}
667
668/// \brief Determines the active Scope associated with the given declaration
669/// context.
670///
671/// This routine maps a declaration context to the active Scope object that
672/// represents that declaration context in the parser. It is typically used
673/// from "scope-less" code (e.g., template instantiation, lazy creation of
674/// declarations) that injects a name for name-lookup purposes and, therefore,
675/// must update the Scope.
676///
677/// \returns The scope corresponding to the given declaraion context, or NULL
678/// if no such scope is open.
679Scope *Sema::getScopeForContext(DeclContext *Ctx) {
680
681  if (!Ctx)
682    return 0;
683
684  Ctx = Ctx->getPrimaryContext();
685  for (Scope *S = getCurScope(); S; S = S->getParent()) {
686    // Ignore scopes that cannot have declarations. This is important for
687    // out-of-line definitions of static class members.
688    if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
689      if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
690        if (Ctx == Entity->getPrimaryContext())
691          return S;
692  }
693
694  return 0;
695}
696
697/// \brief Enter a new function scope
698void Sema::PushFunctionScope() {
699  if (FunctionScopes.size() == 1) {
700    // Use the "top" function scope rather than having to allocate
701    // memory for a new scope.
702    FunctionScopes.back()->Clear();
703    FunctionScopes.push_back(FunctionScopes.back());
704    return;
705  }
706
707  FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
708}
709
710void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
711  FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
712                                              BlockScope, Block));
713}
714
715void Sema::PopFunctionOrBlockScope(const AnalysisBasedWarnings::Policy *WP,
716                                   const Decl *D, const BlockExpr *blkExpr) {
717  FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
718  assert(!FunctionScopes.empty() && "mismatched push/pop!");
719
720  // Issue any analysis-based warnings.
721  if (WP && D)
722    AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
723  else {
724    for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
725         i = Scope->PossiblyUnreachableDiags.begin(),
726         e = Scope->PossiblyUnreachableDiags.end();
727         i != e; ++i) {
728      const sema::PossiblyUnreachableDiag &D = *i;
729      Diag(D.Loc, D.PD);
730    }
731  }
732
733  if (FunctionScopes.back() != Scope) {
734    delete Scope;
735  }
736}
737
738/// \brief Determine whether any errors occurred within this function/method/
739/// block.
740bool Sema::hasAnyErrorsInThisFunction() const {
741  return getCurFunction()->ErrorTrap.hasErrorOccurred();
742}
743
744BlockScopeInfo *Sema::getCurBlock() {
745  if (FunctionScopes.empty())
746    return 0;
747
748  return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
749}
750
751// Pin this vtable to this file.
752ExternalSemaSource::~ExternalSemaSource() {}
753
754std::pair<ObjCMethodList, ObjCMethodList>
755ExternalSemaSource::ReadMethodPool(Selector Sel) {
756  return std::pair<ObjCMethodList, ObjCMethodList>();
757}
758
759void PrettyDeclStackTraceEntry::print(llvm::raw_ostream &OS) const {
760  SourceLocation Loc = this->Loc;
761  if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
762  if (Loc.isValid()) {
763    Loc.print(OS, S.getSourceManager());
764    OS << ": ";
765  }
766  OS << Message;
767
768  if (TheDecl && isa<NamedDecl>(TheDecl)) {
769    std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
770    if (!Name.empty())
771      OS << " '" << Name << '\'';
772  }
773
774  OS << '\n';
775}
776
777/// \brief Figure out if an expression could be turned into a call.
778///
779/// Use this when trying to recover from an error where the programmer may have
780/// written just the name of a function instead of actually calling it.
781///
782/// \param E - The expression to examine.
783/// \param ZeroArgCallReturnTy - If the expression can be turned into a call
784///  with no arguments, this parameter is set to the type returned by such a
785///  call; otherwise, it is set to an empty QualType.
786/// \param NonTemplateOverloads - If the expression is an overloaded function
787///  name, this parameter is populated with the decls of the various overloads.
788bool Sema::isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy,
789                          UnresolvedSetImpl &NonTemplateOverloads) {
790  ZeroArgCallReturnTy = QualType();
791  NonTemplateOverloads.clear();
792  if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(&E)) {
793    for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
794         DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
795      // Our overload set may include TemplateDecls, which we'll ignore for our
796      // present purpose.
797      if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
798        NonTemplateOverloads.addDecl(*it);
799        if (OverloadDecl->getMinRequiredArguments() == 0)
800          ZeroArgCallReturnTy = OverloadDecl->getResultType();
801      }
802    }
803    return true;
804  }
805
806  if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(&E)) {
807    if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
808      if (Fun->getMinRequiredArguments() == 0)
809        ZeroArgCallReturnTy = Fun->getResultType();
810      return true;
811    }
812  }
813
814  // We don't have an expression that's convenient to get a FunctionDecl from,
815  // but we can at least check if the type is "function of 0 arguments".
816  QualType ExprTy = E.getType();
817  const FunctionType *FunTy = NULL;
818  QualType PointeeTy = ExprTy->getPointeeType();
819  if (!PointeeTy.isNull())
820    FunTy = PointeeTy->getAs<FunctionType>();
821  if (!FunTy)
822    FunTy = ExprTy->getAs<FunctionType>();
823  if (!FunTy && ExprTy == Context.BoundMemberTy) {
824    // Look for the bound-member type.  If it's still overloaded, give up,
825    // although we probably should have fallen into the OverloadExpr case above
826    // if we actually have an overloaded bound member.
827    QualType BoundMemberTy = Expr::findBoundMemberType(&E);
828    if (!BoundMemberTy.isNull())
829      FunTy = BoundMemberTy->castAs<FunctionType>();
830  }
831
832  if (const FunctionProtoType *FPT =
833      dyn_cast_or_null<FunctionProtoType>(FunTy)) {
834    if (FPT->getNumArgs() == 0)
835      ZeroArgCallReturnTy = FunTy->getResultType();
836    return true;
837  }
838  return false;
839}
840
841/// \brief Give notes for a set of overloads.
842///
843/// A companion to isExprCallable. In cases when the name that the programmer
844/// wrote was an overloaded function, we may be able to make some guesses about
845/// plausible overloads based on their return types; such guesses can be handed
846/// off to this method to be emitted as notes.
847///
848/// \param Overloads - The overloads to note.
849/// \param FinalNoteLoc - If we've suppressed printing some overloads due to
850///  -fshow-overloads=best, this is the location to attach to the note about too
851///  many candidates. Typically this will be the location of the original
852///  ill-formed expression.
853void Sema::NoteOverloads(const UnresolvedSetImpl &Overloads,
854                         const SourceLocation FinalNoteLoc) {
855  int ShownOverloads = 0;
856  int SuppressedOverloads = 0;
857  for (UnresolvedSetImpl::iterator It = Overloads.begin(),
858       DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
859    // FIXME: Magic number for max shown overloads stolen from
860    // OverloadCandidateSet::NoteCandidates.
861    if (ShownOverloads >= 4 &&
862        Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
863      ++SuppressedOverloads;
864      continue;
865    }
866    Diag(cast<FunctionDecl>(*It)->getSourceRange().getBegin(),
867         diag::note_member_ref_possible_intended_overload);
868    ++ShownOverloads;
869  }
870  if (SuppressedOverloads)
871    Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
872        << SuppressedOverloads;
873}
874