blob: 92e3fdd72adba01963cfd61cb6c9df022f827345 [file] [log] [blame]
Chris Lattnerddd6fc82006-11-10 04:58:55 +00001//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
Chris Lattner3e7bd4e2006-08-17 05:51:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner3e7bd4e2006-08-17 05:51:27 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerddd6fc82006-11-10 04:58:55 +000010// This file implements the actions class which performs semantic analysis and
11// builds an AST out of a parse stream.
Chris Lattner3e7bd4e2006-08-17 05:51:27 +000012//
13//===----------------------------------------------------------------------===//
14
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Sema.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000016#include "TargetAttributesSema.h"
Ryan Flynn7d470f32009-07-30 03:15:39 +000017#include "llvm/ADT/DenseMap.h"
Sebastian Redl35351a92010-01-31 22:27:38 +000018#include "llvm/ADT/SmallSet.h"
John McCallfceb64b2009-11-07 03:30:10 +000019#include "llvm/ADT/APFloat.h"
John McCall75b960e2010-06-01 09:23:16 +000020#include "clang/Sema/ExternalSemaSource.h"
Douglas Gregor5c6f10b2010-08-12 22:51:45 +000021#include "clang/Sema/SemaConsumer.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000022#include "clang/AST/ASTContext.h"
Douglas Gregor639cccc2010-02-09 22:26:47 +000023#include "clang/AST/ASTDiagnostic.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000025#include "clang/AST/Expr.h"
Chris Lattnerd3e98952006-10-06 05:22:26 +000026#include "clang/Lex/Preprocessor.h"
Anders Carlssonf68079e2009-08-26 22:33:56 +000027#include "clang/Basic/PartialDiagnostic.h"
Chris Lattner7d4f5c42009-04-30 06:18:40 +000028#include "clang/Basic/TargetInfo.h"
Chris Lattnerc11438c2006-08-18 05:17:52 +000029using namespace clang;
Douglas Gregor9a28e842010-03-01 23:15:13 +000030
31FunctionScopeInfo::~FunctionScopeInfo() { }
32
33void FunctionScopeInfo::Clear(unsigned NumErrors) {
John McCalla95172b2010-08-01 00:26:45 +000034 HasBranchProtectedScope = false;
35 HasBranchIntoScope = false;
36 HasIndirectGoto = false;
37
Douglas Gregor9a28e842010-03-01 23:15:13 +000038 LabelMap.clear();
39 SwitchStack.clear();
Douglas Gregor6fd1b182010-05-15 06:01:05 +000040 Returns.clear();
Douglas Gregor9a28e842010-03-01 23:15:13 +000041 NumErrorsAtStartOfFunction = NumErrors;
42}
43
44BlockScopeInfo::~BlockScopeInfo() { }
45
Steve Naroffc62adb62007-10-09 22:01:59 +000046void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
47 TUScope = S;
Douglas Gregor91f84212008-12-11 16:49:14 +000048 PushDeclContext(S, Context.getTranslationUnitDecl());
Mike Stump11289f42009-09-09 15:08:12 +000049
John McCallf24d7bb2010-05-28 18:45:08 +000050 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
51
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +000052 if (!Context.isInt128Installed() && // May be set by PCHReader.
53 PP.getTargetInfo().getPointerWidth(0) >= 64) {
John McCallbcd03502009-12-07 02:54:59 +000054 TypeSourceInfo *TInfo;
John McCall703a3f82009-10-24 08:00:42 +000055
Chris Lattner7d4f5c42009-04-30 06:18:40 +000056 // Install [u]int128_t for 64-bit targets.
John McCallbcd03502009-12-07 02:54:59 +000057 TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty);
Chris Lattner7d4f5c42009-04-30 06:18:40 +000058 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
59 SourceLocation(),
60 &Context.Idents.get("__int128_t"),
John McCallbcd03502009-12-07 02:54:59 +000061 TInfo), TUScope);
John McCall703a3f82009-10-24 08:00:42 +000062
John McCallbcd03502009-12-07 02:54:59 +000063 TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty);
Chris Lattner7d4f5c42009-04-30 06:18:40 +000064 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
65 SourceLocation(),
66 &Context.Idents.get("__uint128_t"),
John McCallbcd03502009-12-07 02:54:59 +000067 TInfo), TUScope);
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +000068 Context.setInt128Installed();
Chris Lattner7d4f5c42009-04-30 06:18:40 +000069 }
Mike Stump11289f42009-09-09 15:08:12 +000070
71
Chris Lattnerfe0e0af2008-02-06 00:46:58 +000072 if (!PP.getLangOptions().ObjC1) return;
Mike Stump11289f42009-09-09 15:08:12 +000073
Steve Naroff853308d2009-06-16 00:20:10 +000074 // Built-in ObjC types may already be set by PCHReader (hence isNull checks).
Douglas Gregor512b0772009-04-23 22:29:11 +000075 if (Context.getObjCSelType().isNull()) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +000076 // Create the built-in typedef for 'SEL'.
Fariborz Jahanian0afc5552009-11-23 18:04:25 +000077 QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy);
John McCallbcd03502009-12-07 02:54:59 +000078 TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT);
John McCall703a3f82009-10-24 08:00:42 +000079 TypedefDecl *SelTypedef
80 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
81 &Context.Idents.get("SEL"), SelInfo);
Douglas Gregor512b0772009-04-23 22:29:11 +000082 PushOnScopeChains(SelTypedef, TUScope);
83 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
Fariborz Jahanian04b258c2009-11-25 23:07:42 +000084 Context.ObjCSelRedefinitionType = Context.getObjCSelType();
Douglas Gregor512b0772009-04-23 22:29:11 +000085 }
Chris Lattner5a92bab2008-06-21 20:20:39 +000086
Chris Lattner5a92bab2008-06-21 20:20:39 +000087 // Synthesize "@class Protocol;
Douglas Gregor512b0772009-04-23 22:29:11 +000088 if (Context.getObjCProtoType().isNull()) {
89 ObjCInterfaceDecl *ProtocolDecl =
90 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000091 &Context.Idents.get("Protocol"),
Douglas Gregor1c283312010-08-11 12:19:30 +000092 SourceLocation(), true);
Douglas Gregor512b0772009-04-23 22:29:11 +000093 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
Fariborz Jahanian1e3609f2009-11-18 23:15:37 +000094 PushOnScopeChains(ProtocolDecl, TUScope, false);
Douglas Gregor512b0772009-04-23 22:29:11 +000095 }
Steve Naroff1329fa02009-07-15 18:40:39 +000096 // Create the built-in typedef for 'id'.
Douglas Gregor512b0772009-04-23 22:29:11 +000097 if (Context.getObjCIdType().isNull()) {
John McCall8b07ec22010-05-15 11:32:37 +000098 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 0, 0);
99 T = Context.getObjCObjectPointerType(T);
100 TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +0000101 TypedefDecl *IdTypedef
102 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
103 &Context.Idents.get("id"), IdInfo);
Douglas Gregor512b0772009-04-23 22:29:11 +0000104 PushOnScopeChains(IdTypedef, TUScope);
105 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
David Chisnall9f57c292009-08-17 16:35:33 +0000106 Context.ObjCIdRedefinitionType = Context.getObjCIdType();
Douglas Gregor512b0772009-04-23 22:29:11 +0000107 }
Steve Naroff1329fa02009-07-15 18:40:39 +0000108 // Create the built-in typedef for 'Class'.
Steve Naroff7cae42b2009-07-10 23:34:53 +0000109 if (Context.getObjCClassType().isNull()) {
John McCall8b07ec22010-05-15 11:32:37 +0000110 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 0, 0);
111 T = Context.getObjCObjectPointerType(T);
112 TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +0000113 TypedefDecl *ClassTypedef
114 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
115 &Context.Idents.get("Class"), ClassInfo);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000116 PushOnScopeChains(ClassTypedef, TUScope);
117 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
David Chisnall9f57c292009-08-17 16:35:33 +0000118 Context.ObjCClassRedefinitionType = Context.getObjCClassType();
Douglas Gregor5c6f10b2010-08-12 22:51:45 +0000119 }
Steve Naroff7f549f12007-10-10 21:53:07 +0000120}
121
Douglas Gregor54feb842009-04-14 16:27:31 +0000122Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
Daniel Dunbar242ea9a2009-11-13 08:58:20 +0000123 bool CompleteTranslationUnit,
124 CodeCompleteConsumer *CodeCompleter)
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000125 : TheTargetAttributesSema(0),
126 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
Mike Stump11289f42009-09-09 15:08:12 +0000127 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
Daniel Dunbar242ea9a2009-11-13 08:58:20 +0000128 ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0),
Eli Friedman570024a2010-08-05 06:57:20 +0000129 PackContext(0), VisContext(0), TopFunctionScope(0), ParsingDeclDepth(0),
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +0000130 IdResolver(pp.getLangOptions()), GlobalNewDeleteDeclared(false),
Douglas Gregor37256522009-05-14 21:44:34 +0000131 CompleteTranslationUnit(CompleteTranslationUnit),
Chandler Carruth2d69ec72010-06-28 08:39:25 +0000132 NumSFINAEErrors(0), SuppressAccessChecking(false),
133 NonInstantiationEntries(0), CurrentInstantiationScope(0), TyposCorrected(0),
Ted Kremenek0b405322010-03-23 00:13:23 +0000134 AnalysisWarnings(*this)
Douglas Gregor84d49a22009-11-11 21:54:23 +0000135{
Steve Naroff7f549f12007-10-10 21:53:07 +0000136 TUScope = 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000137 if (getLangOptions().CPlusPlus)
138 FieldCollector.reset(new CXXFieldCollector());
Mike Stump11289f42009-09-09 15:08:12 +0000139
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000140 // Tell diagnostics how to render things from the AST library.
Douglas Gregor639cccc2010-02-09 22:26:47 +0000141 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
142 &Context);
Douglas Gregorff790f12009-11-26 00:44:06 +0000143
144 ExprEvalContexts.push_back(
Douglas Gregor5c6f10b2010-08-12 22:51:45 +0000145 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0));
146}
147
148void Sema::Initialize() {
149 // Tell the AST consumer about this Sema object.
150 Consumer.Initialize(Context);
151
152 // FIXME: Isn't this redundant with the initialization above?
153 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
154 SC->InitializeSema(*this);
155
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);
Steve Naroff38d31b42007-02-28 01:22:02 +0000160}
Chris Lattnercb6a3822006-11-10 06:20:45 +0000161
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000162Sema::~Sema() {
163 if (PackContext) FreePackedContext();
Eli Friedman570024a2010-08-05 06:57:20 +0000164 if (VisContext) FreeVisContext();
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000165 delete TheTargetAttributesSema;
Douglas Gregor9a28e842010-03-01 23:15:13 +0000166 while (!FunctionScopes.empty())
167 PopFunctionOrBlockScope();
Douglas Gregor5c6f10b2010-08-12 22:51:45 +0000168
169 // Tell the SemaConsumer to forget about us; we're going out of scope.
170 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
171 SC->ForgetSema();
172
173 // Detach from the external Sema source.
174 if (ExternalSemaSource *ExternalSema
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000175 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
Douglas Gregor5c6f10b2010-08-12 22:51:45 +0000176 ExternalSema->ForgetSema();
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000177}
178
Mike Stump11289f42009-09-09 15:08:12 +0000179/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Chris Lattnera65e1f32008-01-16 19:17:22 +0000180/// If there is already an implicit cast, merge into the existing one.
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000181/// The result is of the given category.
Mike Stump11289f42009-09-09 15:08:12 +0000182void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
Anders Carlsson975979382010-04-23 22:18:37 +0000183 CastExpr::CastKind Kind,
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000184 ImplicitCastExpr::ResultCategory Category,
John McCallcf142162010-08-07 06:22:56 +0000185 const CXXCastPath *BasePath) {
Mon P Wang74b32072008-09-04 08:38:01 +0000186 QualType ExprTy = Context.getCanonicalType(Expr->getType());
187 QualType TypeTy = Context.getCanonicalType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +0000188
Mon P Wang74b32072008-09-04 08:38:01 +0000189 if (ExprTy == TypeTy)
190 return;
Mike Stump11289f42009-09-09 15:08:12 +0000191
John McCallfceb64b2009-11-07 03:30:10 +0000192 if (Expr->getType()->isPointerType() && Ty->isPointerType()) {
193 QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType();
194 QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType();
Mon P Wang74b32072008-09-04 08:38:01 +0000195 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
Chris Lattnerf490e152008-11-19 05:27:50 +0000196 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
197 << Expr->getSourceRange();
Mon P Wang74b32072008-09-04 08:38:01 +0000198 }
199 }
Mike Stump11289f42009-09-09 15:08:12 +0000200
Douglas Gregor88d292c2010-05-13 16:44:06 +0000201 // If this is a derived-to-base cast to a through a virtual base, we
202 // need a vtable.
203 if (Kind == CastExpr::CK_DerivedToBase &&
John McCallcf142162010-08-07 06:22:56 +0000204 BasePathInvolvesVirtualBase(*BasePath)) {
Douglas Gregor88d292c2010-05-13 16:44:06 +0000205 QualType T = Expr->getType();
206 if (const PointerType *Pointer = T->getAs<PointerType>())
207 T = Pointer->getPointeeType();
208 if (const RecordType *RecordTy = T->getAs<RecordType>())
209 MarkVTableUsed(Expr->getLocStart(),
210 cast<CXXRecordDecl>(RecordTy->getDecl()));
211 }
212
Douglas Gregora11693b2008-11-12 17:17:38 +0000213 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
John McCallcf142162010-08-07 06:22:56 +0000214 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
Anders Carlsson4e66cda2009-09-15 05:28:24 +0000215 ImpCast->setType(Ty);
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000216 ImpCast->setCategory(Category);
Anders Carlsson4e66cda2009-09-15 05:28:24 +0000217 return;
218 }
219 }
220
John McCallcf142162010-08-07 06:22:56 +0000221 Expr = ImplicitCastExpr::Create(Context, Ty, Kind, Expr, BasePath, Category);
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000222}
223
224ImplicitCastExpr::ResultCategory Sema::CastCategory(Expr *E) {
225 Expr::Classification Classification = E->Classify(Context);
226 return Classification.isRValue() ?
227 ImplicitCastExpr::RValue :
228 (Classification.isLValue() ?
229 ImplicitCastExpr::LValue :
230 ImplicitCastExpr::XValue);
Chris Lattnera65e1f32008-01-16 19:17:22 +0000231}
232
Chris Lattner57c523f2007-08-31 04:53:24 +0000233void Sema::DeleteExpr(ExprTy *E) {
Chris Lattner57c523f2007-08-31 04:53:24 +0000234}
235void Sema::DeleteStmt(StmtTy *S) {
Chris Lattner57c523f2007-08-31 04:53:24 +0000236}
237
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000238/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
239static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
240 if (D->isUsed())
241 return true;
242
243 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
244 // UnusedFileScopedDecls stores the first declaration.
245 // The declaration may have become definition so check again.
246 const FunctionDecl *DeclToCheck;
247 if (FD->hasBody(DeclToCheck))
248 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
249
250 // Later redecls may add new information resulting in not having to warn,
251 // so check again.
252 DeclToCheck = FD->getMostRecentDeclaration();
253 if (DeclToCheck != FD)
254 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
255 }
256
257 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
258 // UnusedFileScopedDecls stores the first declaration.
259 // The declaration may have become definition so check again.
260 const VarDecl *DeclToCheck = VD->getDefinition();
261 if (DeclToCheck)
262 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
263
264 // Later redecls may add new information resulting in not having to warn,
265 // so check again.
266 DeclToCheck = VD->getMostRecentDeclaration();
267 if (DeclToCheck != VD)
268 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
269 }
270
271 return false;
272}
273
Chris Lattnerf4404402008-08-23 03:19:52 +0000274/// ActOnEndOfTranslationUnit - This is called at the very end of the
275/// translation unit when EOF is reached and all but the top-level scope is
276/// popped.
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +0000277void Sema::ActOnEndOfTranslationUnit() {
278 // At PCH writing, implicit instantiations and VTable handling info are
279 // stored and performed when the PCH is included.
280 if (CompleteTranslationUnit)
281 while (1) {
282 // C++: Perform implicit template instantiations.
283 //
284 // FIXME: When we perform these implicit instantiations, we do not
285 // carefully keep track of the point of instantiation (C++ [temp.point]).
286 // This means that name lookup that occurs within the template
287 // instantiation will always happen at the end of the translation unit,
288 // so it will find some names that should not be found. Although this is
289 // common behavior for C++ compilers, it is technically wrong. In the
290 // future, we either need to be able to filter the results of name lookup
291 // or we need to perform template instantiations earlier.
292 PerformPendingImplicitInstantiations();
293
294 /// If DefinedUsedVTables ends up marking any virtual member
295 /// functions it might lead to more pending template
296 /// instantiations, which is why we need to loop here.
297 if (!DefineUsedVTables())
298 break;
299 }
Anders Carlsson82fccd02009-12-07 08:24:59 +0000300
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +0000301 // Remove file scoped decls that turned out to be used.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000302 UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(),
303 UnusedFileScopedDecls.end(),
304 std::bind1st(std::ptr_fun(ShouldRemoveFromUnused),
305 this)),
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +0000306 UnusedFileScopedDecls.end());
Douglas Gregorfb8b27d2010-04-09 17:41:13 +0000307
Douglas Gregorb14904c2010-08-13 22:48:40 +0000308 if (!CompleteTranslationUnit) {
309 TUScope = 0;
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +0000310 return;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000311 }
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +0000312
Chris Lattner0c797362009-09-08 18:19:27 +0000313 // Check for #pragma weak identifiers that were never declared
314 // FIXME: This will cause diagnostics to be emitted in a non-determinstic
315 // order! Iterating over a densemap like this is bad.
Ryan Flynn7d470f32009-07-30 03:15:39 +0000316 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
Chris Lattner0c797362009-09-08 18:19:27 +0000317 I = WeakUndeclaredIdentifiers.begin(),
318 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
319 if (I->second.getUsed()) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000320
Chris Lattner0c797362009-09-08 18:19:27 +0000321 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
322 << I->first;
Ryan Flynn7d470f32009-07-30 03:15:39 +0000323 }
324
Douglas Gregor0760fa12009-03-10 23:43:53 +0000325 // C99 6.9.2p2:
326 // A declaration of an identifier for an object that has file
327 // scope without an initializer, and without a storage-class
328 // specifier or with the storage-class specifier static,
329 // constitutes a tentative definition. If a translation unit
330 // contains one or more tentative definitions for an identifier,
331 // and the translation unit contains no external definition for
332 // that identifier, then the behavior is exactly as if the
333 // translation unit contains a file scope declaration of that
334 // identifier, with the composite type as of the end of the
335 // translation unit, with an initializer equal to 0.
Sebastian Redl35351a92010-01-31 22:27:38 +0000336 llvm::SmallSet<VarDecl *, 32> Seen;
337 for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) {
338 VarDecl *VD = TentativeDefinitions[i]->getActingDefinition();
Mike Stump11289f42009-09-09 15:08:12 +0000339
Sebastian Redl35351a92010-01-31 22:27:38 +0000340 // If the tentative definition was completed, getActingDefinition() returns
341 // null. If we've already seen this variable before, insert()'s second
342 // return value is false.
343 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
Douglas Gregorbeecd582009-04-21 17:11:58 +0000344 continue;
345
Mike Stump11289f42009-09-09 15:08:12 +0000346 if (const IncompleteArrayType *ArrayT
Douglas Gregorbeecd582009-04-21 17:11:58 +0000347 = Context.getAsIncompleteArrayType(VD->getType())) {
Mike Stump11289f42009-09-09 15:08:12 +0000348 if (RequireCompleteType(VD->getLocation(),
Douglas Gregorbeecd582009-04-21 17:11:58 +0000349 ArrayT->getElementType(),
Chris Lattner0c797362009-09-08 18:19:27 +0000350 diag::err_tentative_def_incomplete_type_arr)) {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000351 VD->setInvalidDecl();
Chris Lattner0c797362009-09-08 18:19:27 +0000352 continue;
Douglas Gregor0760fa12009-03-10 23:43:53 +0000353 }
Mike Stump11289f42009-09-09 15:08:12 +0000354
Chris Lattner0c797362009-09-08 18:19:27 +0000355 // Set the length of the array to 1 (C99 6.9.2p5).
356 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
357 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
John McCallc5b82252009-10-16 00:14:28 +0000358 QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
359 One, ArrayType::Normal, 0);
Chris Lattner0c797362009-09-08 18:19:27 +0000360 VD->setType(T);
Mike Stump11289f42009-09-09 15:08:12 +0000361 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
Douglas Gregorbeecd582009-04-21 17:11:58 +0000362 diag::err_tentative_def_incomplete_type))
363 VD->setInvalidDecl();
364
365 // Notify the consumer that we've completed a tentative definition.
366 if (!VD->isInvalidDecl())
367 Consumer.CompleteTentativeDefinition(VD);
368
Douglas Gregor0760fa12009-03-10 23:43:53 +0000369 }
Tanya Lattner90073802010-02-12 00:07:30 +0000370
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +0000371 // Output warning for unused file scoped decls.
372 for (std::vector<const DeclaratorDecl*>::iterator
373 I = UnusedFileScopedDecls.begin(),
374 E = UnusedFileScopedDecls.end(); I != E; ++I) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000375 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
376 const FunctionDecl *DiagD;
377 if (!FD->hasBody(DiagD))
378 DiagD = FD;
Argyrios Kyrtzidiscad715f2010-08-17 21:43:11 +0000379 Diag(DiagD->getLocation(),
380 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_method
381 : diag::warn_unused_function)
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000382 << DiagD->getDeclName();
383 } else {
384 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
385 if (!DiagD)
386 DiagD = cast<VarDecl>(*I);
387 Diag(DiagD->getLocation(), diag::warn_unused_variable)
388 << DiagD->getDeclName();
389 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +0000390 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000391
392 TUScope = 0;
Chris Lattnerf4404402008-08-23 03:19:52 +0000393}
394
395
Chris Lattnerc11438c2006-08-18 05:17:52 +0000396//===----------------------------------------------------------------------===//
Chris Lattnereaafe1222006-11-10 05:17:58 +0000397// Helper functions.
398//===----------------------------------------------------------------------===//
399
Anders Carlssonb26ab812009-08-08 17:45:02 +0000400DeclContext *Sema::getFunctionLevelDeclContext() {
John McCallb8788012009-12-19 10:53:49 +0000401 DeclContext *DC = CurContext;
Mike Stump11289f42009-09-09 15:08:12 +0000402
Douglas Gregor0c6f5392010-05-22 16:25:05 +0000403 while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC))
Anders Carlssonb26ab812009-08-08 17:45:02 +0000404 DC = DC->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000405
Anders Carlssonb26ab812009-08-08 17:45:02 +0000406 return DC;
407}
408
Chris Lattner79413952008-12-04 23:50:19 +0000409/// getCurFunctionDecl - If inside of a function body, this returns a pointer
410/// to the function decl for the function being parsed. If we're currently
411/// in a 'block', this returns the containing context.
412FunctionDecl *Sema::getCurFunctionDecl() {
Anders Carlssonb26ab812009-08-08 17:45:02 +0000413 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner79413952008-12-04 23:50:19 +0000414 return dyn_cast<FunctionDecl>(DC);
415}
416
Daniel Dunbar6e8aa532008-08-11 05:35:13 +0000417ObjCMethodDecl *Sema::getCurMethodDecl() {
Anders Carlssonb26ab812009-08-08 17:45:02 +0000418 DeclContext *DC = getFunctionLevelDeclContext();
Steve Naroffecf2bb82008-11-17 16:28:52 +0000419 return dyn_cast<ObjCMethodDecl>(DC);
Daniel Dunbar6e8aa532008-08-11 05:35:13 +0000420}
Chris Lattner79413952008-12-04 23:50:19 +0000421
422NamedDecl *Sema::getCurFunctionOrMethodDecl() {
Anders Carlssonb26ab812009-08-08 17:45:02 +0000423 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner79413952008-12-04 23:50:19 +0000424 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000425 return cast<NamedDecl>(DC);
Chris Lattner79413952008-12-04 23:50:19 +0000426 return 0;
427}
428
Douglas Gregorda17bd32009-03-20 22:48:49 +0000429Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
Douglas Gregor33834512009-06-14 07:33:30 +0000430 if (!this->Emit())
431 return;
Mike Stump11289f42009-09-09 15:08:12 +0000432
Douglas Gregorda17bd32009-03-20 22:48:49 +0000433 // If this is not a note, and we're in a template instantiation
434 // that is different from the last template instantiation where
435 // we emitted an error, print a template instantiation
436 // backtrace.
437 if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
438 !SemaRef.ActiveTemplateInstantiations.empty() &&
Mike Stump11289f42009-09-09 15:08:12 +0000439 SemaRef.ActiveTemplateInstantiations.back()
Douglas Gregorda17bd32009-03-20 22:48:49 +0000440 != SemaRef.LastTemplateInstantiationErrorContext) {
441 SemaRef.PrintInstantiationStack();
Mike Stump11289f42009-09-09 15:08:12 +0000442 SemaRef.LastTemplateInstantiationErrorContext
Douglas Gregorda17bd32009-03-20 22:48:49 +0000443 = SemaRef.ActiveTemplateInstantiations.back();
444 }
445}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000446
Douglas Gregor210b5902010-03-25 22:17:48 +0000447Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
448 if (isSFINAEContext()) {
449 switch (Diagnostic::getDiagnosticSFINAEResponse(DiagID)) {
450 case Diagnostic::SFINAE_Report:
451 // Fall through; we'll report the diagnostic below.
452 break;
453
454 case Diagnostic::SFINAE_SubstitutionFailure:
455 // Count this failure so that we know that template argument deduction
456 // has failed.
457 ++NumSFINAEErrors;
458 // Fall through
459
460 case Diagnostic::SFINAE_Suppress:
461 // Suppress this diagnostic.
462 Diags.setLastDiagnosticIgnored();
463 return SemaDiagnosticBuilder(*this);
464 }
465 }
466
467 DiagnosticBuilder DB = Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
468 return SemaDiagnosticBuilder(DB, *this, DiagID);
469}
470
Anders Carlssonf68079e2009-08-26 22:33:56 +0000471Sema::SemaDiagnosticBuilder
472Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
473 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
474 PD.Emit(Builder);
Mike Stump11289f42009-09-09 15:08:12 +0000475
Anders Carlssonf68079e2009-08-26 22:33:56 +0000476 return Builder;
477}
478
Douglas Gregor0be31a22010-07-02 17:43:08 +0000479/// \brief Determines the active Scope associated with the given declaration
480/// context.
481///
482/// This routine maps a declaration context to the active Scope object that
483/// represents that declaration context in the parser. It is typically used
484/// from "scope-less" code (e.g., template instantiation, lazy creation of
485/// declarations) that injects a name for name-lookup purposes and, therefore,
486/// must update the Scope.
487///
488/// \returns The scope corresponding to the given declaraion context, or NULL
489/// if no such scope is open.
490Scope *Sema::getScopeForContext(DeclContext *Ctx) {
491
492 if (!Ctx)
493 return 0;
494
495 Ctx = Ctx->getPrimaryContext();
496 for (Scope *S = getCurScope(); S; S = S->getParent()) {
Sebastian Redlcaef9ab2010-07-08 23:07:34 +0000497 // Ignore scopes that cannot have declarations. This is important for
498 // out-of-line definitions of static class members.
499 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
500 if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
501 if (Ctx == Entity->getPrimaryContext())
502 return S;
Douglas Gregor0be31a22010-07-02 17:43:08 +0000503 }
504
505 return 0;
506}
Douglas Gregor9a28e842010-03-01 23:15:13 +0000507
508/// \brief Enter a new function scope
509void Sema::PushFunctionScope() {
510 if (FunctionScopes.empty()) {
511 // Use the "top" function scope rather than having to allocate memory for
512 // a new scope.
513 TopFunctionScope.Clear(getDiagnostics().getNumErrors());
514 FunctionScopes.push_back(&TopFunctionScope);
515 return;
516 }
517
518 FunctionScopes.push_back(
519 new FunctionScopeInfo(getDiagnostics().getNumErrors()));
520}
521
522void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
523 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics().getNumErrors(),
524 BlockScope, Block));
525}
526
527void Sema::PopFunctionOrBlockScope() {
528 if (FunctionScopes.back() != &TopFunctionScope)
529 delete FunctionScopes.back();
530 else
531 TopFunctionScope.Clear(getDiagnostics().getNumErrors());
532
533 FunctionScopes.pop_back();
534}
535
536/// \brief Determine whether any errors occurred within this function/method/
537/// block.
538bool Sema::hasAnyErrorsInThisFunction() const {
539 unsigned NumErrors = TopFunctionScope.NumErrorsAtStartOfFunction;
540 if (!FunctionScopes.empty())
541 NumErrors = FunctionScopes.back()->NumErrorsAtStartOfFunction;
542 return NumErrors != getDiagnostics().getNumErrors();
543}
544
545BlockScopeInfo *Sema::getCurBlock() {
546 if (FunctionScopes.empty())
547 return 0;
548
549 return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
550}
John McCall75b960e2010-06-01 09:23:16 +0000551
552// Pin this vtable to this file.
553ExternalSemaSource::~ExternalSemaSource() {}