blob: 6143492ea7637b0e3000a75ad2dbf13e29b6e313 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
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
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Sema.h"
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000016#include "TargetAttributesSema.h"
Ryan Flynne25ff832009-07-30 03:15:39 +000017#include "llvm/ADT/DenseMap.h"
Sebastian Redle9d12b62010-01-31 22:27:38 +000018#include "llvm/ADT/SmallSet.h"
John McCall680523a2009-11-07 03:30:10 +000019#include "llvm/ADT/APFloat.h"
John McCall5f1e0942010-08-24 08:50:51 +000020#include "clang/Sema/CXXFieldCollector.h"
John McCall76bd1f32010-06-01 09:23:16 +000021#include "clang/Sema/ExternalSemaSource.h"
John McCall5f1e0942010-08-24 08:50:51 +000022#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000023#include "clang/Sema/ScopeInfo.h"
Douglas Gregor46ea32a2010-08-12 22:51:45 +000024#include "clang/Sema/SemaConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/AST/ASTContext.h"
Douglas Gregor79a9a342010-02-09 22:26:47 +000026#include "clang/AST/ASTDiagnostic.h"
John McCall384aff82010-08-25 07:42:41 +000027#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000028#include "clang/AST/DeclObjC.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000029#include "clang/AST/Expr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "clang/Lex/Preprocessor.h"
Anders Carlsson91a0cc92009-08-26 22:33:56 +000031#include "clang/Basic/PartialDiagnostic.h"
Chris Lattner4d150c82009-04-30 06:18:40 +000032#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000034using namespace sema;
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000035
36FunctionScopeInfo::~FunctionScopeInfo() { }
37
38void FunctionScopeInfo::Clear(unsigned NumErrors) {
John McCallb60a77e2010-08-01 00:26:45 +000039 HasBranchProtectedScope = false;
40 HasBranchIntoScope = false;
41 HasIndirectGoto = false;
42
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000043 LabelMap.clear();
44 SwitchStack.clear();
Douglas Gregor5077c382010-05-15 06:01:05 +000045 Returns.clear();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000046 NumErrorsAtStartOfFunction = NumErrors;
47}
48
49BlockScopeInfo::~BlockScopeInfo() { }
50
Steve Naroffb216c882007-10-09 22:01:59 +000051void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
52 TUScope = S;
Douglas Gregor44b43212008-12-11 16:49:14 +000053 PushDeclContext(S, Context.getTranslationUnitDecl());
Mike Stump1eb44332009-09-09 15:08:12 +000054
John McCallc7e04da2010-05-28 18:45:08 +000055 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
56
Sebastian Redlc43b54c2010-08-18 23:56:43 +000057 if (!Context.isInt128Installed() && // May be set by ASTReader.
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +000058 PP.getTargetInfo().getPointerWidth(0) >= 64) {
John McCalla93c9342009-12-07 02:54:59 +000059 TypeSourceInfo *TInfo;
John McCallba6a9bd2009-10-24 08:00:42 +000060
Chris Lattner4d150c82009-04-30 06:18:40 +000061 // Install [u]int128_t for 64-bit targets.
John McCalla93c9342009-12-07 02:54:59 +000062 TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty);
Chris Lattner4d150c82009-04-30 06:18:40 +000063 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
64 SourceLocation(),
65 &Context.Idents.get("__int128_t"),
John McCalla93c9342009-12-07 02:54:59 +000066 TInfo), TUScope);
John McCallba6a9bd2009-10-24 08:00:42 +000067
John McCalla93c9342009-12-07 02:54:59 +000068 TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty);
Chris Lattner4d150c82009-04-30 06:18:40 +000069 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
70 SourceLocation(),
71 &Context.Idents.get("__uint128_t"),
John McCalla93c9342009-12-07 02:54:59 +000072 TInfo), TUScope);
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +000073 Context.setInt128Installed();
Chris Lattner4d150c82009-04-30 06:18:40 +000074 }
Mike Stump1eb44332009-09-09 15:08:12 +000075
76
Chris Lattner2ae34ed2008-02-06 00:46:58 +000077 if (!PP.getLangOptions().ObjC1) return;
Mike Stump1eb44332009-09-09 15:08:12 +000078
Sebastian Redlc43b54c2010-08-18 23:56:43 +000079 // Built-in ObjC types may already be set by ASTReader (hence isNull checks).
Douglas Gregor319ac892009-04-23 22:29:11 +000080 if (Context.getObjCSelType().isNull()) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +000081 // Create the built-in typedef for 'SEL'.
Fariborz Jahanian04765ac2009-11-23 18:04:25 +000082 QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy);
John McCalla93c9342009-12-07 02:54:59 +000083 TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT);
John McCallba6a9bd2009-10-24 08:00:42 +000084 TypedefDecl *SelTypedef
85 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
86 &Context.Idents.get("SEL"), SelInfo);
Douglas Gregor319ac892009-04-23 22:29:11 +000087 PushOnScopeChains(SelTypedef, TUScope);
88 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000089 Context.ObjCSelRedefinitionType = Context.getObjCSelType();
Douglas Gregor319ac892009-04-23 22:29:11 +000090 }
Chris Lattner6ee1f9c2008-06-21 20:20:39 +000091
Chris Lattner6ee1f9c2008-06-21 20:20:39 +000092 // Synthesize "@class Protocol;
Douglas Gregor319ac892009-04-23 22:29:11 +000093 if (Context.getObjCProtoType().isNull()) {
94 ObjCInterfaceDecl *ProtocolDecl =
95 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000096 &Context.Idents.get("Protocol"),
Douglas Gregordeacbdc2010-08-11 12:19:30 +000097 SourceLocation(), true);
Douglas Gregor319ac892009-04-23 22:29:11 +000098 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
Fariborz Jahanian10324db2009-11-18 23:15:37 +000099 PushOnScopeChains(ProtocolDecl, TUScope, false);
Douglas Gregor319ac892009-04-23 22:29:11 +0000100 }
Steve Naroffde2e22d2009-07-15 18:40:39 +0000101 // Create the built-in typedef for 'id'.
Douglas Gregor319ac892009-04-23 22:29:11 +0000102 if (Context.getObjCIdType().isNull()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000103 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 0, 0);
104 T = Context.getObjCObjectPointerType(T);
105 TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +0000106 TypedefDecl *IdTypedef
107 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
108 &Context.Idents.get("id"), IdInfo);
Douglas Gregor319ac892009-04-23 22:29:11 +0000109 PushOnScopeChains(IdTypedef, TUScope);
110 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
David Chisnall0f436562009-08-17 16:35:33 +0000111 Context.ObjCIdRedefinitionType = Context.getObjCIdType();
Douglas Gregor319ac892009-04-23 22:29:11 +0000112 }
Steve Naroffde2e22d2009-07-15 18:40:39 +0000113 // Create the built-in typedef for 'Class'.
Steve Naroff14108da2009-07-10 23:34:53 +0000114 if (Context.getObjCClassType().isNull()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000115 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 0, 0);
116 T = Context.getObjCObjectPointerType(T);
117 TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +0000118 TypedefDecl *ClassTypedef
119 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
120 &Context.Idents.get("Class"), ClassInfo);
Steve Naroff14108da2009-07-10 23:34:53 +0000121 PushOnScopeChains(ClassTypedef, TUScope);
122 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
David Chisnall0f436562009-08-17 16:35:33 +0000123 Context.ObjCClassRedefinitionType = Context.getObjCClassType();
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000124 }
Steve Naroff3b950172007-10-10 21:53:07 +0000125}
126
Douglas Gregorf807fe02009-04-14 16:27:31 +0000127Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
Daniel Dunbar3a2838d2009-11-13 08:58:20 +0000128 bool CompleteTranslationUnit,
129 CodeCompleteConsumer *CodeCompleter)
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000130 : TheTargetAttributesSema(0),
131 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
Mike Stump1eb44332009-09-09 15:08:12 +0000132 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
Daniel Dunbar3a2838d2009-11-13 08:58:20 +0000133 ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0),
John McCall781472f2010-08-25 08:40:02 +0000134 PackContext(0), VisContext(0), ParsingDeclDepth(0),
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +0000135 IdResolver(pp.getLangOptions()), GlobalNewDeleteDeclared(false),
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000136 CompleteTranslationUnit(CompleteTranslationUnit),
Chandler Carruth926c4b42010-06-28 08:39:25 +0000137 NumSFINAEErrors(0), SuppressAccessChecking(false),
138 NonInstantiationEntries(0), CurrentInstantiationScope(0), TyposCorrected(0),
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000139 AnalysisWarnings(*this)
Douglas Gregorf35f8282009-11-11 21:54:23 +0000140{
Steve Naroff3b950172007-10-10 21:53:07 +0000141 TUScope = 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000142 if (getLangOptions().CPlusPlus)
143 FieldCollector.reset(new CXXFieldCollector());
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Chris Lattner22caddc2008-11-23 09:13:29 +0000145 // Tell diagnostics how to render things from the AST library.
Douglas Gregor79a9a342010-02-09 22:26:47 +0000146 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
147 &Context);
Douglas Gregor2afce722009-11-26 00:44:06 +0000148
149 ExprEvalContexts.push_back(
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000150 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0));
John McCall781472f2010-08-25 08:40:02 +0000151
152 FunctionScopes.push_back(new FunctionScopeInfo(Diags.getNumErrors()));
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000153}
154
155void Sema::Initialize() {
156 // Tell the AST consumer about this Sema object.
157 Consumer.Initialize(Context);
158
159 // FIXME: Isn't this redundant with the initialization above?
160 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
161 SC->InitializeSema(*this);
162
163 // Tell the external Sema source about this Sema object.
164 if (ExternalSemaSource *ExternalSema
165 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
166 ExternalSema->InitializeSema(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000167}
168
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000169Sema::~Sema() {
170 if (PackContext) FreePackedContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +0000171 if (VisContext) FreeVisContext();
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000172 delete TheTargetAttributesSema;
John McCall781472f2010-08-25 08:40:02 +0000173
174 // Kill all the active scopes.
175 for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
176 delete FunctionScopes[I];
177 if (FunctionScopes.size() == 1)
178 delete FunctionScopes[0];
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000179
180 // Tell the SemaConsumer to forget about us; we're going out of scope.
181 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
182 SC->ForgetSema();
183
184 // Detach from the external Sema source.
185 if (ExternalSemaSource *ExternalSema
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000186 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000187 ExternalSema->ForgetSema();
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000188}
189
Mike Stump1eb44332009-09-09 15:08:12 +0000190/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Chris Lattner1e0a3902008-01-16 19:17:22 +0000191/// If there is already an implicit cast, merge into the existing one.
Sebastian Redl906082e2010-07-20 04:20:21 +0000192/// The result is of the given category.
Mike Stump1eb44332009-09-09 15:08:12 +0000193void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
Anders Carlsson88465d32010-04-23 22:18:37 +0000194 CastExpr::CastKind Kind,
Sebastian Redl906082e2010-07-20 04:20:21 +0000195 ImplicitCastExpr::ResultCategory Category,
John McCallf871d0c2010-08-07 06:22:56 +0000196 const CXXCastPath *BasePath) {
Mon P Wang3a2c7442008-09-04 08:38:01 +0000197 QualType ExprTy = Context.getCanonicalType(Expr->getType());
198 QualType TypeTy = Context.getCanonicalType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Mon P Wang3a2c7442008-09-04 08:38:01 +0000200 if (ExprTy == TypeTy)
201 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000202
John McCall680523a2009-11-07 03:30:10 +0000203 if (Expr->getType()->isPointerType() && Ty->isPointerType()) {
204 QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType();
205 QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType();
Mon P Wang3a2c7442008-09-04 08:38:01 +0000206 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000207 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
208 << Expr->getSourceRange();
Mon P Wang3a2c7442008-09-04 08:38:01 +0000209 }
210 }
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000212 // If this is a derived-to-base cast to a through a virtual base, we
213 // need a vtable.
214 if (Kind == CastExpr::CK_DerivedToBase &&
John McCallf871d0c2010-08-07 06:22:56 +0000215 BasePathInvolvesVirtualBase(*BasePath)) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000216 QualType T = Expr->getType();
217 if (const PointerType *Pointer = T->getAs<PointerType>())
218 T = Pointer->getPointeeType();
219 if (const RecordType *RecordTy = T->getAs<RecordType>())
220 MarkVTableUsed(Expr->getLocStart(),
221 cast<CXXRecordDecl>(RecordTy->getDecl()));
222 }
223
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000224 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
John McCallf871d0c2010-08-07 06:22:56 +0000225 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
Anders Carlsson4c5fad32009-09-15 05:28:24 +0000226 ImpCast->setType(Ty);
Sebastian Redl906082e2010-07-20 04:20:21 +0000227 ImpCast->setCategory(Category);
Anders Carlsson4c5fad32009-09-15 05:28:24 +0000228 return;
229 }
230 }
231
John McCallf871d0c2010-08-07 06:22:56 +0000232 Expr = ImplicitCastExpr::Create(Context, Ty, Kind, Expr, BasePath, Category);
Sebastian Redl906082e2010-07-20 04:20:21 +0000233}
234
235ImplicitCastExpr::ResultCategory Sema::CastCategory(Expr *E) {
236 Expr::Classification Classification = E->Classify(Context);
237 return Classification.isRValue() ?
238 ImplicitCastExpr::RValue :
239 (Classification.isLValue() ?
240 ImplicitCastExpr::LValue :
241 ImplicitCastExpr::XValue);
Chris Lattner1e0a3902008-01-16 19:17:22 +0000242}
243
Chris Lattner394a3fd2007-08-31 04:53:24 +0000244void Sema::DeleteExpr(ExprTy *E) {
Chris Lattner394a3fd2007-08-31 04:53:24 +0000245}
246void Sema::DeleteStmt(StmtTy *S) {
Chris Lattner394a3fd2007-08-31 04:53:24 +0000247}
248
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000249/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
250static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
251 if (D->isUsed())
252 return true;
253
254 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
255 // UnusedFileScopedDecls stores the first declaration.
256 // The declaration may have become definition so check again.
257 const FunctionDecl *DeclToCheck;
258 if (FD->hasBody(DeclToCheck))
259 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
260
261 // Later redecls may add new information resulting in not having to warn,
262 // so check again.
263 DeclToCheck = FD->getMostRecentDeclaration();
264 if (DeclToCheck != FD)
265 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
266 }
267
268 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
269 // UnusedFileScopedDecls stores the first declaration.
270 // The declaration may have become definition so check again.
271 const VarDecl *DeclToCheck = VD->getDefinition();
272 if (DeclToCheck)
273 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
274
275 // Later redecls may add new information resulting in not having to warn,
276 // so check again.
277 DeclToCheck = VD->getMostRecentDeclaration();
278 if (DeclToCheck != VD)
279 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
280 }
281
282 return false;
283}
284
Chris Lattner9299f3f2008-08-23 03:19:52 +0000285/// ActOnEndOfTranslationUnit - This is called at the very end of the
286/// translation unit when EOF is reached and all but the top-level scope is
287/// popped.
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +0000288void Sema::ActOnEndOfTranslationUnit() {
289 // At PCH writing, implicit instantiations and VTable handling info are
290 // stored and performed when the PCH is included.
291 if (CompleteTranslationUnit)
292 while (1) {
293 // C++: Perform implicit template instantiations.
294 //
295 // FIXME: When we perform these implicit instantiations, we do not
296 // carefully keep track of the point of instantiation (C++ [temp.point]).
297 // This means that name lookup that occurs within the template
298 // instantiation will always happen at the end of the translation unit,
299 // so it will find some names that should not be found. Although this is
300 // common behavior for C++ compilers, it is technically wrong. In the
301 // future, we either need to be able to filter the results of name lookup
302 // or we need to perform template instantiations earlier.
Chandler Carruth62c78d52010-08-25 08:44:16 +0000303 PerformPendingInstantiations();
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +0000304
305 /// If DefinedUsedVTables ends up marking any virtual member
306 /// functions it might lead to more pending template
307 /// instantiations, which is why we need to loop here.
308 if (!DefineUsedVTables())
309 break;
310 }
Anders Carlssond6a637f2009-12-07 08:24:59 +0000311
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000312 // Remove file scoped decls that turned out to be used.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000313 UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(),
314 UnusedFileScopedDecls.end(),
315 std::bind1st(std::ptr_fun(ShouldRemoveFromUnused),
316 this)),
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000317 UnusedFileScopedDecls.end());
Douglas Gregor47268a32010-04-09 17:41:13 +0000318
Douglas Gregor87c08a52010-08-13 22:48:40 +0000319 if (!CompleteTranslationUnit) {
320 TUScope = 0;
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +0000321 return;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000322 }
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +0000323
Chris Lattner63d65f82009-09-08 18:19:27 +0000324 // Check for #pragma weak identifiers that were never declared
325 // FIXME: This will cause diagnostics to be emitted in a non-determinstic
326 // order! Iterating over a densemap like this is bad.
Ryan Flynne25ff832009-07-30 03:15:39 +0000327 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
Chris Lattner63d65f82009-09-08 18:19:27 +0000328 I = WeakUndeclaredIdentifiers.begin(),
329 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
330 if (I->second.getUsed()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Chris Lattner63d65f82009-09-08 18:19:27 +0000332 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
333 << I->first;
Ryan Flynne25ff832009-07-30 03:15:39 +0000334 }
335
Douglas Gregor275a3692009-03-10 23:43:53 +0000336 // C99 6.9.2p2:
337 // A declaration of an identifier for an object that has file
338 // scope without an initializer, and without a storage-class
339 // specifier or with the storage-class specifier static,
340 // constitutes a tentative definition. If a translation unit
341 // contains one or more tentative definitions for an identifier,
342 // and the translation unit contains no external definition for
343 // that identifier, then the behavior is exactly as if the
344 // translation unit contains a file scope declaration of that
345 // identifier, with the composite type as of the end of the
346 // translation unit, with an initializer equal to 0.
Sebastian Redle9d12b62010-01-31 22:27:38 +0000347 llvm::SmallSet<VarDecl *, 32> Seen;
348 for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) {
349 VarDecl *VD = TentativeDefinitions[i]->getActingDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Sebastian Redle9d12b62010-01-31 22:27:38 +0000351 // If the tentative definition was completed, getActingDefinition() returns
352 // null. If we've already seen this variable before, insert()'s second
353 // return value is false.
354 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000355 continue;
356
Mike Stump1eb44332009-09-09 15:08:12 +0000357 if (const IncompleteArrayType *ArrayT
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000358 = Context.getAsIncompleteArrayType(VD->getType())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000359 if (RequireCompleteType(VD->getLocation(),
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000360 ArrayT->getElementType(),
Chris Lattner63d65f82009-09-08 18:19:27 +0000361 diag::err_tentative_def_incomplete_type_arr)) {
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000362 VD->setInvalidDecl();
Chris Lattner63d65f82009-09-08 18:19:27 +0000363 continue;
Douglas Gregor275a3692009-03-10 23:43:53 +0000364 }
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Chris Lattner63d65f82009-09-08 18:19:27 +0000366 // Set the length of the array to 1 (C99 6.9.2p5).
367 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
368 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
John McCall46a617a2009-10-16 00:14:28 +0000369 QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
370 One, ArrayType::Normal, 0);
Chris Lattner63d65f82009-09-08 18:19:27 +0000371 VD->setType(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000372 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000373 diag::err_tentative_def_incomplete_type))
374 VD->setInvalidDecl();
375
376 // Notify the consumer that we've completed a tentative definition.
377 if (!VD->isInvalidDecl())
378 Consumer.CompleteTentativeDefinition(VD);
379
Douglas Gregor275a3692009-03-10 23:43:53 +0000380 }
Tanya Lattnere6bbc012010-02-12 00:07:30 +0000381
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000382 // Output warning for unused file scoped decls.
John McCallaab01322010-08-24 17:40:45 +0000383 for (llvm::SmallVectorImpl<const DeclaratorDecl*>::iterator
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000384 I = UnusedFileScopedDecls.begin(),
385 E = UnusedFileScopedDecls.end(); I != E; ++I) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000386 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
387 const FunctionDecl *DiagD;
388 if (!FD->hasBody(DiagD))
389 DiagD = FD;
Argyrios Kyrtzidis3d27b102010-08-17 21:43:11 +0000390 Diag(DiagD->getLocation(),
Argyrios Kyrtzidis42cbd782010-08-17 22:06:44 +0000391 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
Argyrios Kyrtzidis3d27b102010-08-17 21:43:11 +0000392 : diag::warn_unused_function)
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000393 << DiagD->getDeclName();
394 } else {
395 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
396 if (!DiagD)
397 DiagD = cast<VarDecl>(*I);
398 Diag(DiagD->getLocation(), diag::warn_unused_variable)
399 << DiagD->getDeclName();
400 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000401 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000402
403 TUScope = 0;
Chris Lattner9299f3f2008-08-23 03:19:52 +0000404}
405
406
Reid Spencer5f016e22007-07-11 17:01:13 +0000407//===----------------------------------------------------------------------===//
408// Helper functions.
409//===----------------------------------------------------------------------===//
410
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000411DeclContext *Sema::getFunctionLevelDeclContext() {
John McCalldb0ee1d2009-12-19 10:53:49 +0000412 DeclContext *DC = CurContext;
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Douglas Gregord9008312010-05-22 16:25:05 +0000414 while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC))
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000415 DC = DC->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000417 return DC;
418}
419
Chris Lattner371f2582008-12-04 23:50:19 +0000420/// getCurFunctionDecl - If inside of a function body, this returns a pointer
421/// to the function decl for the function being parsed. If we're currently
422/// in a 'block', this returns the containing context.
423FunctionDecl *Sema::getCurFunctionDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000424 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner371f2582008-12-04 23:50:19 +0000425 return dyn_cast<FunctionDecl>(DC);
426}
427
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000428ObjCMethodDecl *Sema::getCurMethodDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000429 DeclContext *DC = getFunctionLevelDeclContext();
Steve Naroffd7612e12008-11-17 16:28:52 +0000430 return dyn_cast<ObjCMethodDecl>(DC);
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000431}
Chris Lattner371f2582008-12-04 23:50:19 +0000432
433NamedDecl *Sema::getCurFunctionOrMethodDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000434 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner371f2582008-12-04 23:50:19 +0000435 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000436 return cast<NamedDecl>(DC);
Chris Lattner371f2582008-12-04 23:50:19 +0000437 return 0;
438}
439
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000440Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000441 if (!this->Emit())
442 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000444 // If this is not a note, and we're in a template instantiation
445 // that is different from the last template instantiation where
446 // we emitted an error, print a template instantiation
447 // backtrace.
448 if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
449 !SemaRef.ActiveTemplateInstantiations.empty() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000450 SemaRef.ActiveTemplateInstantiations.back()
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000451 != SemaRef.LastTemplateInstantiationErrorContext) {
452 SemaRef.PrintInstantiationStack();
Mike Stump1eb44332009-09-09 15:08:12 +0000453 SemaRef.LastTemplateInstantiationErrorContext
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000454 = SemaRef.ActiveTemplateInstantiations.back();
455 }
456}
Douglas Gregor2e222532009-07-02 17:08:52 +0000457
Douglas Gregoreab5d1e2010-03-25 22:17:48 +0000458Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
459 if (isSFINAEContext()) {
460 switch (Diagnostic::getDiagnosticSFINAEResponse(DiagID)) {
461 case Diagnostic::SFINAE_Report:
462 // Fall through; we'll report the diagnostic below.
463 break;
464
465 case Diagnostic::SFINAE_SubstitutionFailure:
466 // Count this failure so that we know that template argument deduction
467 // has failed.
468 ++NumSFINAEErrors;
469 // Fall through
470
471 case Diagnostic::SFINAE_Suppress:
472 // Suppress this diagnostic.
473 Diags.setLastDiagnosticIgnored();
474 return SemaDiagnosticBuilder(*this);
475 }
476 }
477
478 DiagnosticBuilder DB = Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
479 return SemaDiagnosticBuilder(DB, *this, DiagID);
480}
481
Anders Carlsson91a0cc92009-08-26 22:33:56 +0000482Sema::SemaDiagnosticBuilder
483Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
484 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
485 PD.Emit(Builder);
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Anders Carlsson91a0cc92009-08-26 22:33:56 +0000487 return Builder;
488}
489
Douglas Gregor23c94db2010-07-02 17:43:08 +0000490/// \brief Determines the active Scope associated with the given declaration
491/// context.
492///
493/// This routine maps a declaration context to the active Scope object that
494/// represents that declaration context in the parser. It is typically used
495/// from "scope-less" code (e.g., template instantiation, lazy creation of
496/// declarations) that injects a name for name-lookup purposes and, therefore,
497/// must update the Scope.
498///
499/// \returns The scope corresponding to the given declaraion context, or NULL
500/// if no such scope is open.
501Scope *Sema::getScopeForContext(DeclContext *Ctx) {
502
503 if (!Ctx)
504 return 0;
505
506 Ctx = Ctx->getPrimaryContext();
507 for (Scope *S = getCurScope(); S; S = S->getParent()) {
Sebastian Redlcddc69f2010-07-08 23:07:34 +0000508 // Ignore scopes that cannot have declarations. This is important for
509 // out-of-line definitions of static class members.
510 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
511 if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
512 if (Ctx == Entity->getPrimaryContext())
513 return S;
Douglas Gregor23c94db2010-07-02 17:43:08 +0000514 }
515
516 return 0;
517}
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000518
519/// \brief Enter a new function scope
520void Sema::PushFunctionScope() {
John McCall781472f2010-08-25 08:40:02 +0000521 if (FunctionScopes.size() == 1) {
522 // Use the "top" function scope rather than having to allocate
523 // memory for a new scope.
524 FunctionScopes.back()->Clear(getDiagnostics().getNumErrors());
525 FunctionScopes.push_back(FunctionScopes.back());
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000526 return;
527 }
528
529 FunctionScopes.push_back(
530 new FunctionScopeInfo(getDiagnostics().getNumErrors()));
531}
532
533void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
534 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics().getNumErrors(),
535 BlockScope, Block));
536}
537
538void Sema::PopFunctionOrBlockScope() {
John McCall781472f2010-08-25 08:40:02 +0000539 FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
540 assert(!FunctionScopes.empty() && "mismatched push/pop!");
541 if (FunctionScopes.back() != Scope)
542 delete Scope;
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000543}
544
545/// \brief Determine whether any errors occurred within this function/method/
546/// block.
547bool Sema::hasAnyErrorsInThisFunction() const {
John McCall781472f2010-08-25 08:40:02 +0000548 return getCurFunction()->NumErrorsAtStartOfFunction
549 != getDiagnostics().getNumErrors();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000550}
551
552BlockScopeInfo *Sema::getCurBlock() {
553 if (FunctionScopes.empty())
554 return 0;
555
556 return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
557}
John McCall76bd1f32010-06-01 09:23:16 +0000558
559// Pin this vtable to this file.
560ExternalSemaSource::~ExternalSemaSource() {}