Sema.cpp 28 KB

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