Sema.cpp revision 483b9f3bc05c5409e2c6643f1c9d91e21c8ff9d2
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/StmtCXX.h"
35#include "clang/Lex/Preprocessor.h"
36#include "clang/Basic/PartialDiagnostic.h"
37#include "clang/Basic/TargetInfo.h"
38using namespace clang;
39using namespace sema;
40
41FunctionScopeInfo::~FunctionScopeInfo() { }
42
43void FunctionScopeInfo::Clear() {
44  HasBranchProtectedScope = false;
45  HasBranchIntoScope = false;
46  HasIndirectGoto = false;
47
48  SwitchStack.clear();
49  Returns.clear();
50  ErrorTrap.reset();
51}
52
53BlockScopeInfo::~BlockScopeInfo() { }
54
55void Sema::ActOnTranslationUnitScope(Scope *S) {
56  TUScope = S;
57  PushDeclContext(S, Context.getTranslationUnitDecl());
58
59  VAListTagName = PP.getIdentifierInfo("__va_list_tag");
60
61  if (!Context.isInt128Installed() && // May be set by ASTReader.
62      PP.getTargetInfo().getPointerWidth(0) >= 64) {
63    TypeSourceInfo *TInfo;
64
65    // Install [u]int128_t for 64-bit targets.
66    TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty);
67    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
68                                          SourceLocation(),
69                                          &Context.Idents.get("__int128_t"),
70                                          TInfo), TUScope);
71
72    TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty);
73    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
74                                          SourceLocation(),
75                                          &Context.Idents.get("__uint128_t"),
76                                          TInfo), TUScope);
77    Context.setInt128Installed();
78  }
79
80
81  if (!PP.getLangOptions().ObjC1) return;
82
83  // Built-in ObjC types may already be set by ASTReader (hence isNull checks).
84  if (Context.getObjCSelType().isNull()) {
85    // Create the built-in typedef for 'SEL'.
86    QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy);
87    TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT);
88    TypedefDecl *SelTypedef
89      = TypedefDecl::Create(Context, CurContext, SourceLocation(),
90                            &Context.Idents.get("SEL"), SelInfo);
91    PushOnScopeChains(SelTypedef, TUScope);
92    Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
93    Context.ObjCSelRedefinitionType = Context.getObjCSelType();
94  }
95
96  // Synthesize "@class Protocol;
97  if (Context.getObjCProtoType().isNull()) {
98    ObjCInterfaceDecl *ProtocolDecl =
99      ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
100                                &Context.Idents.get("Protocol"),
101                                SourceLocation(), true);
102    Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
103    PushOnScopeChains(ProtocolDecl, TUScope, false);
104  }
105  // Create the built-in typedef for 'id'.
106  if (Context.getObjCIdType().isNull()) {
107    QualType T = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 0, 0);
108    T = Context.getObjCObjectPointerType(T);
109    TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(T);
110    TypedefDecl *IdTypedef
111      = TypedefDecl::Create(Context, CurContext, SourceLocation(),
112                            &Context.Idents.get("id"), IdInfo);
113    PushOnScopeChains(IdTypedef, TUScope);
114    Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
115    Context.ObjCIdRedefinitionType = Context.getObjCIdType();
116  }
117  // Create the built-in typedef for 'Class'.
118  if (Context.getObjCClassType().isNull()) {
119    QualType T = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 0, 0);
120    T = Context.getObjCObjectPointerType(T);
121    TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(T);
122    TypedefDecl *ClassTypedef
123      = TypedefDecl::Create(Context, CurContext, SourceLocation(),
124                            &Context.Idents.get("Class"), ClassInfo);
125    PushOnScopeChains(ClassTypedef, TUScope);
126    Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
127    Context.ObjCClassRedefinitionType = Context.getObjCClassType();
128  }
129}
130
131Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
132           bool CompleteTranslationUnit,
133           CodeCompleteConsumer *CodeCompleter)
134  : TheTargetAttributesSema(0), FPFeatures(pp.getLangOptions()),
135    LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
136    Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
137    ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0),
138    PackContext(0), VisContext(0),
139    IdResolver(pp.getLangOptions()), CXXTypeInfoDecl(0), MSVCGuidDecl(0),
140    GlobalNewDeleteDeclared(false),
141    CompleteTranslationUnit(CompleteTranslationUnit),
142    NumSFINAEErrors(0), SuppressAccessChecking(false),
143    AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
144    NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
145    CurrentInstantiationScope(0), TyposCorrected(0),
146    AnalysisWarnings(*this)
147{
148  TUScope = 0;
149  if (getLangOptions().CPlusPlus)
150    FieldCollector.reset(new CXXFieldCollector());
151
152  // Tell diagnostics how to render things from the AST library.
153  PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
154                                       &Context);
155
156  ExprEvalContexts.push_back(
157                  ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0));
158
159  FunctionScopes.push_back(new FunctionScopeInfo(Diags));
160}
161
162void Sema::Initialize() {
163  // Tell the AST consumer about this Sema object.
164  Consumer.Initialize(Context);
165
166  // FIXME: Isn't this redundant with the initialization above?
167  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
168    SC->InitializeSema(*this);
169
170  // Tell the external Sema source about this Sema object.
171  if (ExternalSemaSource *ExternalSema
172      = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
173    ExternalSema->InitializeSema(*this);
174}
175
176Sema::~Sema() {
177  if (PackContext) FreePackedContext();
178  if (VisContext) FreeVisContext();
179  delete TheTargetAttributesSema;
180
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/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
198/// If there is already an implicit cast, merge into the existing one.
199/// The result is of the given category.
200void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
201                             CastKind Kind, ExprValueKind VK,
202                             const CXXCastPath *BasePath) {
203  QualType ExprTy = Context.getCanonicalType(Expr->getType());
204  QualType TypeTy = Context.getCanonicalType(Ty);
205
206  if (ExprTy == TypeTy)
207    return;
208
209  // If this is a derived-to-base cast to a through a virtual base, we
210  // need a vtable.
211  if (Kind == CK_DerivedToBase &&
212      BasePathInvolvesVirtualBase(*BasePath)) {
213    QualType T = Expr->getType();
214    if (const PointerType *Pointer = T->getAs<PointerType>())
215      T = Pointer->getPointeeType();
216    if (const RecordType *RecordTy = T->getAs<RecordType>())
217      MarkVTableUsed(Expr->getLocStart(),
218                     cast<CXXRecordDecl>(RecordTy->getDecl()));
219  }
220
221  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
222    if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
223      ImpCast->setType(Ty);
224      ImpCast->setValueKind(VK);
225      return;
226    }
227  }
228
229  Expr = ImplicitCastExpr::Create(Context, Ty, Kind, Expr, BasePath, VK);
230}
231
232ExprValueKind Sema::CastCategory(Expr *E) {
233  Expr::Classification Classification = E->Classify(Context);
234  return Classification.isRValue() ? VK_RValue :
235      (Classification.isLValue() ? VK_LValue : VK_XValue);
236}
237
238/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
239static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
240  if (D->isUsed())
241    return true;
242
243  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
244    // UnusedFileScopedDecls stores the first declaration.
245    // The declaration may have become definition so check again.
246    const FunctionDecl *DeclToCheck;
247    if (FD->hasBody(DeclToCheck))
248      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
249
250    // Later redecls may add new information resulting in not having to warn,
251    // so check again.
252    DeclToCheck = FD->getMostRecentDeclaration();
253    if (DeclToCheck != FD)
254      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
255  }
256
257  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
258    // UnusedFileScopedDecls stores the first declaration.
259    // The declaration may have become definition so check again.
260    const VarDecl *DeclToCheck = VD->getDefinition();
261    if (DeclToCheck)
262      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
263
264    // Later redecls may add new information resulting in not having to warn,
265    // so check again.
266    DeclToCheck = VD->getMostRecentDeclaration();
267    if (DeclToCheck != VD)
268      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
269  }
270
271  return false;
272}
273
274namespace {
275  struct UndefinedInternal {
276    NamedDecl *decl;
277    FullSourceLoc useLoc;
278
279    UndefinedInternal(NamedDecl *decl, FullSourceLoc useLoc)
280      : decl(decl), useLoc(useLoc) {}
281  };
282
283  bool operator<(const UndefinedInternal &l, const UndefinedInternal &r) {
284    return l.useLoc.isBeforeInTranslationUnitThan(r.useLoc);
285  }
286}
287
288/// checkUndefinedInternals - Check for undefined objects with internal linkage.
289static void checkUndefinedInternals(Sema &S) {
290  if (S.UndefinedInternals.empty()) return;
291
292  // Collect all the still-undefined entities with internal linkage.
293  llvm::SmallVector<UndefinedInternal, 16> undefined;
294  for (llvm::DenseMap<NamedDecl*,SourceLocation>::iterator
295         i = S.UndefinedInternals.begin(), e = S.UndefinedInternals.end();
296       i != e; ++i) {
297    NamedDecl *decl = i->first;
298
299    // Ignore attributes that have become invalid.
300    if (decl->isInvalidDecl()) continue;
301
302    // __attribute__((weakref)) is basically a definition.
303    if (decl->hasAttr<WeakRefAttr>()) continue;
304
305    if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
306      if (fn->isPure() || fn->hasBody())
307        continue;
308    } else {
309      if (cast<VarDecl>(decl)->hasDefinition() != VarDecl::DeclarationOnly)
310        continue;
311    }
312
313    // We build a FullSourceLoc so that we can sort with array_pod_sort.
314    FullSourceLoc loc(i->second, S.Context.getSourceManager());
315    undefined.push_back(UndefinedInternal(decl, loc));
316  }
317
318  if (undefined.empty()) return;
319
320  // Sort (in order of use site) so that we're not (as) dependent on
321  // the iteration order through an llvm::DenseMap.
322  llvm::array_pod_sort(undefined.begin(), undefined.end());
323
324  for (llvm::SmallVectorImpl<UndefinedInternal>::iterator
325         i = undefined.begin(), e = undefined.end(); i != e; ++i) {
326    NamedDecl *decl = i->decl;
327    S.Diag(decl->getLocation(), diag::warn_undefined_internal)
328      << isa<VarDecl>(decl) << decl;
329    S.Diag(i->useLoc, diag::note_used_here);
330  }
331}
332
333/// ActOnEndOfTranslationUnit - This is called at the very end of the
334/// translation unit when EOF is reached and all but the top-level scope is
335/// popped.
336void Sema::ActOnEndOfTranslationUnit() {
337  // At PCH writing, implicit instantiations and VTable handling info are
338  // stored and performed when the PCH is included.
339  if (CompleteTranslationUnit) {
340    // If any dynamic classes have their key function defined within
341    // this translation unit, then those vtables are considered "used" and must
342    // be emitted.
343    for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
344      assert(!DynamicClasses[I]->isDependentType() &&
345             "Should not see dependent types here!");
346      if (const CXXMethodDecl *KeyFunction
347          = Context.getKeyFunction(DynamicClasses[I])) {
348        const FunctionDecl *Definition = 0;
349        if (KeyFunction->hasBody(Definition))
350          MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
351      }
352    }
353
354    // If DefinedUsedVTables ends up marking any virtual member functions it
355    // might lead to more pending template instantiations, which we then need
356    // to instantiate.
357    DefineUsedVTables();
358
359    // C++: Perform implicit template instantiations.
360    //
361    // FIXME: When we perform these implicit instantiations, we do not
362    // carefully keep track of the point of instantiation (C++ [temp.point]).
363    // This means that name lookup that occurs within the template
364    // instantiation will always happen at the end of the translation unit,
365    // so it will find some names that should not be found. Although this is
366    // common behavior for C++ compilers, it is technically wrong. In the
367    // future, we either need to be able to filter the results of name lookup
368    // or we need to perform template instantiations earlier.
369    PerformPendingInstantiations();
370  }
371
372  // Remove file scoped decls that turned out to be used.
373  UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(),
374                                             UnusedFileScopedDecls.end(),
375                              std::bind1st(std::ptr_fun(ShouldRemoveFromUnused),
376                                           this)),
377                              UnusedFileScopedDecls.end());
378
379  if (!CompleteTranslationUnit) {
380    TUScope = 0;
381    return;
382  }
383
384  // Check for #pragma weak identifiers that were never declared
385  // FIXME: This will cause diagnostics to be emitted in a non-determinstic
386  // order!  Iterating over a densemap like this is bad.
387  for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
388       I = WeakUndeclaredIdentifiers.begin(),
389       E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
390    if (I->second.getUsed()) continue;
391
392    Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
393      << I->first;
394  }
395
396  // C99 6.9.2p2:
397  //   A declaration of an identifier for an object that has file
398  //   scope without an initializer, and without a storage-class
399  //   specifier or with the storage-class specifier static,
400  //   constitutes a tentative definition. If a translation unit
401  //   contains one or more tentative definitions for an identifier,
402  //   and the translation unit contains no external definition for
403  //   that identifier, then the behavior is exactly as if the
404  //   translation unit contains a file scope declaration of that
405  //   identifier, with the composite type as of the end of the
406  //   translation unit, with an initializer equal to 0.
407  llvm::SmallSet<VarDecl *, 32> Seen;
408  for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) {
409    VarDecl *VD = TentativeDefinitions[i]->getActingDefinition();
410
411    // If the tentative definition was completed, getActingDefinition() returns
412    // null. If we've already seen this variable before, insert()'s second
413    // return value is false.
414    if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
415      continue;
416
417    if (const IncompleteArrayType *ArrayT
418        = Context.getAsIncompleteArrayType(VD->getType())) {
419      if (RequireCompleteType(VD->getLocation(),
420                              ArrayT->getElementType(),
421                              diag::err_tentative_def_incomplete_type_arr)) {
422        VD->setInvalidDecl();
423        continue;
424      }
425
426      // Set the length of the array to 1 (C99 6.9.2p5).
427      Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
428      llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
429      QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
430                                                One, ArrayType::Normal, 0);
431      VD->setType(T);
432    } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
433                                   diag::err_tentative_def_incomplete_type))
434      VD->setInvalidDecl();
435
436    // Notify the consumer that we've completed a tentative definition.
437    if (!VD->isInvalidDecl())
438      Consumer.CompleteTentativeDefinition(VD);
439
440  }
441
442  // If there were errors, disable 'unused' warnings since they will mostly be
443  // noise.
444  if (!Diags.hasErrorOccurred()) {
445    // Output warning for unused file scoped decls.
446    for (llvm::SmallVectorImpl<const DeclaratorDecl*>::iterator
447           I = UnusedFileScopedDecls.begin(),
448           E = UnusedFileScopedDecls.end(); I != E; ++I) {
449      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
450        const FunctionDecl *DiagD;
451        if (!FD->hasBody(DiagD))
452          DiagD = FD;
453        Diag(DiagD->getLocation(),
454             isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
455                                       : diag::warn_unused_function)
456              << DiagD->getDeclName();
457      } else {
458        const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
459        if (!DiagD)
460          DiagD = cast<VarDecl>(*I);
461        Diag(DiagD->getLocation(), diag::warn_unused_variable)
462              << DiagD->getDeclName();
463      }
464    }
465
466    checkUndefinedInternals(*this);
467  }
468
469  // Check we've noticed that we're no longer parsing the initializer for every
470  // variable. If we miss cases, then at best we have a performance issue and
471  // at worst a rejects-valid bug.
472  assert(ParsingInitForAutoVars.empty() &&
473         "Didn't unmark var as having its initializer parsed");
474
475  TUScope = 0;
476}
477
478
479//===----------------------------------------------------------------------===//
480// Helper functions.
481//===----------------------------------------------------------------------===//
482
483DeclContext *Sema::getFunctionLevelDeclContext() {
484  DeclContext *DC = CurContext;
485
486  while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC))
487    DC = DC->getParent();
488
489  return DC;
490}
491
492/// getCurFunctionDecl - If inside of a function body, this returns a pointer
493/// to the function decl for the function being parsed.  If we're currently
494/// in a 'block', this returns the containing context.
495FunctionDecl *Sema::getCurFunctionDecl() {
496  DeclContext *DC = getFunctionLevelDeclContext();
497  return dyn_cast<FunctionDecl>(DC);
498}
499
500ObjCMethodDecl *Sema::getCurMethodDecl() {
501  DeclContext *DC = getFunctionLevelDeclContext();
502  return dyn_cast<ObjCMethodDecl>(DC);
503}
504
505NamedDecl *Sema::getCurFunctionOrMethodDecl() {
506  DeclContext *DC = getFunctionLevelDeclContext();
507  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
508    return cast<NamedDecl>(DC);
509  return 0;
510}
511
512Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
513  if (!isActive())
514    return;
515
516  if (llvm::Optional<TemplateDeductionInfo*> Info = SemaRef.isSFINAEContext()) {
517    switch (DiagnosticIDs::getDiagnosticSFINAEResponse(getDiagID())) {
518    case DiagnosticIDs::SFINAE_Report:
519      // Fall through; we'll report the diagnostic below.
520      break;
521
522    case DiagnosticIDs::SFINAE_AccessControl:
523      // Unless access checking is specifically called out as a SFINAE
524      // error, report this diagnostic.
525      if (!SemaRef.AccessCheckingSFINAE)
526        break;
527
528    case DiagnosticIDs::SFINAE_SubstitutionFailure:
529      // Count this failure so that we know that template argument deduction
530      // has failed.
531      ++SemaRef.NumSFINAEErrors;
532      SemaRef.Diags.setLastDiagnosticIgnored();
533      SemaRef.Diags.Clear();
534      Clear();
535      return;
536
537    case DiagnosticIDs::SFINAE_Suppress:
538      // Make a copy of this suppressed diagnostic and store it with the
539      // template-deduction information;
540      FlushCounts();
541      DiagnosticInfo DiagInfo(&SemaRef.Diags);
542
543      if (*Info)
544        (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
545                        PartialDiagnostic(DiagInfo,
546                                          SemaRef.Context.getDiagAllocator()));
547
548      // Suppress this diagnostic.
549      SemaRef.Diags.setLastDiagnosticIgnored();
550      SemaRef.Diags.Clear();
551      Clear();
552      return;
553    }
554  }
555
556  // Emit the diagnostic.
557  if (!this->Emit())
558    return;
559
560  // If this is not a note, and we're in a template instantiation
561  // that is different from the last template instantiation where
562  // we emitted an error, print a template instantiation
563  // backtrace.
564  if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
565      !SemaRef.ActiveTemplateInstantiations.empty() &&
566      SemaRef.ActiveTemplateInstantiations.back()
567        != SemaRef.LastTemplateInstantiationErrorContext) {
568    SemaRef.PrintInstantiationStack();
569    SemaRef.LastTemplateInstantiationErrorContext
570      = SemaRef.ActiveTemplateInstantiations.back();
571  }
572}
573
574Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
575  DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
576  return SemaDiagnosticBuilder(DB, *this, DiagID);
577}
578
579Sema::SemaDiagnosticBuilder
580Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
581  SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
582  PD.Emit(Builder);
583
584  return Builder;
585}
586
587/// \brief Determines the active Scope associated with the given declaration
588/// context.
589///
590/// This routine maps a declaration context to the active Scope object that
591/// represents that declaration context in the parser. It is typically used
592/// from "scope-less" code (e.g., template instantiation, lazy creation of
593/// declarations) that injects a name for name-lookup purposes and, therefore,
594/// must update the Scope.
595///
596/// \returns The scope corresponding to the given declaraion context, or NULL
597/// if no such scope is open.
598Scope *Sema::getScopeForContext(DeclContext *Ctx) {
599
600  if (!Ctx)
601    return 0;
602
603  Ctx = Ctx->getPrimaryContext();
604  for (Scope *S = getCurScope(); S; S = S->getParent()) {
605    // Ignore scopes that cannot have declarations. This is important for
606    // out-of-line definitions of static class members.
607    if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
608      if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
609        if (Ctx == Entity->getPrimaryContext())
610          return S;
611  }
612
613  return 0;
614}
615
616/// \brief Enter a new function scope
617void Sema::PushFunctionScope() {
618  if (FunctionScopes.size() == 1) {
619    // Use the "top" function scope rather than having to allocate
620    // memory for a new scope.
621    FunctionScopes.back()->Clear();
622    FunctionScopes.push_back(FunctionScopes.back());
623    return;
624  }
625
626  FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
627}
628
629void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
630  FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
631                                              BlockScope, Block));
632}
633
634void Sema::PopFunctionOrBlockScope() {
635  FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
636  assert(!FunctionScopes.empty() && "mismatched push/pop!");
637  if (FunctionScopes.back() != Scope)
638    delete Scope;
639}
640
641/// \brief Determine whether any errors occurred within this function/method/
642/// block.
643bool Sema::hasAnyErrorsInThisFunction() const {
644  return getCurFunction()->ErrorTrap.hasErrorOccurred();
645}
646
647BlockScopeInfo *Sema::getCurBlock() {
648  if (FunctionScopes.empty())
649    return 0;
650
651  return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
652}
653
654// Pin this vtable to this file.
655ExternalSemaSource::~ExternalSemaSource() {}
656
657std::pair<ObjCMethodList, ObjCMethodList>
658ExternalSemaSource::ReadMethodPool(Selector Sel) {
659  return std::pair<ObjCMethodList, ObjCMethodList>();
660}
661
662void PrettyDeclStackTraceEntry::print(llvm::raw_ostream &OS) const {
663  SourceLocation Loc = this->Loc;
664  if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
665  if (Loc.isValid()) {
666    Loc.print(OS, S.getSourceManager());
667    OS << ": ";
668  }
669  OS << Message;
670
671  if (TheDecl && isa<NamedDecl>(TheDecl)) {
672    std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
673    if (!Name.empty())
674      OS << " '" << Name << '\'';
675  }
676
677  OS << '\n';
678}
679