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