blob: 1de7b7fbead873c9eb4e8ddb86c997f99f048456 [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"
Douglas Gregor46ea32a2010-08-12 22:51:45 +000023#include "clang/Sema/SemaConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/AST/ASTContext.h"
Douglas Gregor79a9a342010-02-09 22:26:47 +000025#include "clang/AST/ASTDiagnostic.h"
John McCall384aff82010-08-25 07:42:41 +000026#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000027#include "clang/AST/DeclObjC.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000028#include "clang/AST/Expr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "clang/Lex/Preprocessor.h"
Anders Carlsson91a0cc92009-08-26 22:33:56 +000030#include "clang/Basic/PartialDiagnostic.h"
Chris Lattner4d150c82009-04-30 06:18:40 +000031#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000033
34FunctionScopeInfo::~FunctionScopeInfo() { }
35
36void FunctionScopeInfo::Clear(unsigned NumErrors) {
John McCallb60a77e2010-08-01 00:26:45 +000037 HasBranchProtectedScope = false;
38 HasBranchIntoScope = false;
39 HasIndirectGoto = false;
40
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000041 LabelMap.clear();
42 SwitchStack.clear();
Douglas Gregor5077c382010-05-15 06:01:05 +000043 Returns.clear();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +000044 NumErrorsAtStartOfFunction = NumErrors;
45}
46
47BlockScopeInfo::~BlockScopeInfo() { }
48
Steve Naroffb216c882007-10-09 22:01:59 +000049void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
50 TUScope = S;
Douglas Gregor44b43212008-12-11 16:49:14 +000051 PushDeclContext(S, Context.getTranslationUnitDecl());
Mike Stump1eb44332009-09-09 15:08:12 +000052
John McCallc7e04da2010-05-28 18:45:08 +000053 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
54
Sebastian Redlc43b54c2010-08-18 23:56:43 +000055 if (!Context.isInt128Installed() && // May be set by ASTReader.
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +000056 PP.getTargetInfo().getPointerWidth(0) >= 64) {
John McCalla93c9342009-12-07 02:54:59 +000057 TypeSourceInfo *TInfo;
John McCallba6a9bd2009-10-24 08:00:42 +000058
Chris Lattner4d150c82009-04-30 06:18:40 +000059 // Install [u]int128_t for 64-bit targets.
John McCalla93c9342009-12-07 02:54:59 +000060 TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty);
Chris Lattner4d150c82009-04-30 06:18:40 +000061 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
62 SourceLocation(),
63 &Context.Idents.get("__int128_t"),
John McCalla93c9342009-12-07 02:54:59 +000064 TInfo), TUScope);
John McCallba6a9bd2009-10-24 08:00:42 +000065
John McCalla93c9342009-12-07 02:54:59 +000066 TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty);
Chris Lattner4d150c82009-04-30 06:18:40 +000067 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
68 SourceLocation(),
69 &Context.Idents.get("__uint128_t"),
John McCalla93c9342009-12-07 02:54:59 +000070 TInfo), TUScope);
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +000071 Context.setInt128Installed();
Chris Lattner4d150c82009-04-30 06:18:40 +000072 }
Mike Stump1eb44332009-09-09 15:08:12 +000073
74
Chris Lattner2ae34ed2008-02-06 00:46:58 +000075 if (!PP.getLangOptions().ObjC1) return;
Mike Stump1eb44332009-09-09 15:08:12 +000076
Sebastian Redlc43b54c2010-08-18 23:56:43 +000077 // Built-in ObjC types may already be set by ASTReader (hence isNull checks).
Douglas Gregor319ac892009-04-23 22:29:11 +000078 if (Context.getObjCSelType().isNull()) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +000079 // Create the built-in typedef for 'SEL'.
Fariborz Jahanian04765ac2009-11-23 18:04:25 +000080 QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy);
John McCalla93c9342009-12-07 02:54:59 +000081 TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT);
John McCallba6a9bd2009-10-24 08:00:42 +000082 TypedefDecl *SelTypedef
83 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
84 &Context.Idents.get("SEL"), SelInfo);
Douglas Gregor319ac892009-04-23 22:29:11 +000085 PushOnScopeChains(SelTypedef, TUScope);
86 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000087 Context.ObjCSelRedefinitionType = Context.getObjCSelType();
Douglas Gregor319ac892009-04-23 22:29:11 +000088 }
Chris Lattner6ee1f9c2008-06-21 20:20:39 +000089
Chris Lattner6ee1f9c2008-06-21 20:20:39 +000090 // Synthesize "@class Protocol;
Douglas Gregor319ac892009-04-23 22:29:11 +000091 if (Context.getObjCProtoType().isNull()) {
92 ObjCInterfaceDecl *ProtocolDecl =
93 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000094 &Context.Idents.get("Protocol"),
Douglas Gregordeacbdc2010-08-11 12:19:30 +000095 SourceLocation(), true);
Douglas Gregor319ac892009-04-23 22:29:11 +000096 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
Fariborz Jahanian10324db2009-11-18 23:15:37 +000097 PushOnScopeChains(ProtocolDecl, TUScope, false);
Douglas Gregor319ac892009-04-23 22:29:11 +000098 }
Steve Naroffde2e22d2009-07-15 18:40:39 +000099 // Create the built-in typedef for 'id'.
Douglas Gregor319ac892009-04-23 22:29:11 +0000100 if (Context.getObjCIdType().isNull()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000101 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 0, 0);
102 T = Context.getObjCObjectPointerType(T);
103 TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +0000104 TypedefDecl *IdTypedef
105 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
106 &Context.Idents.get("id"), IdInfo);
Douglas Gregor319ac892009-04-23 22:29:11 +0000107 PushOnScopeChains(IdTypedef, TUScope);
108 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
David Chisnall0f436562009-08-17 16:35:33 +0000109 Context.ObjCIdRedefinitionType = Context.getObjCIdType();
Douglas Gregor319ac892009-04-23 22:29:11 +0000110 }
Steve Naroffde2e22d2009-07-15 18:40:39 +0000111 // Create the built-in typedef for 'Class'.
Steve Naroff14108da2009-07-10 23:34:53 +0000112 if (Context.getObjCClassType().isNull()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000113 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 0, 0);
114 T = Context.getObjCObjectPointerType(T);
115 TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +0000116 TypedefDecl *ClassTypedef
117 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
118 &Context.Idents.get("Class"), ClassInfo);
Steve Naroff14108da2009-07-10 23:34:53 +0000119 PushOnScopeChains(ClassTypedef, TUScope);
120 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
David Chisnall0f436562009-08-17 16:35:33 +0000121 Context.ObjCClassRedefinitionType = Context.getObjCClassType();
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000122 }
Steve Naroff3b950172007-10-10 21:53:07 +0000123}
124
Douglas Gregorf807fe02009-04-14 16:27:31 +0000125Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
Daniel Dunbar3a2838d2009-11-13 08:58:20 +0000126 bool CompleteTranslationUnit,
127 CodeCompleteConsumer *CodeCompleter)
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000128 : TheTargetAttributesSema(0),
129 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
Mike Stump1eb44332009-09-09 15:08:12 +0000130 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
Daniel Dunbar3a2838d2009-11-13 08:58:20 +0000131 ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0),
Eli Friedmanaa8b0d12010-08-05 06:57:20 +0000132 PackContext(0), VisContext(0), TopFunctionScope(0), ParsingDeclDepth(0),
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +0000133 IdResolver(pp.getLangOptions()), GlobalNewDeleteDeclared(false),
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000134 CompleteTranslationUnit(CompleteTranslationUnit),
Chandler Carruth926c4b42010-06-28 08:39:25 +0000135 NumSFINAEErrors(0), SuppressAccessChecking(false),
136 NonInstantiationEntries(0), CurrentInstantiationScope(0), TyposCorrected(0),
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000137 AnalysisWarnings(*this)
Douglas Gregorf35f8282009-11-11 21:54:23 +0000138{
Steve Naroff3b950172007-10-10 21:53:07 +0000139 TUScope = 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000140 if (getLangOptions().CPlusPlus)
141 FieldCollector.reset(new CXXFieldCollector());
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Chris Lattner22caddc2008-11-23 09:13:29 +0000143 // Tell diagnostics how to render things from the AST library.
Douglas Gregor79a9a342010-02-09 22:26:47 +0000144 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
145 &Context);
Douglas Gregor2afce722009-11-26 00:44:06 +0000146
147 ExprEvalContexts.push_back(
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000148 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0));
149}
150
151void Sema::Initialize() {
152 // Tell the AST consumer about this Sema object.
153 Consumer.Initialize(Context);
154
155 // FIXME: Isn't this redundant with the initialization above?
156 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
157 SC->InitializeSema(*this);
158
159 // Tell the external Sema source about this Sema object.
160 if (ExternalSemaSource *ExternalSema
161 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
162 ExternalSema->InitializeSema(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000163}
164
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000165Sema::~Sema() {
166 if (PackContext) FreePackedContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +0000167 if (VisContext) FreeVisContext();
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000168 delete TheTargetAttributesSema;
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000169 while (!FunctionScopes.empty())
170 PopFunctionOrBlockScope();
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000171
172 // Tell the SemaConsumer to forget about us; we're going out of scope.
173 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
174 SC->ForgetSema();
175
176 // Detach from the external Sema source.
177 if (ExternalSemaSource *ExternalSema
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000178 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
Douglas Gregor46ea32a2010-08-12 22:51:45 +0000179 ExternalSema->ForgetSema();
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000180}
181
Mike Stump1eb44332009-09-09 15:08:12 +0000182/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Chris Lattner1e0a3902008-01-16 19:17:22 +0000183/// If there is already an implicit cast, merge into the existing one.
Sebastian Redl906082e2010-07-20 04:20:21 +0000184/// The result is of the given category.
Mike Stump1eb44332009-09-09 15:08:12 +0000185void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
Anders Carlsson88465d32010-04-23 22:18:37 +0000186 CastExpr::CastKind Kind,
Sebastian Redl906082e2010-07-20 04:20:21 +0000187 ImplicitCastExpr::ResultCategory Category,
John McCallf871d0c2010-08-07 06:22:56 +0000188 const CXXCastPath *BasePath) {
Mon P Wang3a2c7442008-09-04 08:38:01 +0000189 QualType ExprTy = Context.getCanonicalType(Expr->getType());
190 QualType TypeTy = Context.getCanonicalType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Mon P Wang3a2c7442008-09-04 08:38:01 +0000192 if (ExprTy == TypeTy)
193 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000194
John McCall680523a2009-11-07 03:30:10 +0000195 if (Expr->getType()->isPointerType() && Ty->isPointerType()) {
196 QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType();
197 QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType();
Mon P Wang3a2c7442008-09-04 08:38:01 +0000198 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000199 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
200 << Expr->getSourceRange();
Mon P Wang3a2c7442008-09-04 08:38:01 +0000201 }
202 }
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000204 // If this is a derived-to-base cast to a through a virtual base, we
205 // need a vtable.
206 if (Kind == CastExpr::CK_DerivedToBase &&
John McCallf871d0c2010-08-07 06:22:56 +0000207 BasePathInvolvesVirtualBase(*BasePath)) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000208 QualType T = Expr->getType();
209 if (const PointerType *Pointer = T->getAs<PointerType>())
210 T = Pointer->getPointeeType();
211 if (const RecordType *RecordTy = T->getAs<RecordType>())
212 MarkVTableUsed(Expr->getLocStart(),
213 cast<CXXRecordDecl>(RecordTy->getDecl()));
214 }
215
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000216 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
John McCallf871d0c2010-08-07 06:22:56 +0000217 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
Anders Carlsson4c5fad32009-09-15 05:28:24 +0000218 ImpCast->setType(Ty);
Sebastian Redl906082e2010-07-20 04:20:21 +0000219 ImpCast->setCategory(Category);
Anders Carlsson4c5fad32009-09-15 05:28:24 +0000220 return;
221 }
222 }
223
John McCallf871d0c2010-08-07 06:22:56 +0000224 Expr = ImplicitCastExpr::Create(Context, Ty, Kind, Expr, BasePath, Category);
Sebastian Redl906082e2010-07-20 04:20:21 +0000225}
226
227ImplicitCastExpr::ResultCategory Sema::CastCategory(Expr *E) {
228 Expr::Classification Classification = E->Classify(Context);
229 return Classification.isRValue() ?
230 ImplicitCastExpr::RValue :
231 (Classification.isLValue() ?
232 ImplicitCastExpr::LValue :
233 ImplicitCastExpr::XValue);
Chris Lattner1e0a3902008-01-16 19:17:22 +0000234}
235
Chris Lattner394a3fd2007-08-31 04:53:24 +0000236void Sema::DeleteExpr(ExprTy *E) {
Chris Lattner394a3fd2007-08-31 04:53:24 +0000237}
238void Sema::DeleteStmt(StmtTy *S) {
Chris Lattner394a3fd2007-08-31 04:53:24 +0000239}
240
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000241/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
242static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
243 if (D->isUsed())
244 return true;
245
246 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
247 // UnusedFileScopedDecls stores the first declaration.
248 // The declaration may have become definition so check again.
249 const FunctionDecl *DeclToCheck;
250 if (FD->hasBody(DeclToCheck))
251 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
252
253 // Later redecls may add new information resulting in not having to warn,
254 // so check again.
255 DeclToCheck = FD->getMostRecentDeclaration();
256 if (DeclToCheck != FD)
257 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
258 }
259
260 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
261 // UnusedFileScopedDecls stores the first declaration.
262 // The declaration may have become definition so check again.
263 const VarDecl *DeclToCheck = VD->getDefinition();
264 if (DeclToCheck)
265 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
266
267 // Later redecls may add new information resulting in not having to warn,
268 // so check again.
269 DeclToCheck = VD->getMostRecentDeclaration();
270 if (DeclToCheck != VD)
271 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
272 }
273
274 return false;
275}
276
Chris Lattner9299f3f2008-08-23 03:19:52 +0000277/// ActOnEndOfTranslationUnit - This is called at the very end of the
278/// translation unit when EOF is reached and all but the top-level scope is
279/// popped.
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +0000280void Sema::ActOnEndOfTranslationUnit() {
281 // At PCH writing, implicit instantiations and VTable handling info are
282 // stored and performed when the PCH is included.
283 if (CompleteTranslationUnit)
284 while (1) {
285 // C++: Perform implicit template instantiations.
286 //
287 // FIXME: When we perform these implicit instantiations, we do not
288 // carefully keep track of the point of instantiation (C++ [temp.point]).
289 // This means that name lookup that occurs within the template
290 // instantiation will always happen at the end of the translation unit,
291 // so it will find some names that should not be found. Although this is
292 // common behavior for C++ compilers, it is technically wrong. In the
293 // future, we either need to be able to filter the results of name lookup
294 // or we need to perform template instantiations earlier.
295 PerformPendingImplicitInstantiations();
296
297 /// If DefinedUsedVTables ends up marking any virtual member
298 /// functions it might lead to more pending template
299 /// instantiations, which is why we need to loop here.
300 if (!DefineUsedVTables())
301 break;
302 }
Anders Carlssond6a637f2009-12-07 08:24:59 +0000303
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000304 // Remove file scoped decls that turned out to be used.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000305 UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(),
306 UnusedFileScopedDecls.end(),
307 std::bind1st(std::ptr_fun(ShouldRemoveFromUnused),
308 this)),
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000309 UnusedFileScopedDecls.end());
Douglas Gregor47268a32010-04-09 17:41:13 +0000310
Douglas Gregor87c08a52010-08-13 22:48:40 +0000311 if (!CompleteTranslationUnit) {
312 TUScope = 0;
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +0000313 return;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000314 }
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +0000315
Chris Lattner63d65f82009-09-08 18:19:27 +0000316 // Check for #pragma weak identifiers that were never declared
317 // FIXME: This will cause diagnostics to be emitted in a non-determinstic
318 // order! Iterating over a densemap like this is bad.
Ryan Flynne25ff832009-07-30 03:15:39 +0000319 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
Chris Lattner63d65f82009-09-08 18:19:27 +0000320 I = WeakUndeclaredIdentifiers.begin(),
321 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
322 if (I->second.getUsed()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Chris Lattner63d65f82009-09-08 18:19:27 +0000324 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
325 << I->first;
Ryan Flynne25ff832009-07-30 03:15:39 +0000326 }
327
Douglas Gregor275a3692009-03-10 23:43:53 +0000328 // C99 6.9.2p2:
329 // A declaration of an identifier for an object that has file
330 // scope without an initializer, and without a storage-class
331 // specifier or with the storage-class specifier static,
332 // constitutes a tentative definition. If a translation unit
333 // contains one or more tentative definitions for an identifier,
334 // and the translation unit contains no external definition for
335 // that identifier, then the behavior is exactly as if the
336 // translation unit contains a file scope declaration of that
337 // identifier, with the composite type as of the end of the
338 // translation unit, with an initializer equal to 0.
Sebastian Redle9d12b62010-01-31 22:27:38 +0000339 llvm::SmallSet<VarDecl *, 32> Seen;
340 for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) {
341 VarDecl *VD = TentativeDefinitions[i]->getActingDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Sebastian Redle9d12b62010-01-31 22:27:38 +0000343 // If the tentative definition was completed, getActingDefinition() returns
344 // null. If we've already seen this variable before, insert()'s second
345 // return value is false.
346 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000347 continue;
348
Mike Stump1eb44332009-09-09 15:08:12 +0000349 if (const IncompleteArrayType *ArrayT
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000350 = Context.getAsIncompleteArrayType(VD->getType())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000351 if (RequireCompleteType(VD->getLocation(),
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000352 ArrayT->getElementType(),
Chris Lattner63d65f82009-09-08 18:19:27 +0000353 diag::err_tentative_def_incomplete_type_arr)) {
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000354 VD->setInvalidDecl();
Chris Lattner63d65f82009-09-08 18:19:27 +0000355 continue;
Douglas Gregor275a3692009-03-10 23:43:53 +0000356 }
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Chris Lattner63d65f82009-09-08 18:19:27 +0000358 // Set the length of the array to 1 (C99 6.9.2p5).
359 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
360 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
John McCall46a617a2009-10-16 00:14:28 +0000361 QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
362 One, ArrayType::Normal, 0);
Chris Lattner63d65f82009-09-08 18:19:27 +0000363 VD->setType(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000364 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000365 diag::err_tentative_def_incomplete_type))
366 VD->setInvalidDecl();
367
368 // Notify the consumer that we've completed a tentative definition.
369 if (!VD->isInvalidDecl())
370 Consumer.CompleteTentativeDefinition(VD);
371
Douglas Gregor275a3692009-03-10 23:43:53 +0000372 }
Tanya Lattnere6bbc012010-02-12 00:07:30 +0000373
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000374 // Output warning for unused file scoped decls.
John McCallaab01322010-08-24 17:40:45 +0000375 for (llvm::SmallVectorImpl<const DeclaratorDecl*>::iterator
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000376 I = UnusedFileScopedDecls.begin(),
377 E = UnusedFileScopedDecls.end(); I != E; ++I) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000378 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
379 const FunctionDecl *DiagD;
380 if (!FD->hasBody(DiagD))
381 DiagD = FD;
Argyrios Kyrtzidis3d27b102010-08-17 21:43:11 +0000382 Diag(DiagD->getLocation(),
Argyrios Kyrtzidis42cbd782010-08-17 22:06:44 +0000383 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
Argyrios Kyrtzidis3d27b102010-08-17 21:43:11 +0000384 : diag::warn_unused_function)
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000385 << DiagD->getDeclName();
386 } else {
387 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
388 if (!DiagD)
389 DiagD = cast<VarDecl>(*I);
390 Diag(DiagD->getLocation(), diag::warn_unused_variable)
391 << DiagD->getDeclName();
392 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000393 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000394
395 TUScope = 0;
Chris Lattner9299f3f2008-08-23 03:19:52 +0000396}
397
398
Reid Spencer5f016e22007-07-11 17:01:13 +0000399//===----------------------------------------------------------------------===//
400// Helper functions.
401//===----------------------------------------------------------------------===//
402
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000403DeclContext *Sema::getFunctionLevelDeclContext() {
John McCalldb0ee1d2009-12-19 10:53:49 +0000404 DeclContext *DC = CurContext;
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Douglas Gregord9008312010-05-22 16:25:05 +0000406 while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC))
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000407 DC = DC->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000409 return DC;
410}
411
Chris Lattner371f2582008-12-04 23:50:19 +0000412/// getCurFunctionDecl - If inside of a function body, this returns a pointer
413/// to the function decl for the function being parsed. If we're currently
414/// in a 'block', this returns the containing context.
415FunctionDecl *Sema::getCurFunctionDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000416 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner371f2582008-12-04 23:50:19 +0000417 return dyn_cast<FunctionDecl>(DC);
418}
419
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000420ObjCMethodDecl *Sema::getCurMethodDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000421 DeclContext *DC = getFunctionLevelDeclContext();
Steve Naroffd7612e12008-11-17 16:28:52 +0000422 return dyn_cast<ObjCMethodDecl>(DC);
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000423}
Chris Lattner371f2582008-12-04 23:50:19 +0000424
425NamedDecl *Sema::getCurFunctionOrMethodDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000426 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner371f2582008-12-04 23:50:19 +0000427 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000428 return cast<NamedDecl>(DC);
Chris Lattner371f2582008-12-04 23:50:19 +0000429 return 0;
430}
431
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000432Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000433 if (!this->Emit())
434 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000435
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000436 // If this is not a note, and we're in a template instantiation
437 // that is different from the last template instantiation where
438 // we emitted an error, print a template instantiation
439 // backtrace.
440 if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
441 !SemaRef.ActiveTemplateInstantiations.empty() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000442 SemaRef.ActiveTemplateInstantiations.back()
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000443 != SemaRef.LastTemplateInstantiationErrorContext) {
444 SemaRef.PrintInstantiationStack();
Mike Stump1eb44332009-09-09 15:08:12 +0000445 SemaRef.LastTemplateInstantiationErrorContext
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000446 = SemaRef.ActiveTemplateInstantiations.back();
447 }
448}
Douglas Gregor2e222532009-07-02 17:08:52 +0000449
Douglas Gregoreab5d1e2010-03-25 22:17:48 +0000450Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
451 if (isSFINAEContext()) {
452 switch (Diagnostic::getDiagnosticSFINAEResponse(DiagID)) {
453 case Diagnostic::SFINAE_Report:
454 // Fall through; we'll report the diagnostic below.
455 break;
456
457 case Diagnostic::SFINAE_SubstitutionFailure:
458 // Count this failure so that we know that template argument deduction
459 // has failed.
460 ++NumSFINAEErrors;
461 // Fall through
462
463 case Diagnostic::SFINAE_Suppress:
464 // Suppress this diagnostic.
465 Diags.setLastDiagnosticIgnored();
466 return SemaDiagnosticBuilder(*this);
467 }
468 }
469
470 DiagnosticBuilder DB = Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
471 return SemaDiagnosticBuilder(DB, *this, DiagID);
472}
473
Anders Carlsson91a0cc92009-08-26 22:33:56 +0000474Sema::SemaDiagnosticBuilder
475Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
476 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
477 PD.Emit(Builder);
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Anders Carlsson91a0cc92009-08-26 22:33:56 +0000479 return Builder;
480}
481
Douglas Gregor23c94db2010-07-02 17:43:08 +0000482/// \brief Determines the active Scope associated with the given declaration
483/// context.
484///
485/// This routine maps a declaration context to the active Scope object that
486/// represents that declaration context in the parser. It is typically used
487/// from "scope-less" code (e.g., template instantiation, lazy creation of
488/// declarations) that injects a name for name-lookup purposes and, therefore,
489/// must update the Scope.
490///
491/// \returns The scope corresponding to the given declaraion context, or NULL
492/// if no such scope is open.
493Scope *Sema::getScopeForContext(DeclContext *Ctx) {
494
495 if (!Ctx)
496 return 0;
497
498 Ctx = Ctx->getPrimaryContext();
499 for (Scope *S = getCurScope(); S; S = S->getParent()) {
Sebastian Redlcddc69f2010-07-08 23:07:34 +0000500 // Ignore scopes that cannot have declarations. This is important for
501 // out-of-line definitions of static class members.
502 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
503 if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
504 if (Ctx == Entity->getPrimaryContext())
505 return S;
Douglas Gregor23c94db2010-07-02 17:43:08 +0000506 }
507
508 return 0;
509}
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000510
511/// \brief Enter a new function scope
512void Sema::PushFunctionScope() {
513 if (FunctionScopes.empty()) {
514 // Use the "top" function scope rather than having to allocate memory for
515 // a new scope.
516 TopFunctionScope.Clear(getDiagnostics().getNumErrors());
517 FunctionScopes.push_back(&TopFunctionScope);
518 return;
519 }
520
521 FunctionScopes.push_back(
522 new FunctionScopeInfo(getDiagnostics().getNumErrors()));
523}
524
525void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
526 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics().getNumErrors(),
527 BlockScope, Block));
528}
529
530void Sema::PopFunctionOrBlockScope() {
531 if (FunctionScopes.back() != &TopFunctionScope)
532 delete FunctionScopes.back();
533 else
534 TopFunctionScope.Clear(getDiagnostics().getNumErrors());
535
536 FunctionScopes.pop_back();
537}
538
539/// \brief Determine whether any errors occurred within this function/method/
540/// block.
541bool Sema::hasAnyErrorsInThisFunction() const {
542 unsigned NumErrors = TopFunctionScope.NumErrorsAtStartOfFunction;
543 if (!FunctionScopes.empty())
544 NumErrors = FunctionScopes.back()->NumErrorsAtStartOfFunction;
545 return NumErrors != getDiagnostics().getNumErrors();
546}
547
548BlockScopeInfo *Sema::getCurBlock() {
549 if (FunctionScopes.empty())
550 return 0;
551
552 return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
553}
John McCall76bd1f32010-06-01 09:23:16 +0000554
555// Pin this vtable to this file.
556ExternalSemaSource::~ExternalSemaSource() {}