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