blob: b6b1f4c44658b2bc607c049517eedaa1932ae6f8 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
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 semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
28using namespace clang;
29
Douglas Gregor2def4832008-11-17 20:34:05 +000030Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000031 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000032 DeclContext *DC = 0;
33 if (SS) {
34 if (SS->isInvalid())
35 return 0;
36 DC = static_cast<DeclContext*>(SS->getScopeRep());
37 }
38 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroffb327ce02008-04-02 14:35:35 +000039
Douglas Gregor2ce52f32008-04-13 21:07:44 +000040 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
41 isa<ObjCInterfaceDecl>(IIDecl) ||
Douglas Gregor72c3f312008-12-05 18:15:24 +000042 isa<TagDecl>(IIDecl) ||
43 isa<TemplateTypeParmDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000044 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000045 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000046}
47
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000048DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000049 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000050 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000051 if (MD->isOutOfLineDefinition())
52 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000053
54 // A C++ inline method is parsed *after* the topmost class it was declared in
55 // is fully parsed (it's "complete").
56 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000057 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000058 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
59 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000060 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000061 DC = RD;
62
63 // Return the declaration context of the topmost class the inline method is
64 // declared in.
65 return DC;
66 }
67
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000068 if (isa<ObjCMethodDecl>(DC))
69 return Context.getTranslationUnitDecl();
70
71 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
72 return SD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000073
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000074 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000075}
76
Chris Lattner9fdf9c62008-04-22 18:39:57 +000077void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000078 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +000079 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000080 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000081}
82
Chris Lattnerb048c982008-04-06 04:47:34 +000083void Sema::PopDeclContext() {
84 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000085 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000086}
87
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000088/// Add this decl to the scope shadowed decl chains.
89void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000090 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000091
92 // C++ [basic.scope]p4:
93 // -- exactly one declaration shall declare a class name or
94 // enumeration name that is not a typedef name and the other
95 // declarations shall all refer to the same object or
96 // enumerator, or all refer to functions and function templates;
97 // in this case the class name or enumeration name is hidden.
98 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
99 // We are pushing the name of a tag (enum or class).
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000100 IdentifierResolver::iterator
101 I = IdResolver.begin(TD->getIdentifier(),
102 TD->getDeclContext(), false/*LookInParentCtx*/);
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000103 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000104 // There is already a declaration with the same name in the same
105 // scope. It must be found before we find the new declaration,
106 // so swap the order on the shadowed declaration chain.
107
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000108 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000109 return;
110 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000111 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
112 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000113 // We are pushing the name of a function, which might be an
114 // overloaded name.
115 IdentifierResolver::iterator
Douglas Gregor2def4832008-11-17 20:34:05 +0000116 I = IdResolver.begin(FD->getDeclName(),
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000117 FD->getDeclContext(), false/*LookInParentCtx*/);
118 if (I != IdResolver.end() &&
119 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
120 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
121 // There is already a declaration with the same name in the same
122 // scope. It must be a function or an overloaded function.
123 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
124 if (!Ovl) {
125 // We haven't yet overloaded this function. Take the existing
126 // FunctionDecl and put it into an OverloadedFunctionDecl.
127 Ovl = OverloadedFunctionDecl::Create(Context,
128 FD->getDeclContext(),
Douglas Gregor2def4832008-11-17 20:34:05 +0000129 FD->getDeclName());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000130 Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
131
132 // Remove the name binding to the existing FunctionDecl...
133 IdResolver.RemoveDecl(*I);
134
135 // ... and put the OverloadedFunctionDecl in its place.
136 IdResolver.AddDecl(Ovl);
137 }
138
139 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
140 // to its list of overloads.
141 Ovl->addOverload(FD);
142
143 return;
144 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000145 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000146
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000147 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000148}
149
Steve Naroffb216c882007-10-09 22:01:59 +0000150void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000151 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000152 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
153 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000154
Reid Spencer5f016e22007-07-11 17:01:13 +0000155 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
156 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000157 Decl *TmpD = static_cast<Decl*>(*I);
158 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000159
160 if (isa<CXXFieldDecl>(TmpD)) continue;
161
162 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
163 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000164
Reid Spencer5f016e22007-07-11 17:01:13 +0000165 IdentifierInfo *II = D->getIdentifier();
166 if (!II) continue;
167
Ted Kremeneka89d1972008-09-03 18:03:35 +0000168 // We only want to remove the decls from the identifier decl chains for
169 // local scopes, when inside a function/method.
Douglas Gregor72c3f312008-12-05 18:15:24 +0000170 // However, we *always* remove template parameters, since they are
171 // purely lexically scoped (and can never be found by qualified
172 // name lookup).
173 if (S->getFnParent() != 0 || isa<TemplateTypeParmDecl>(D))
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000174 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000175
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000176 // Chain this decl to the containing DeclContext.
177 D->setNext(CurContext->getDeclChain());
178 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000179 }
180}
181
Steve Naroffe8043c32008-04-01 23:04:06 +0000182/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
183/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000184ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000185 // The third "scope" argument is 0 since we aren't enabling lazy built-in
186 // creation from this context.
187 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000188
Steve Naroffb327ce02008-04-02 14:35:35 +0000189 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000190}
191
Steve Naroffe8043c32008-04-01 23:04:06 +0000192/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000193/// namespace.
Douglas Gregor2def4832008-11-17 20:34:05 +0000194Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000195 const DeclContext *LookupCtx,
196 bool enableLazyBuiltinCreation) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000197 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000198 unsigned NS = NSI;
199 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
200 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000201
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000202 IdentifierResolver::iterator
Douglas Gregor2def4832008-11-17 20:34:05 +0000203 I = LookupCtx ? IdResolver.begin(Name, LookupCtx, false/*LookInParentCtx*/)
204 : IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/);
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 // Scan up the scope chain looking for a decl that matches this identifier
206 // that is in the appropriate namespace. This search should not take long, as
207 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000208 for (; I != IdResolver.end(); ++I)
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000209 if ((*I)->getIdentifierNamespace() & NS)
210 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000211
Reid Spencer5f016e22007-07-11 17:01:13 +0000212 // If we didn't find a use of this identifier, and if the identifier
213 // corresponds to a compiler builtin, create the decl object for the builtin
214 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000215 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000216 IdentifierInfo *II = Name.getAsIdentifierInfo();
217 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000218 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000219 // If this is a builtin on this (or all) targets, create the decl.
220 if (unsigned BuiltinID = II->getBuiltinID())
221 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
222 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000223 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000224 // @interface and @compatibility_alias introduce typedef-like names.
225 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000226 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000227 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000228 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
229 if (IDI != ObjCInterfaceDecls.end())
230 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000231 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
232 if (I != ObjCAliasDecls.end())
233 return I->second->getClassInterface();
234 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 }
236 return 0;
237}
238
Chris Lattner95e2c712008-05-05 22:18:14 +0000239void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000240 if (!Context.getBuiltinVaListType().isNull())
241 return;
242
243 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000244 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000245 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000246 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
247}
248
Reid Spencer5f016e22007-07-11 17:01:13 +0000249/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
250/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000251ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
252 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000253 Builtin::ID BID = (Builtin::ID)bid;
254
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000255 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000256 InitBuiltinVaListType();
257
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000258 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000259 FunctionDecl *New = FunctionDecl::Create(Context,
260 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000261 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000262 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000263
Chris Lattner95e2c712008-05-05 22:18:14 +0000264 // Create Decl objects for each parameter, adding them to the
265 // FunctionDecl.
266 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
267 llvm::SmallVector<ParmVarDecl*, 16> Params;
268 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
269 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
270 FT->getArgType(i), VarDecl::None, 0,
271 0));
272 New->setParams(&Params[0], Params.size());
273 }
274
275
276
Chris Lattner7f925cc2008-04-11 07:00:53 +0000277 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000278 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 return New;
280}
281
Sebastian Redlc42e1182008-11-11 11:37:55 +0000282/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
283/// everything from the standard library is defined.
284NamespaceDecl *Sema::GetStdNamespace() {
285 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000286 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000287 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattner8edea832008-11-20 05:45:14 +0000288 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000289 0, Global, /*enableLazyBuiltinCreation=*/false);
290 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
291 }
292 return StdNamespace;
293}
294
Reid Spencer5f016e22007-07-11 17:01:13 +0000295/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
296/// and scope as a previous declaration 'Old'. Figure out how to resolve this
297/// situation, merging decls or emitting diagnostics as appropriate.
298///
Steve Naroffe8043c32008-04-01 23:04:06 +0000299TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000300 // Allow multiple definitions for ObjC built-in typedefs.
301 // FIXME: Verify the underlying types are equivalent!
302 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000303 const IdentifierInfo *TypeID = New->getIdentifier();
304 switch (TypeID->getLength()) {
305 default: break;
306 case 2:
307 if (!TypeID->isStr("id"))
308 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000309 Context.setObjCIdType(New);
310 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000311 case 5:
312 if (!TypeID->isStr("Class"))
313 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000314 Context.setObjCClassType(New);
315 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000316 case 3:
317 if (!TypeID->isStr("SEL"))
318 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000319 Context.setObjCSelType(New);
320 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000321 case 8:
322 if (!TypeID->isStr("Protocol"))
323 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000324 Context.setObjCProtoType(New->getUnderlyingType());
325 return New;
326 }
327 // Fall through - the typedef name was not a builtin type.
328 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 // Verify the old decl was also a typedef.
330 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
331 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000332 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000333 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000334 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 return New;
336 }
337
Chris Lattner99cb9972008-07-25 18:44:27 +0000338 // If the typedef types are not identical, reject them in all languages and
339 // with any extensions enabled.
340 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
341 Context.getCanonicalType(Old->getUnderlyingType()) !=
342 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000343 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000344 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000345 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner99cb9972008-07-25 18:44:27 +0000346 return Old;
347 }
348
Eli Friedman54ecfce2008-06-11 06:20:39 +0000349 if (getLangOptions().Microsoft) return New;
350
Douglas Gregorbbe27432008-11-21 16:29:06 +0000351 // C++ [dcl.typedef]p2:
352 // In a given non-class scope, a typedef specifier can be used to
353 // redefine the name of any type declared in that scope to refer
354 // to the type to which it already refers.
355 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
356 return New;
357
358 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000359 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
360 // *either* declaration is in a system header. The code below implements
361 // this adhoc compatibility rule. FIXME: The following code will not
362 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000363 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
364 SourceManager &SrcMgr = Context.getSourceManager();
365 if (SrcMgr.isInSystemHeader(Old->getLocation()))
366 return New;
367 if (SrcMgr.isInSystemHeader(New->getLocation()))
368 return New;
369 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000370
Chris Lattner08631c52008-11-23 21:45:46 +0000371 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000372 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 return New;
374}
375
Chris Lattner6b6b5372008-06-26 18:38:35 +0000376/// DeclhasAttr - returns true if decl Declaration already has the target
377/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000378static bool DeclHasAttr(const Decl *decl, const Attr *target) {
379 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
380 if (attr->getKind() == target->getKind())
381 return true;
382
383 return false;
384}
385
386/// MergeAttributes - append attributes from the Old decl to the New one.
387static void MergeAttributes(Decl *New, Decl *Old) {
388 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
389
Chris Lattnerddee4232008-03-03 03:28:21 +0000390 while (attr) {
391 tmp = attr;
392 attr = attr->getNext();
393
394 if (!DeclHasAttr(New, tmp)) {
395 New->addAttr(tmp);
396 } else {
397 tmp->setNext(0);
398 delete(tmp);
399 }
400 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000401
402 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000403}
404
Chris Lattner04421082008-04-08 04:40:51 +0000405/// MergeFunctionDecl - We just parsed a function 'New' from
406/// declarator D which has the same name and scope as a previous
407/// declaration 'Old'. Figure out how to resolve this situation,
408/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000409/// Redeclaration will be set true if this New is a redeclaration OldD.
410///
411/// In C++, New and Old must be declarations that are not
412/// overloaded. Use IsOverload to determine whether New and Old are
413/// overloaded, and to select the Old declaration that New should be
414/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000415FunctionDecl *
416Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000417 assert(!isa<OverloadedFunctionDecl>(OldD) &&
418 "Cannot merge with an overloaded function declaration");
419
Douglas Gregorf0097952008-04-21 02:02:58 +0000420 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000421 // Verify the old decl was also a function.
422 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
423 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000424 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000425 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000426 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000427 return New;
428 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000429
430 // Determine whether the previous declaration was a definition,
431 // implicit declaration, or a declaration.
432 diag::kind PrevDiag;
433 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000434 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000435 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000436 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000437 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000438 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000439
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000440 QualType OldQType = Context.getCanonicalType(Old->getType());
441 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000442
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000443 if (getLangOptions().CPlusPlus) {
444 // (C++98 13.1p2):
445 // Certain function declarations cannot be overloaded:
446 // -- Function declarations that differ only in the return type
447 // cannot be overloaded.
448 QualType OldReturnType
449 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
450 QualType NewReturnType
451 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
452 if (OldReturnType != NewReturnType) {
453 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
454 Diag(Old->getLocation(), PrevDiag);
455 return New;
456 }
457
458 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
459 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
460 if (OldMethod && NewMethod) {
461 // -- Member function declarations with the same name and the
462 // same parameter types cannot be overloaded if any of them
463 // is a static member function declaration.
464 if (OldMethod->isStatic() || NewMethod->isStatic()) {
465 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
466 Diag(Old->getLocation(), PrevDiag);
467 return New;
468 }
469 }
470
471 // (C++98 8.3.5p3):
472 // All declarations for a function shall agree exactly in both the
473 // return type and the parameter-type-list.
474 if (OldQType == NewQType) {
475 // We have a redeclaration.
476 MergeAttributes(New, Old);
477 Redeclaration = true;
478 return MergeCXXFunctionDecl(New, Old);
479 }
480
481 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000482 }
Chris Lattner04421082008-04-08 04:40:51 +0000483
484 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000485 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000486 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000487 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000488 MergeAttributes(New, Old);
489 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000490 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000491 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000492
Steve Naroff837618c2008-01-16 15:01:34 +0000493 // A function that has already been declared has been redeclared or defined
494 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000495
Reid Spencer5f016e22007-07-11 17:01:13 +0000496 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
497 // TODO: This is totally simplistic. It should handle merging functions
498 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000499 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000500 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 return New;
502}
503
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000504/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000505static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000506 if (VD->isFileVarDecl())
507 return (!VD->getInit() &&
508 (VD->getStorageClass() == VarDecl::None ||
509 VD->getStorageClass() == VarDecl::Static));
510 return false;
511}
512
513/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
514/// when dealing with C "tentative" external object definitions (C99 6.9.2).
515void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
516 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000517 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000518
519 for (IdentifierResolver::iterator
520 I = IdResolver.begin(VD->getIdentifier(),
521 VD->getDeclContext(), false/*LookInParentCtx*/),
522 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000523 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000524 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
525
Steve Narofff855e6f2008-08-10 15:20:13 +0000526 // Handle the following case:
527 // int a[10];
528 // int a[]; - the code below makes sure we set the correct type.
529 // int a[11]; - this is an error, size isn't 10.
530 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
531 OldDecl->getType()->isConstantArrayType())
532 VD->setType(OldDecl->getType());
533
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000534 // Check for "tentative" definitions. We can't accomplish this in
535 // MergeVarDecl since the initializer hasn't been attached.
536 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
537 continue;
538
539 // Handle __private_extern__ just like extern.
540 if (OldDecl->getStorageClass() != VarDecl::Extern &&
541 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
542 VD->getStorageClass() != VarDecl::Extern &&
543 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000544 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000545 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000546 }
547 }
548 }
549}
550
Reid Spencer5f016e22007-07-11 17:01:13 +0000551/// MergeVarDecl - We just parsed a variable 'New' which has the same name
552/// and scope as a previous declaration 'Old'. Figure out how to resolve this
553/// situation, merging decls or emitting diagnostics as appropriate.
554///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000555/// Tentative definition rules (C99 6.9.2p2) are checked by
556/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
557/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000558///
Steve Naroffe8043c32008-04-01 23:04:06 +0000559VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000560 // Verify the old decl was also a variable.
561 VarDecl *Old = dyn_cast<VarDecl>(OldD);
562 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000563 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000564 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000565 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000566 return New;
567 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000568
569 MergeAttributes(New, Old);
570
Reid Spencer5f016e22007-07-11 17:01:13 +0000571 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000572 QualType OldCType = Context.getCanonicalType(Old->getType());
573 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000574 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner08631c52008-11-23 21:45:46 +0000575 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000576 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 return New;
578 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000579 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
580 if (New->getStorageClass() == VarDecl::Static &&
581 (Old->getStorageClass() == VarDecl::None ||
582 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000583 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000584 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000585 return New;
586 }
587 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
588 if (New->getStorageClass() != VarDecl::Static &&
589 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000590 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000591 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000592 return New;
593 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000594 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
595 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000596 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000597 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 }
599 return New;
600}
601
Chris Lattner04421082008-04-08 04:40:51 +0000602/// CheckParmsForFunctionDef - Check that the parameters of the given
603/// function are appropriate for the definition of a function. This
604/// takes care of any checks that cannot be performed on the
605/// declaration itself, e.g., that the types of each of the function
606/// parameters are complete.
607bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
608 bool HasInvalidParm = false;
609 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
610 ParmVarDecl *Param = FD->getParamDecl(p);
611
612 // C99 6.7.5.3p4: the parameters in a parameter type list in a
613 // function declarator that is part of a function definition of
614 // that function shall not have incomplete type.
615 if (Param->getType()->isIncompleteType() &&
616 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000617 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000618 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000619 Param->setInvalidDecl();
620 HasInvalidParm = true;
621 }
622 }
623
624 return HasInvalidParm;
625}
626
Reid Spencer5f016e22007-07-11 17:01:13 +0000627/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
628/// no declarator (e.g. "struct foo;") is parsed.
629Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
630 // TODO: emit error on 'int;' or 'const enum foo;'.
631 // TODO: emit error on 'typedef int;'
632 // if (!DS.isMissingDeclaratorOk()) Diag(...);
633
Steve Naroff92199282007-11-17 21:37:36 +0000634 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000635}
636
Steve Naroffd0091aa2008-01-10 22:15:12 +0000637bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000638 // Get the type before calling CheckSingleAssignmentConstraints(), since
639 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000640 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000641
Chris Lattner5cf216b2008-01-04 18:04:52 +0000642 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
643 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
644 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000645}
646
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000647bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000648 const ArrayType *AT = Context.getAsArrayType(DeclT);
649
650 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000651 // C99 6.7.8p14. We have an array of character type with unknown size
652 // being initialized to a string literal.
653 llvm::APSInt ConstVal(32);
654 ConstVal = strLiteral->getByteLength() + 1;
655 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000656 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000657 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000658 } else {
659 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000660 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000661 // FIXME: Avoid truncation for 64-bit length strings.
662 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000663 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000664 diag::warn_initializer_string_for_char_array_too_long)
665 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000666 }
667 // Set type from "char *" to "constant array of char".
668 strLiteral->setType(DeclT);
669 // For now, we always return false (meaning success).
670 return false;
671}
672
673StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000674 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000675 if (AT && AT->getElementType()->isCharType()) {
676 return dyn_cast<StringLiteral>(Init);
677 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000678 return 0;
679}
680
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000681bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
682 SourceLocation InitLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000683 DeclarationName InitEntity) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000684 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +0000685 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000686 // (8.3.2), shall be initialized by an object, or function, of
687 // type T or by an object that can be converted into a T.
688 if (DeclType->isReferenceType())
689 return CheckReferenceInit(Init, DeclType);
690
Steve Naroffca107302008-01-21 23:53:58 +0000691 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
692 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000693 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000694 return Diag(InitLoc, diag::err_variable_object_no_init)
695 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +0000696
Steve Naroff2fdc3742007-12-10 22:44:33 +0000697 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
698 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000699 // FIXME: Handle wide strings
700 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
701 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000702
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000703 // C++ [dcl.init]p14:
704 // -- If the destination type is a (possibly cv-qualified) class
705 // type:
706 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
707 QualType DeclTypeC = Context.getCanonicalType(DeclType);
708 QualType InitTypeC = Context.getCanonicalType(Init->getType());
709
710 // -- If the initialization is direct-initialization, or if it is
711 // copy-initialization where the cv-unqualified version of the
712 // source type is the same class as, or a derived class of, the
713 // class of the destination, constructors are considered.
714 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
715 IsDerivedFrom(InitTypeC, DeclTypeC)) {
716 CXXConstructorDecl *Constructor
717 = PerformInitializationByConstructor(DeclType, &Init, 1,
718 InitLoc, Init->getSourceRange(),
719 InitEntity, IK_Copy);
720 return Constructor == 0;
721 }
722
723 // -- Otherwise (i.e., for the remaining copy-initialization
724 // cases), user-defined conversion sequences that can
725 // convert from the source type to the destination type or
726 // (when a conversion function is used) to a derived class
727 // thereof are enumerated as described in 13.3.1.4, and the
728 // best one is chosen through overload resolution
729 // (13.3). If the conversion cannot be done or is
730 // ambiguous, the initialization is ill-formed. The
731 // function selected is called with the initializer
732 // expression as its argument; if the function is a
733 // constructor, the call initializes a temporary of the
734 // destination type.
735 // FIXME: We're pretending to do copy elision here; return to
736 // this when we have ASTs for such things.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000737 if (!PerformImplicitConversion(Init, DeclType))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000738 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000739
740 return Diag(InitLoc, diag::err_typecheck_convert_incompatible)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000741 << DeclType << InitEntity << "initializing"
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000742 << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000743 }
744
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000745 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000746 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000747 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
748 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +0000749
Steve Naroffd0091aa2008-01-10 22:15:12 +0000750 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000751 } else if (getLangOptions().CPlusPlus) {
752 // C++ [dcl.init]p14:
753 // [...] If the class is an aggregate (8.5.1), and the initializer
754 // is a brace-enclosed list, see 8.5.1.
755 //
756 // Note: 8.5.1 is handled below; here, we diagnose the case where
757 // we have an initializer list and a destination type that is not
758 // an aggregate.
759 // FIXME: In C++0x, this is yet another form of initialization.
760 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
761 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
762 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000763 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +0000764 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +0000765 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000766 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000767
Steve Naroff0cca7492008-05-01 22:18:59 +0000768 InitListChecker CheckInitList(this, InitList, DeclType);
769 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000770}
771
Douglas Gregor10bd3682008-11-17 22:58:34 +0000772/// GetNameForDeclarator - Determine the full declaration name for the
773/// given Declarator.
774DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
775 switch (D.getKind()) {
776 case Declarator::DK_Abstract:
777 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
778 return DeclarationName();
779
780 case Declarator::DK_Normal:
781 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
782 return DeclarationName(D.getIdentifier());
783
784 case Declarator::DK_Constructor: {
785 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
786 Ty = Context.getCanonicalType(Ty);
787 return Context.DeclarationNames.getCXXConstructorName(Ty);
788 }
789
790 case Declarator::DK_Destructor: {
791 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
792 Ty = Context.getCanonicalType(Ty);
793 return Context.DeclarationNames.getCXXDestructorName(Ty);
794 }
795
796 case Declarator::DK_Conversion: {
797 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
798 Ty = Context.getCanonicalType(Ty);
799 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
800 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000801
802 case Declarator::DK_Operator:
803 assert(D.getIdentifier() == 0 && "operator names have no identifier");
804 return Context.DeclarationNames.getCXXOperatorName(
805 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000806 }
807
808 assert(false && "Unknown name kind");
809 return DeclarationName();
810}
811
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000812Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000813Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000814 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +0000815 DeclarationName Name = GetNameForDeclarator(D);
816
Chris Lattnere80a59c2007-07-25 00:24:17 +0000817 // All of these full declarators require an identifier. If it doesn't have
818 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +0000819 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +0000820 if (!D.getInvalidType()) // Reject this if we think it is valid.
821 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000822 diag::err_declarator_need_ident)
823 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +0000824 return 0;
825 }
826
Chris Lattner31e05722007-08-26 06:24:45 +0000827 // The scope passed in may not be a decl scope. Zip up the scope tree until
828 // we find one that is.
829 while ((S->getFlags() & Scope::DeclScope) == 0)
830 S = S->getParent();
831
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000832 DeclContext *DC;
833 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +0000834 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000835 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000836
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000837 // See if this is a redefinition of a variable in the same scope.
838 if (!D.getCXXScopeSpec().isSet()) {
839 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +0000840 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000841 } else { // Something like "int foo::x;"
842 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000843 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000844
845 // C++ 7.3.1.2p2:
846 // Members (including explicit specializations of templates) of a named
847 // namespace can also be defined outside that namespace by explicit
848 // qualification of the name being defined, provided that the entity being
849 // defined was already declared in the namespace and the definition appears
850 // after the point of declaration in a namespace that encloses the
851 // declarations namespace.
852 //
853 if (PrevDecl == 0) {
854 // No previous declaration in the qualifying scope.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000855 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
Chris Lattner08631c52008-11-23 21:45:46 +0000856 << Name << D.getCXXScopeSpec().getRange();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000857 } else if (!CurContext->Encloses(DC)) {
858 // The qualifying scope doesn't enclose the original declaration.
859 // Emit diagnostic based on current scope.
860 SourceLocation L = D.getIdentifierLoc();
861 SourceRange R = D.getCXXScopeSpec().getRange();
862 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +0000863 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000864 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +0000865 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000866 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000867 }
868 }
869 }
870
Douglas Gregor72c3f312008-12-05 18:15:24 +0000871 if (PrevDecl && isTemplateParameterDecl(PrevDecl)) {
872 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +0000873 InvalidDecl = InvalidDecl
874 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000875 // Just pretend that we didn't see the previous declaration.
876 PrevDecl = 0;
877 }
878
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000879 // In C++, the previous declaration we find might be a tag type
880 // (class or enum). In this case, the new declaration will hide the
881 // tag type.
882 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
883 PrevDecl = 0;
884
Chris Lattner41af0932007-11-14 06:34:38 +0000885 QualType R = GetTypeForDeclarator(D, S);
886 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
887
Reid Spencer5f016e22007-07-11 17:01:13 +0000888 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000889 // Check that there are no default arguments (C++ only).
890 if (getLangOptions().CPlusPlus)
891 CheckExtraCXXDefaultArguments(D);
892
Chris Lattner41af0932007-11-14 06:34:38 +0000893 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000894 if (!NewTD) return 0;
895
896 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000897 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000898 // Merge the decl with the existing one if appropriate. If the decl is
899 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000900 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000901 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
902 if (NewTD == 0) return 0;
903 }
904 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000905 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000906 // C99 6.7.7p2: If a typedef name specifies a variably modified type
907 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000908 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +0000909 if (NewTD->getUnderlyingType()->isVariableArrayType())
910 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
911 else
912 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
913
Steve Naroffd7444aa2007-08-31 17:20:07 +0000914 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000915 }
916 }
Chris Lattner41af0932007-11-14 06:34:38 +0000917 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000918 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000919 switch (D.getDeclSpec().getStorageClassSpec()) {
920 default: assert(0 && "Unknown storage class!");
921 case DeclSpec::SCS_auto:
922 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +0000923 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +0000924 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +0000925 InvalidDecl = true;
926 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000927 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
928 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
929 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000930 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000931 }
932
Chris Lattnera98e58d2008-03-15 21:24:04 +0000933 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +0000934 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +0000935 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
936
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000937 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +0000938 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +0000939 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000940 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +0000941 "Constructors can only be declared in a member context");
942
Douglas Gregor42a552f2008-11-05 20:51:48 +0000943 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +0000944
945 // Create the new declaration
946 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000947 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000948 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +0000949 isExplicit, isInline,
950 /*isImplicitlyDeclared=*/false);
951
Douglas Gregor42a552f2008-11-05 20:51:48 +0000952 if (isInvalidDecl)
953 NewFD->setInvalidDecl();
954 } else if (D.getKind() == Declarator::DK_Destructor) {
955 // This is a C++ destructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000956 if (DC->isCXXRecord()) {
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000957 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000958
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000959 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000960 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000961 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000962 isInline,
963 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000964
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000965 if (isInvalidDecl)
966 NewFD->setInvalidDecl();
967 } else {
968 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
969 // Create a FunctionDecl to satisfy the function definition parsing
970 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000971 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000972 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000973 // FIXME: Move to DeclGroup...
974 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000975 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000976 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000977 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000978 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000979 Diag(D.getIdentifierLoc(),
980 diag::err_conv_function_not_member);
981 return 0;
982 } else {
983 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
984
985 NewFD = CXXConversionDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000986 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000987 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000988 isInline, isExplicit);
989
990 if (isInvalidDecl)
991 NewFD->setInvalidDecl();
992 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000993 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000994 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000995 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000996 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000997 (SC == FunctionDecl::Static), isInline,
998 LastDeclarator);
999 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001000 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001001 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001002 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001003 // FIXME: Move to DeclGroup...
1004 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001005 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +00001006 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +00001007 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +00001008
Daniel Dunbara80f8742008-08-05 01:35:17 +00001009 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001010 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001011 // The parser guarantees this is a string.
1012 StringLiteral *SE = cast<StringLiteral>(E);
1013 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1014 SE->getByteLength())));
1015 }
1016
Chris Lattner04421082008-04-08 04:40:51 +00001017 // Copy the parameter declarations from the declarator D to
1018 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001019 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001020 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1021
1022 // Create Decl objects for each parameter, adding them to the
1023 // FunctionDecl.
1024 llvm::SmallVector<ParmVarDecl*, 16> Params;
1025
1026 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1027 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001028 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001029 // We let through "const void" here because Sema::GetTypeForDeclarator
1030 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001031 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1032 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001033 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1034 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001035 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1036
Chris Lattnerdef026a2008-04-10 02:26:16 +00001037 // In C++, the empty parameter-type-list must be spelled "void"; a
1038 // typedef of void is not permitted.
1039 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001040 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001041 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1042 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001043 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001044 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1045 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1046 }
1047
1048 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001049 } else if (R->getAsTypedefType()) {
1050 // When we're declaring a function with a typedef, as in the
1051 // following example, we'll need to synthesize (unnamed)
1052 // parameters for use in the declaration.
1053 //
1054 // @code
1055 // typedef void fn(int);
1056 // fn f;
1057 // @endcode
1058 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1059 if (!FT) {
1060 // This is a typedef of a function with no prototype, so we
1061 // don't need to do anything.
1062 } else if ((FT->getNumArgs() == 0) ||
1063 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1064 FT->getArgType(0)->isVoidType())) {
1065 // This is a zero-argument function. We don't need to do anything.
1066 } else {
1067 // Synthesize a parameter for each argument type.
1068 llvm::SmallVector<ParmVarDecl*, 16> Params;
1069 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1070 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001071 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001072 SourceLocation(), 0,
1073 *ArgType, VarDecl::None,
1074 0, 0));
1075 }
1076
1077 NewFD->setParams(&Params[0], Params.size());
1078 }
Chris Lattner04421082008-04-08 04:40:51 +00001079 }
1080
Douglas Gregor42a552f2008-11-05 20:51:48 +00001081 // C++ constructors and destructors are handled by separate
1082 // routines, since they don't require any declaration merging (C++
1083 // [class.mfct]p2) and they aren't ever pushed into scope, because
1084 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1085 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1086 return ActOnConstructorDeclarator(Constructor);
1087 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1088 return ActOnDestructorDeclarator(Destructor);
Douglas Gregor2def4832008-11-17 20:34:05 +00001089
1090 // Extra checking for conversion functions, including recording
1091 // the conversion function in its class.
1092 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1093 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001094
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001095 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1096 if (NewFD->isOverloadedOperator() &&
1097 CheckOverloadedOperatorDeclaration(NewFD))
1098 NewFD->setInvalidDecl();
1099
Steve Naroffffce4d52008-01-09 23:34:55 +00001100 // Merge the decl with the existing one if appropriate. Since C functions
1101 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001102 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001103 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001104 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001105
1106 // If C++, determine whether NewFD is an overload of PrevDecl or
1107 // a declaration that requires merging. If it's an overload,
1108 // there's no more work to do here; we'll just add the new
1109 // function to the scope.
1110 OverloadedFunctionDecl::function_iterator MatchedDecl;
1111 if (!getLangOptions().CPlusPlus ||
1112 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1113 Decl *OldDecl = PrevDecl;
1114
1115 // If PrevDecl was an overloaded function, extract the
1116 // FunctionDecl that matched.
1117 if (isa<OverloadedFunctionDecl>(PrevDecl))
1118 OldDecl = *MatchedDecl;
1119
1120 // NewFD and PrevDecl represent declarations that need to be
1121 // merged.
1122 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1123
1124 if (NewFD == 0) return 0;
1125 if (Redeclaration) {
1126 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1127
1128 if (OldDecl == PrevDecl) {
1129 // Remove the name binding for the previous
1130 // declaration. We'll add the binding back later, but then
1131 // it will refer to the new declaration (which will
1132 // contain more information).
1133 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1134 } else {
1135 // We need to update the OverloadedFunctionDecl with the
1136 // latest declaration of this function, so that name
1137 // lookup will always refer to the latest declaration of
1138 // this function.
1139 *MatchedDecl = NewFD;
1140
1141 // Add the redeclaration to the current scope, since we'll
1142 // be skipping PushOnScopeChains.
1143 S->AddDecl(NewFD);
1144
1145 return NewFD;
1146 }
1147 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001148 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001149 }
1150 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001151
1152 // In C++, check default arguments now that we have merged decls.
1153 if (getLangOptions().CPlusPlus)
1154 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001156 // Check that there are no default arguments (C++ only).
1157 if (getLangOptions().CPlusPlus)
1158 CheckExtraCXXDefaultArguments(D);
1159
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001160 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001161 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1162 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001163 InvalidDecl = true;
1164 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001165
1166 VarDecl *NewVD;
1167 VarDecl::StorageClass SC;
1168 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001169 default: assert(0 && "Unknown storage class!");
1170 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1171 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1172 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1173 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1174 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1175 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001176 case DeclSpec::SCS_mutable:
1177 // mutable can only appear on non-static class members, so it's always
1178 // an error here
1179 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1180 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001181 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001182 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001183 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001184
1185 IdentifierInfo *II = Name.getAsIdentifierInfo();
1186 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001187 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1188 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001189 return 0;
1190 }
1191
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001192 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001193 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1194 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001195 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001196 D.getIdentifierLoc(), II,
1197 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001198 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001199 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001200 if (S->getFnParent() == 0) {
1201 // C99 6.9p2: The storage-class specifiers auto and register shall not
1202 // appear in the declaration specifiers in an external declaration.
1203 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001204 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001205 InvalidDecl = true;
1206 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001207 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001208 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1209 II, R, SC, LastDeclarator,
1210 // FIXME: Move to DeclGroup...
1211 D.getDeclSpec().getSourceRange().getBegin());
1212 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001213 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001214 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001215 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001216
Daniel Dunbara735ad82008-08-06 00:03:29 +00001217 // Handle GNU asm-label extension (encoded as an attribute).
1218 if (Expr *E = (Expr*) D.getAsmLabel()) {
1219 // The parser guarantees this is a string.
1220 StringLiteral *SE = cast<StringLiteral>(E);
1221 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1222 SE->getByteLength())));
1223 }
1224
Nate Begemanc8e89a82008-03-14 18:07:10 +00001225 // Emit an error if an address space was applied to decl with local storage.
1226 // This includes arrays of objects with address space qualifiers, but not
1227 // automatic variables that point to other address spaces.
1228 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001229 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1230 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1231 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001232 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001233 // Merge the decl with the existing one if appropriate. If the decl is
1234 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001235 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001236 NewVD = MergeVarDecl(NewVD, PrevDecl);
1237 if (NewVD == 0) return 0;
1238 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 New = NewVD;
1240 }
1241
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001242 // Set the lexical context. If the declarator has a C++ scope specifier, the
1243 // lexical context will be different from the semantic context.
1244 New->setLexicalDeclContext(CurContext);
1245
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001247 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001248 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001249 // If any semantic error occurred, mark the decl as invalid.
1250 if (D.getInvalidType() || InvalidDecl)
1251 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001252
1253 return New;
1254}
1255
Steve Naroff6594a702008-10-27 11:34:16 +00001256void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001257 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1258 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001259}
1260
Eli Friedmanc594b322008-05-20 13:48:25 +00001261bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1262 switch (Init->getStmtClass()) {
1263 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001264 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001265 return true;
1266 case Expr::ParenExprClass: {
1267 const ParenExpr* PE = cast<ParenExpr>(Init);
1268 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1269 }
1270 case Expr::CompoundLiteralExprClass:
1271 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1272 case Expr::DeclRefExprClass: {
1273 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001274 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1275 if (VD->hasGlobalStorage())
1276 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001277 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001278 return true;
1279 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001280 if (isa<FunctionDecl>(D))
1281 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001282 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001283 return true;
1284 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001285 case Expr::MemberExprClass: {
1286 const MemberExpr *M = cast<MemberExpr>(Init);
1287 if (M->isArrow())
1288 return CheckAddressConstantExpression(M->getBase());
1289 return CheckAddressConstantExpressionLValue(M->getBase());
1290 }
1291 case Expr::ArraySubscriptExprClass: {
1292 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1293 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1294 return CheckAddressConstantExpression(ASE->getBase()) ||
1295 CheckArithmeticConstantExpression(ASE->getIdx());
1296 }
1297 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001298 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001299 return false;
1300 case Expr::UnaryOperatorClass: {
1301 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1302
1303 // C99 6.6p9
1304 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001305 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001306
Steve Naroff6594a702008-10-27 11:34:16 +00001307 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001308 return true;
1309 }
1310 }
1311}
1312
1313bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1314 switch (Init->getStmtClass()) {
1315 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001316 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001317 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001318 case Expr::ParenExprClass:
1319 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001320 case Expr::StringLiteralClass:
1321 case Expr::ObjCStringLiteralClass:
1322 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001323 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001324 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001325 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1326 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1327 Builtin::BI__builtin___CFStringMakeConstantString)
1328 return false;
1329
Steve Naroff6594a702008-10-27 11:34:16 +00001330 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001331 return true;
1332
Eli Friedmanc594b322008-05-20 13:48:25 +00001333 case Expr::UnaryOperatorClass: {
1334 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1335
1336 // C99 6.6p9
1337 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1338 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1339
1340 if (Exp->getOpcode() == UnaryOperator::Extension)
1341 return CheckAddressConstantExpression(Exp->getSubExpr());
1342
Steve Naroff6594a702008-10-27 11:34:16 +00001343 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001344 return true;
1345 }
1346 case Expr::BinaryOperatorClass: {
1347 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1348 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1349
1350 Expr *PExp = Exp->getLHS();
1351 Expr *IExp = Exp->getRHS();
1352 if (IExp->getType()->isPointerType())
1353 std::swap(PExp, IExp);
1354
1355 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1356 return CheckAddressConstantExpression(PExp) ||
1357 CheckArithmeticConstantExpression(IExp);
1358 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001359 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001360 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001361 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001362 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1363 // Check for implicit promotion
1364 if (SubExpr->getType()->isFunctionType() ||
1365 SubExpr->getType()->isArrayType())
1366 return CheckAddressConstantExpressionLValue(SubExpr);
1367 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001368
1369 // Check for pointer->pointer cast
1370 if (SubExpr->getType()->isPointerType())
1371 return CheckAddressConstantExpression(SubExpr);
1372
Eli Friedmanc3f07642008-08-25 20:46:57 +00001373 if (SubExpr->getType()->isIntegralType()) {
1374 // Check for the special-case of a pointer->int->pointer cast;
1375 // this isn't standard, but some code requires it. See
1376 // PR2720 for an example.
1377 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1378 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1379 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1380 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1381 if (IntWidth >= PointerWidth) {
1382 return CheckAddressConstantExpression(SubCast->getSubExpr());
1383 }
1384 }
1385 }
1386 }
1387 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001388 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001389 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001390
Steve Naroff6594a702008-10-27 11:34:16 +00001391 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001392 return true;
1393 }
1394 case Expr::ConditionalOperatorClass: {
1395 // FIXME: Should we pedwarn here?
1396 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1397 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001398 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001399 return true;
1400 }
1401 if (CheckArithmeticConstantExpression(Exp->getCond()))
1402 return true;
1403 if (Exp->getLHS() &&
1404 CheckAddressConstantExpression(Exp->getLHS()))
1405 return true;
1406 return CheckAddressConstantExpression(Exp->getRHS());
1407 }
1408 case Expr::AddrLabelExprClass:
1409 return false;
1410 }
1411}
1412
Eli Friedman4caf0552008-06-09 05:05:07 +00001413static const Expr* FindExpressionBaseAddress(const Expr* E);
1414
1415static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1416 switch (E->getStmtClass()) {
1417 default:
1418 return E;
1419 case Expr::ParenExprClass: {
1420 const ParenExpr* PE = cast<ParenExpr>(E);
1421 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1422 }
1423 case Expr::MemberExprClass: {
1424 const MemberExpr *M = cast<MemberExpr>(E);
1425 if (M->isArrow())
1426 return FindExpressionBaseAddress(M->getBase());
1427 return FindExpressionBaseAddressLValue(M->getBase());
1428 }
1429 case Expr::ArraySubscriptExprClass: {
1430 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1431 return FindExpressionBaseAddress(ASE->getBase());
1432 }
1433 case Expr::UnaryOperatorClass: {
1434 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1435
1436 if (Exp->getOpcode() == UnaryOperator::Deref)
1437 return FindExpressionBaseAddress(Exp->getSubExpr());
1438
1439 return E;
1440 }
1441 }
1442}
1443
1444static const Expr* FindExpressionBaseAddress(const Expr* E) {
1445 switch (E->getStmtClass()) {
1446 default:
1447 return E;
1448 case Expr::ParenExprClass: {
1449 const ParenExpr* PE = cast<ParenExpr>(E);
1450 return FindExpressionBaseAddress(PE->getSubExpr());
1451 }
1452 case Expr::UnaryOperatorClass: {
1453 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1454
1455 // C99 6.6p9
1456 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1457 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1458
1459 if (Exp->getOpcode() == UnaryOperator::Extension)
1460 return FindExpressionBaseAddress(Exp->getSubExpr());
1461
1462 return E;
1463 }
1464 case Expr::BinaryOperatorClass: {
1465 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1466
1467 Expr *PExp = Exp->getLHS();
1468 Expr *IExp = Exp->getRHS();
1469 if (IExp->getType()->isPointerType())
1470 std::swap(PExp, IExp);
1471
1472 return FindExpressionBaseAddress(PExp);
1473 }
1474 case Expr::ImplicitCastExprClass: {
1475 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1476
1477 // Check for implicit promotion
1478 if (SubExpr->getType()->isFunctionType() ||
1479 SubExpr->getType()->isArrayType())
1480 return FindExpressionBaseAddressLValue(SubExpr);
1481
1482 // Check for pointer->pointer cast
1483 if (SubExpr->getType()->isPointerType())
1484 return FindExpressionBaseAddress(SubExpr);
1485
1486 // We assume that we have an arithmetic expression here;
1487 // if we don't, we'll figure it out later
1488 return 0;
1489 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001490 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001491 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1492
1493 // Check for pointer->pointer cast
1494 if (SubExpr->getType()->isPointerType())
1495 return FindExpressionBaseAddress(SubExpr);
1496
1497 // We assume that we have an arithmetic expression here;
1498 // if we don't, we'll figure it out later
1499 return 0;
1500 }
1501 }
1502}
1503
Anders Carlsson51fe9962008-11-22 21:04:56 +00001504bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001505 switch (Init->getStmtClass()) {
1506 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001507 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001508 return true;
1509 case Expr::ParenExprClass: {
1510 const ParenExpr* PE = cast<ParenExpr>(Init);
1511 return CheckArithmeticConstantExpression(PE->getSubExpr());
1512 }
1513 case Expr::FloatingLiteralClass:
1514 case Expr::IntegerLiteralClass:
1515 case Expr::CharacterLiteralClass:
1516 case Expr::ImaginaryLiteralClass:
1517 case Expr::TypesCompatibleExprClass:
1518 case Expr::CXXBoolLiteralExprClass:
1519 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001520 case Expr::CallExprClass:
1521 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001522 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001523
1524 // Allow any constant foldable calls to builtins.
1525 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001526 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001527
Steve Naroff6594a702008-10-27 11:34:16 +00001528 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001529 return true;
1530 }
1531 case Expr::DeclRefExprClass: {
1532 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1533 if (isa<EnumConstantDecl>(D))
1534 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001535 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001536 return true;
1537 }
1538 case Expr::CompoundLiteralExprClass:
1539 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1540 // but vectors are allowed to be magic.
1541 if (Init->getType()->isVectorType())
1542 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001543 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001544 return true;
1545 case Expr::UnaryOperatorClass: {
1546 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1547
1548 switch (Exp->getOpcode()) {
1549 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1550 // See C99 6.6p3.
1551 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001552 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001553 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001554 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00001555 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1556 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001557 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001558 return true;
1559 case UnaryOperator::Extension:
1560 case UnaryOperator::LNot:
1561 case UnaryOperator::Plus:
1562 case UnaryOperator::Minus:
1563 case UnaryOperator::Not:
1564 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1565 }
1566 }
Sebastian Redl05189992008-11-11 17:56:53 +00001567 case Expr::SizeOfAlignOfExprClass: {
1568 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001569 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00001570 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00001571 return false;
1572 // alignof always evaluates to a constant.
1573 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00001574 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001575 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001576 return true;
1577 }
1578 return false;
1579 }
1580 case Expr::BinaryOperatorClass: {
1581 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1582
1583 if (Exp->getLHS()->getType()->isArithmeticType() &&
1584 Exp->getRHS()->getType()->isArithmeticType()) {
1585 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1586 CheckArithmeticConstantExpression(Exp->getRHS());
1587 }
1588
Eli Friedman4caf0552008-06-09 05:05:07 +00001589 if (Exp->getLHS()->getType()->isPointerType() &&
1590 Exp->getRHS()->getType()->isPointerType()) {
1591 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1592 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1593
1594 // Only allow a null (constant integer) base; we could
1595 // allow some additional cases if necessary, but this
1596 // is sufficient to cover offsetof-like constructs.
1597 if (!LHSBase && !RHSBase) {
1598 return CheckAddressConstantExpression(Exp->getLHS()) ||
1599 CheckAddressConstantExpression(Exp->getRHS());
1600 }
1601 }
1602
Steve Naroff6594a702008-10-27 11:34:16 +00001603 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001604 return true;
1605 }
1606 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001607 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001608 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001609 if (SubExpr->getType()->isArithmeticType())
1610 return CheckArithmeticConstantExpression(SubExpr);
1611
Eli Friedmanb529d832008-09-02 09:37:00 +00001612 if (SubExpr->getType()->isPointerType()) {
1613 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1614 // If the pointer has a null base, this is an offsetof-like construct
1615 if (!Base)
1616 return CheckAddressConstantExpression(SubExpr);
1617 }
1618
Steve Naroff6594a702008-10-27 11:34:16 +00001619 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001620 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001621 }
1622 case Expr::ConditionalOperatorClass: {
1623 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001624
1625 // If GNU extensions are disabled, we require all operands to be arithmetic
1626 // constant expressions.
1627 if (getLangOptions().NoExtensions) {
1628 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1629 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1630 CheckArithmeticConstantExpression(Exp->getRHS());
1631 }
1632
1633 // Otherwise, we have to emulate some of the behavior of fold here.
1634 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1635 // because it can constant fold things away. To retain compatibility with
1636 // GCC code, we see if we can fold the condition to a constant (which we
1637 // should always be able to do in theory). If so, we only require the
1638 // specified arm of the conditional to be a constant. This is a horrible
1639 // hack, but is require by real world code that uses __builtin_constant_p.
1640 APValue Val;
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001641 if (!Exp->getCond()->Evaluate(Val, Context)) {
1642 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00001643 // won't be able to either. Use it to emit the diagnostic though.
1644 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001645 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00001646 return Res;
1647 }
1648
1649 // Verify that the side following the condition is also a constant.
1650 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1651 if (Val.getInt() == 0)
1652 std::swap(TrueSide, FalseSide);
1653
1654 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001655 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001656
1657 // Okay, the evaluated side evaluates to a constant, so we accept this.
1658 // Check to see if the other side is obviously not a constant. If so,
1659 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001660 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001661 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001662 diag::ext_typecheck_expression_not_constant_but_accepted)
1663 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00001664 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001665 }
1666 }
1667}
1668
1669bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001670 Expr::EvalResult Result;
1671
Nuno Lopes9a979c32008-07-07 16:46:50 +00001672 Init = Init->IgnoreParens();
1673
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001674 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
1675 return false;
1676
Eli Friedmanc594b322008-05-20 13:48:25 +00001677 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1678 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1679 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1680
Nuno Lopes9a979c32008-07-07 16:46:50 +00001681 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1682 return CheckForConstantInitializer(e->getInitializer(), DclT);
1683
Eli Friedmanc594b322008-05-20 13:48:25 +00001684 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1685 unsigned numInits = Exp->getNumInits();
1686 for (unsigned i = 0; i < numInits; i++) {
1687 // FIXME: Need to get the type of the declaration for C++,
1688 // because it could be a reference?
1689 if (CheckForConstantInitializer(Exp->getInit(i),
1690 Exp->getInit(i)->getType()))
1691 return true;
1692 }
1693 return false;
1694 }
1695
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001696 // FIXME: We can probably remove some of this code below, now that
1697 // Expr::Evaluate is doing the heavy lifting for scalars.
1698
Eli Friedmanc594b322008-05-20 13:48:25 +00001699 if (Init->isNullPointerConstant(Context))
1700 return false;
1701 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001702 QualType InitTy = Context.getCanonicalType(Init->getType())
1703 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001704 if (InitTy == Context.BoolTy) {
1705 // Special handling for pointers implicitly cast to bool;
1706 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1707 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1708 Expr* SubE = ICE->getSubExpr();
1709 if (SubE->getType()->isPointerType() ||
1710 SubE->getType()->isArrayType() ||
1711 SubE->getType()->isFunctionType()) {
1712 return CheckAddressConstantExpression(Init);
1713 }
1714 }
1715 } else if (InitTy->isIntegralType()) {
1716 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001717 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001718 SubE = CE->getSubExpr();
1719 // Special check for pointer cast to int; we allow as an extension
1720 // an address constant cast to an integer if the integer
1721 // is of an appropriate width (this sort of code is apparently used
1722 // in some places).
1723 // FIXME: Add pedwarn?
1724 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1725 if (SubE && (SubE->getType()->isPointerType() ||
1726 SubE->getType()->isArrayType() ||
1727 SubE->getType()->isFunctionType())) {
1728 unsigned IntWidth = Context.getTypeSize(Init->getType());
1729 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1730 if (IntWidth >= PointerWidth)
1731 return CheckAddressConstantExpression(Init);
1732 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001733 }
1734
1735 return CheckArithmeticConstantExpression(Init);
1736 }
1737
1738 if (Init->getType()->isPointerType())
1739 return CheckAddressConstantExpression(Init);
1740
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001741 // An array type at the top level that isn't an init-list must
1742 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001743 if (Init->getType()->isArrayType())
1744 return false;
1745
Nuno Lopes73419bf2008-09-01 18:42:41 +00001746 if (Init->getType()->isFunctionType())
1747 return false;
1748
Steve Naroff8af6a452008-10-02 17:12:56 +00001749 // Allow block exprs at top level.
1750 if (Init->getType()->isBlockPointerType())
1751 return false;
1752
Steve Naroff6594a702008-10-27 11:34:16 +00001753 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001754 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001755}
1756
Steve Naroffbb204692007-09-12 14:07:44 +00001757void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001758 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001759 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001760 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001761
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001762 // If there is no declaration, there was an error parsing it. Just ignore
1763 // the initializer.
1764 if (RealDecl == 0) {
1765 delete Init;
1766 return;
1767 }
Steve Naroffbb204692007-09-12 14:07:44 +00001768
Steve Naroff410e3e22007-09-12 20:13:48 +00001769 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1770 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001771 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1772 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001773 RealDecl->setInvalidDecl();
1774 return;
1775 }
Steve Naroffbb204692007-09-12 14:07:44 +00001776 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001777 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001778 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001779 if (VDecl->isBlockVarDecl()) {
1780 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001781 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001782 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001783 VDecl->setInvalidDecl();
1784 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001785 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001786 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001787 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001788
1789 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1790 if (!getLangOptions().CPlusPlus) {
1791 if (SC == VarDecl::Static) // C99 6.7.8p4.
1792 CheckForConstantInitializer(Init, DclT);
1793 }
Steve Naroffbb204692007-09-12 14:07:44 +00001794 }
Steve Naroff248a7532008-04-15 22:42:06 +00001795 } else if (VDecl->isFileVarDecl()) {
1796 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001797 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001798 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001799 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001800 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001801 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001802
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001803 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1804 if (!getLangOptions().CPlusPlus) {
1805 // C99 6.7.8p4. All file scoped initializers need to be constant.
1806 CheckForConstantInitializer(Init, DclT);
1807 }
Steve Naroffbb204692007-09-12 14:07:44 +00001808 }
1809 // If the type changed, it means we had an incomplete type that was
1810 // completed by the initializer. For example:
1811 // int ary[] = { 1, 3, 5 };
1812 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001813 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001814 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001815 Init->setType(DclT);
1816 }
Steve Naroffbb204692007-09-12 14:07:44 +00001817
1818 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001819 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001820 return;
1821}
1822
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001823void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1824 Decl *RealDecl = static_cast<Decl *>(dcl);
1825
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00001826 // If there is no declaration, there was an error parsing it. Just ignore it.
1827 if (RealDecl == 0)
1828 return;
1829
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001830 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1831 QualType Type = Var->getType();
1832 // C++ [dcl.init.ref]p3:
1833 // The initializer can be omitted for a reference only in a
1834 // parameter declaration (8.3.5), in the declaration of a
1835 // function return type, in the declaration of a class member
1836 // within its class declaration (9.2), and where the extern
1837 // specifier is explicitly used.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001838 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001839 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001840 << Var->getDeclName()
1841 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00001842 Var->setInvalidDecl();
1843 return;
1844 }
1845
1846 // C++ [dcl.init]p9:
1847 //
1848 // If no initializer is specified for an object, and the object
1849 // is of (possibly cv-qualified) non-POD class type (or array
1850 // thereof), the object shall be default-initialized; if the
1851 // object is of const-qualified type, the underlying class type
1852 // shall have a user-declared default constructor.
1853 if (getLangOptions().CPlusPlus) {
1854 QualType InitType = Type;
1855 if (const ArrayType *Array = Context.getAsArrayType(Type))
1856 InitType = Array->getElementType();
1857 if (InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001858 const CXXConstructorDecl *Constructor
1859 = PerformInitializationByConstructor(InitType, 0, 0,
1860 Var->getLocation(),
1861 SourceRange(Var->getLocation(),
1862 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001863 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001864 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001865 if (!Constructor)
1866 Var->setInvalidDecl();
1867 }
1868 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001869
Douglas Gregor818ce482008-10-29 13:50:18 +00001870#if 0
1871 // FIXME: Temporarily disabled because we are not properly parsing
1872 // linkage specifications on declarations, e.g.,
1873 //
1874 // extern "C" const CGPoint CGPointerZero;
1875 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001876 // C++ [dcl.init]p9:
1877 //
1878 // If no initializer is specified for an object, and the
1879 // object is of (possibly cv-qualified) non-POD class type (or
1880 // array thereof), the object shall be default-initialized; if
1881 // the object is of const-qualified type, the underlying class
1882 // type shall have a user-declared default
1883 // constructor. Otherwise, if no initializer is specified for
1884 // an object, the object and its subobjects, if any, have an
1885 // indeterminate initial value; if the object or any of its
1886 // subobjects are of const-qualified type, the program is
1887 // ill-formed.
1888 //
1889 // This isn't technically an error in C, so we don't diagnose it.
1890 //
1891 // FIXME: Actually perform the POD/user-defined default
1892 // constructor check.
1893 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00001894 Context.getCanonicalType(Type).isConstQualified() &&
1895 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001896 Diag(Var->getLocation(), diag::err_const_var_requires_init)
1897 << Var->getName()
1898 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00001899#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001900 }
1901}
1902
Reid Spencer5f016e22007-07-11 17:01:13 +00001903/// The declarators are chained together backwards, reverse the list.
1904Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1905 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001906 Decl *GroupDecl = static_cast<Decl*>(group);
1907 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001908 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001909
1910 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1911 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001912 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001914 else { // reverse the list.
1915 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001916 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001917 Group->setNextDeclarator(NewGroup);
1918 NewGroup = Group;
1919 Group = Next;
1920 }
1921 }
1922 // Perform semantic analysis that depends on having fully processed both
1923 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001924 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001925 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1926 if (!IDecl)
1927 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001928 QualType T = IDecl->getType();
1929
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001930 if (T->isVariableArrayType()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00001931 const VariableArrayType *VAT =
1932 cast<VariableArrayType>(T.getUnqualifiedType());
1933
1934 // FIXME: This won't give the correct result for
1935 // int a[10][n];
1936 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001937 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00001938 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
1939 SizeRange;
1940
Eli Friedmanc5773c42008-02-15 18:16:39 +00001941 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001942 } else {
1943 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1944 // static storage duration, it shall not have a variable length array.
1945 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00001946 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
1947 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001948 IDecl->setInvalidDecl();
1949 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00001950 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
1951 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001952 IDecl->setInvalidDecl();
1953 }
1954 }
1955 } else if (T->isVariablyModifiedType()) {
1956 if (IDecl->isFileVarDecl()) {
1957 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
1958 IDecl->setInvalidDecl();
1959 } else {
1960 if (IDecl->getStorageClass() == VarDecl::Extern) {
1961 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
1962 IDecl->setInvalidDecl();
1963 }
Steve Naroffbb204692007-09-12 14:07:44 +00001964 }
1965 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001966
Steve Naroffbb204692007-09-12 14:07:44 +00001967 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1968 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001969 if (IDecl->isBlockVarDecl() &&
1970 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001971 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001972 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00001973 IDecl->setInvalidDecl();
1974 }
1975 }
1976 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1977 // object that has file scope without an initializer, and without a
1978 // storage-class specifier or with the storage-class specifier "static",
1979 // constitutes a tentative definition. Note: A tentative definition with
1980 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001981 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001982 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001983 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1984 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001985 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001986 // C99 6.9.2p3: If the declaration of an identifier for an object is
1987 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1988 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001989 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00001990 IDecl->setInvalidDecl();
1991 }
1992 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001993 if (IDecl->isFileVarDecl())
1994 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 }
1996 return NewGroup;
1997}
Steve Naroffe1223f72007-08-28 03:03:08 +00001998
Chris Lattner04421082008-04-08 04:40:51 +00001999/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2000/// to introduce parameters into function prototype scope.
2001Sema::DeclTy *
2002Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002003 // FIXME: disallow CXXScopeSpec for param declarators.
Chris Lattner985abd92008-06-26 06:49:43 +00002004 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00002005
2006 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002007 VarDecl::StorageClass StorageClass = VarDecl::None;
2008 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2009 StorageClass = VarDecl::Register;
2010 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002011 Diag(DS.getStorageClassSpecLoc(),
2012 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002013 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002014 }
2015 if (DS.isThreadSpecified()) {
2016 Diag(DS.getThreadSpecLoc(),
2017 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002018 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002019 }
2020
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002021 // Check that there are no default arguments inside the type of this
2022 // parameter (C++ only).
2023 if (getLangOptions().CPlusPlus)
2024 CheckExtraCXXDefaultArguments(D);
2025
Chris Lattner04421082008-04-08 04:40:51 +00002026 // In this context, we *do not* check D.getInvalidType(). If the declarator
2027 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2028 // though it will not reflect the user specified type.
2029 QualType parmDeclType = GetTypeForDeclarator(D, S);
2030
2031 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2032
Reid Spencer5f016e22007-07-11 17:01:13 +00002033 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2034 // Can this happen for params? We already checked that they don't conflict
2035 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002036 IdentifierInfo *II = D.getIdentifier();
2037 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002038 if (isTemplateParameterDecl(PrevDecl)) {
2039 // Maybe we will complain about the shadowed template parameter.
2040 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2041 // Just pretend that we didn't see the previous declaration.
2042 PrevDecl = 0;
2043 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002044 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002045
2046 // Recover by removing the name
2047 II = 0;
2048 D.SetIdentifier(0, D.getIdentifierLoc());
2049 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002050 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002051
2052 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2053 // Doing the promotion here has a win and a loss. The win is the type for
2054 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2055 // code generator). The loss is the orginal type isn't preserved. For example:
2056 //
2057 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2058 // int blockvardecl[5];
2059 // sizeof(parmvardecl); // size == 4
2060 // sizeof(blockvardecl); // size == 20
2061 // }
2062 //
2063 // For expressions, all implicit conversions are captured using the
2064 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2065 //
2066 // FIXME: If a source translation tool needs to see the original type, then
2067 // we need to consider storing both types (in ParmVarDecl)...
2068 //
Chris Lattnere6327742008-04-02 05:18:44 +00002069 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002070 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002071 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002072 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002073 parmDeclType = Context.getPointerType(parmDeclType);
2074
Chris Lattner04421082008-04-08 04:40:51 +00002075 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2076 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002077 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002078 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002079
Chris Lattner04421082008-04-08 04:40:51 +00002080 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002081 New->setInvalidDecl();
2082
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002083 if (II)
2084 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00002085
Chris Lattner3ff30c82008-06-29 00:02:00 +00002086 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002088
Reid Spencer5f016e22007-07-11 17:01:13 +00002089}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002090
Chris Lattnerb652cea2007-10-09 17:14:05 +00002091Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002092 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002093 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2094 "Not a function declarator!");
2095 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002096
Reid Spencer5f016e22007-07-11 17:01:13 +00002097 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2098 // for a K&R function.
2099 if (!FTI.hasPrototype) {
2100 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002101 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002102 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2103 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002104 // Implicitly declare the argument as type 'int' for lack of a better
2105 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002106 DeclSpec DS;
2107 const char* PrevSpec; // unused
2108 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2109 PrevSpec);
2110 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2111 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2112 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 }
2114 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002116 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002117 }
2118
2119 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002120
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002121 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00002122 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002123}
2124
2125Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2126 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002127 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002128
2129 // See if this is a redefinition.
2130 const FunctionDecl *Definition;
2131 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002132 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002133 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002134 }
2135
Chris Lattnerb048c982008-04-06 04:47:34 +00002136 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00002137
2138 // Check the validity of our function parameters
2139 CheckParmsForFunctionDef(FD);
2140
2141 // Introduce our parameters into the function scope
2142 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2143 ParmVarDecl *Param = FD->getParamDecl(p);
2144 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002145 if (Param->getIdentifier())
2146 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002147 }
Chris Lattner04421082008-04-08 04:40:51 +00002148
Reid Spencer5f016e22007-07-11 17:01:13 +00002149 return FD;
2150}
2151
Steve Naroffd6d054d2007-11-11 23:20:51 +00002152Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2153 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00002154 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002155 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002156 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002157 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002158 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002159 } else
2160 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002161 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002162 // Verify and clean out per-function state.
2163
2164 // Check goto/label use.
2165 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2166 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2167 // Verify that we have no forward references left. If so, there was a goto
2168 // or address of a label taken, but no definition of it. Label fwd
2169 // definitions are indicated with a null substmt.
2170 if (I->second->getSubStmt() == 0) {
2171 LabelStmt *L = I->second;
2172 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002173 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002174
2175 // At this point, we have gotos that use the bogus label. Stitch it into
2176 // the function body so that they aren't leaked and that the AST is well
2177 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002178 if (Body) {
2179 L->setSubStmt(new NullStmt(L->getIdentLoc()));
2180 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2181 } else {
2182 // The whole function wasn't parsed correctly, just delete this.
2183 delete L;
2184 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002185 }
2186 }
2187 LabelMap.clear();
2188
Steve Naroffd6d054d2007-11-11 23:20:51 +00002189 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002190}
2191
Reid Spencer5f016e22007-07-11 17:01:13 +00002192/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2193/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002194ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2195 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002196 // Extension in C99. Legal in C90, but warn about it.
2197 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002198 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002199 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002200 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002201
2202 // FIXME: handle stuff like:
2203 // void foo() { extern float X(); }
2204 // void bar() { X(); } <-- implicit decl for X in another scope.
2205
2206 // Set a Declarator for the implicit definition: int foo();
2207 const char *Dummy;
2208 DeclSpec DS;
2209 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2210 Error = Error; // Silence warning.
2211 assert(!Error && "Error setting up implicit decl!");
2212 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002213 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002214 D.SetIdentifier(&II, Loc);
2215
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002216 // Insert this function into translation-unit scope.
2217
2218 DeclContext *PrevDC = CurContext;
2219 CurContext = Context.getTranslationUnitDecl();
2220
Steve Naroffe2ef8152008-04-04 14:32:09 +00002221 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002222 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002223 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002224
2225 CurContext = PrevDC;
2226
Steve Naroffe2ef8152008-04-04 14:32:09 +00002227 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002228}
2229
2230
Chris Lattner41af0932007-11-14 06:34:38 +00002231TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002232 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002233 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002234 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002235
2236 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002237 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2238 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002239 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002240 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002241 if (D.getInvalidType())
2242 NewTD->setInvalidDecl();
2243 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002244}
2245
Steve Naroff08d92e42007-09-15 18:49:24 +00002246/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002247/// former case, Name will be non-null. In the later case, Name will be null.
2248/// TagType indicates what kind of tag this is. TK indicates whether this is a
2249/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002250Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002251 SourceLocation KWLoc, const CXXScopeSpec &SS,
2252 IdentifierInfo *Name, SourceLocation NameLoc,
2253 AttributeList *Attr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002254 // If this is a use of an existing tag, it must have a name.
2255 assert((Name != 0 || TK == TK_Definition) &&
2256 "Nameless record must be a definition!");
2257
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002258 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002259 switch (TagType) {
2260 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002261 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2262 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2263 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2264 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002265 }
2266
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002267 // Two code paths: a new one for structs/unions/classes where we create
2268 // separate decls for forward declarations, and an old (eventually to
2269 // be removed) code path for enums.
2270 if (Kind != TagDecl::TK_enum)
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002271 return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002272
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002273 DeclContext *DC = CurContext;
2274 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002275
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002276 if (Name && SS.isNotEmpty()) {
2277 // We have a nested-name tag ('struct foo::bar').
2278
2279 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002280 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002281 Name = 0;
2282 goto CreateNewDecl;
2283 }
2284
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002285 DC = static_cast<DeclContext*>(SS.getScopeRep());
2286 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002287 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2288
2289 // A tag 'foo::bar' must already exist.
2290 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002291 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002292 Name = 0;
2293 goto CreateNewDecl;
2294 }
2295 } else {
2296 // If this is a named struct, check to see if there was a previous forward
2297 // declaration or definition.
2298 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2299 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2300 }
2301
Douglas Gregor72c3f312008-12-05 18:15:24 +00002302 if (PrevDecl && isTemplateParameterDecl(PrevDecl)) {
2303 // Maybe we will complain about the shadowed template parameter.
2304 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2305 // Just pretend that we didn't see the previous declaration.
2306 PrevDecl = 0;
2307 }
2308
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002309 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002310 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2311 "unexpected Decl type");
2312 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002313 // If this is a use of a previous tag, or if the tag is already declared
2314 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002315 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002316 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002317 // Make sure that this wasn't declared as an enum and now used as a
2318 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002319 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002320 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002321 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002322 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002323 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002324 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002325 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00002326 // If this is a use or a forward declaration, we're good.
2327 if (TK != TK_Definition)
2328 return PrevDecl;
2329
2330 // Diagnose attempts to redefine a tag.
2331 if (PrevTagDecl->isDefinition()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002332 Diag(NameLoc, diag::err_redefinition) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002333 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner14943b92008-07-03 03:30:58 +00002334 // If this is a redefinition, recover by making this struct be
2335 // anonymous, which will make any later references get the previous
2336 // definition.
2337 Name = 0;
2338 } else {
2339 // Okay, this is definition of a previously declared or referenced
2340 // tag. Move the location of the decl to be the definition site.
2341 PrevDecl->setLocation(NameLoc);
2342 return PrevDecl;
2343 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002344 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002345 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002346 // If we get here, this is a definition of a new struct type in a nested
2347 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2348 // type.
2349 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002350 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002351 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002352 // The tag name clashes with a namespace name, issue an error and
2353 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002354 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002355 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002356 Name = 0;
2357 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002358 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002359 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002360
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002361 CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002362
2363 // If there is an identifier, use the location of the identifier as the
2364 // location of the decl, otherwise use the location of the struct/union
2365 // keyword.
2366 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2367
2368 // Otherwise, if this is the first time we've seen this tag, create the decl.
2369 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002370 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002371 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2372 // enum X { A, B, C } D; D should chain to X.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002373 New = EnumDecl::Create(Context, DC, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002374 // If this is an undefined enum, warn.
2375 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002376 } else {
2377 // struct/union/class
2378
Reid Spencer5f016e22007-07-11 17:01:13 +00002379 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2380 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002381 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002382 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002383 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002384 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002385 New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002386 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002387
2388 // If this has an identifier, add it to the scope stack.
2389 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002390 // The scope passed in may not be a decl scope. Zip up the scope tree until
2391 // we find one that is.
2392 while ((S->getFlags() & Scope::DeclScope) == 0)
2393 S = S->getParent();
2394
2395 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002396 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002397 }
Chris Lattnere1e79852008-02-06 00:51:33 +00002398
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00002399 if (Attr)
2400 ProcessDeclAttributeList(New, Attr);
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002401
2402 // Set the lexical context. If the tag has a C++ scope specifier, the
2403 // lexical context will be different from the semantic context.
2404 New->setLexicalDeclContext(CurContext);
2405
Reid Spencer5f016e22007-07-11 17:01:13 +00002406 return New;
2407}
2408
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002409/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2410/// the logic for enums, we create separate decls for forward declarations.
2411/// This is called by ActOnTag, but eventually will replace its logic.
2412Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002413 SourceLocation KWLoc, const CXXScopeSpec &SS,
2414 IdentifierInfo *Name, SourceLocation NameLoc,
2415 AttributeList *Attr) {
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002416 DeclContext *DC = CurContext;
2417 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002418
2419 if (Name && SS.isNotEmpty()) {
2420 // We have a nested-name tag ('struct foo::bar').
2421
2422 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002423 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002424 Name = 0;
2425 goto CreateNewDecl;
2426 }
2427
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002428 DC = static_cast<DeclContext*>(SS.getScopeRep());
2429 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002430 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2431
2432 // A tag 'foo::bar' must already exist.
2433 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002434 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002435 Name = 0;
2436 goto CreateNewDecl;
2437 }
2438 } else {
2439 // If this is a named struct, check to see if there was a previous forward
2440 // declaration or definition.
2441 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2442 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2443 }
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002444
Douglas Gregor72c3f312008-12-05 18:15:24 +00002445 if (PrevDecl && isTemplateParameterDecl(PrevDecl)) {
2446 // Maybe we will complain about the shadowed template parameter.
2447 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2448 // Just pretend that we didn't see the previous declaration.
2449 PrevDecl = 0;
2450 }
2451
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002452 if (PrevDecl) {
2453 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2454 "unexpected Decl type");
2455
2456 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2457 // If this is a use of a previous tag, or if the tag is already declared
2458 // in the same scope (so that the definition/declaration completes or
2459 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002460 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002461 // Make sure that this wasn't declared as an enum and now used as a
2462 // struct or something similar.
2463 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002464 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002465 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002466 // Recover by making this an anonymous redefinition.
2467 Name = 0;
2468 PrevDecl = 0;
2469 } else {
2470 // If this is a use, return the original decl.
2471
2472 // FIXME: In the future, return a variant or some other clue
2473 // for the consumer of this Decl to know it doesn't own it.
2474 // For our current ASTs this shouldn't be a problem, but will
2475 // need to be changed with DeclGroups.
2476 if (TK == TK_Reference)
2477 return PrevDecl;
2478
2479 // The new decl is a definition?
2480 if (TK == TK_Definition) {
2481 // Diagnose attempts to redefine a tag.
2482 if (RecordDecl* DefRecord =
2483 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002484 Diag(NameLoc, diag::err_redefinition) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002485 Diag(DefRecord->getLocation(), diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002486 // If this is a redefinition, recover by making this struct be
2487 // anonymous, which will make any later references get the previous
2488 // definition.
2489 Name = 0;
2490 PrevDecl = 0;
2491 }
2492 // Okay, this is definition of a previously declared or referenced
2493 // tag. We're going to create a new Decl.
2494 }
2495 }
2496 // If we get here we have (another) forward declaration. Just create
2497 // a new decl.
2498 }
2499 else {
2500 // If we get here, this is a definition of a new struct type in a nested
2501 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2502 // new decl/type. We set PrevDecl to NULL so that the Records
2503 // have distinct types.
2504 PrevDecl = 0;
2505 }
2506 } else {
2507 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002508 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002509 // The tag name clashes with a namespace name, issue an error and
2510 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002511 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002512 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002513 Name = 0;
2514 }
2515 }
2516 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002517
2518 CreateNewDecl:
2519
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002520 // If there is an identifier, use the location of the identifier as the
2521 // location of the decl, otherwise use the location of the struct/union
2522 // keyword.
2523 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2524
2525 // Otherwise, if this is the first time we've seen this tag, create the decl.
2526 TagDecl *New;
2527
2528 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2529 // struct X { int A; } D; D should chain to X.
2530 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002531 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002532 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002533 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2534 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002535 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002536 dyn_cast_or_null<RecordDecl>(PrevDecl));
2537
2538 // If this has an identifier, add it to the scope stack.
2539 if ((TK == TK_Definition || !PrevDecl) && Name) {
2540 // The scope passed in may not be a decl scope. Zip up the scope tree until
2541 // we find one that is.
2542 while ((S->getFlags() & Scope::DeclScope) == 0)
2543 S = S->getParent();
2544
2545 // Add it to the decl chain.
2546 PushOnScopeChains(New, S);
2547 }
Daniel Dunbar3b0db902008-10-16 02:34:03 +00002548
2549 // Handle #pragma pack: if the #pragma pack stack has non-default
2550 // alignment, make up a packed attribute for this decl. These
2551 // attributes are checked when the ASTContext lays out the
2552 // structure.
2553 //
2554 // It is important for implementing the correct semantics that this
2555 // happen here (in act on tag decl). The #pragma pack stack is
2556 // maintained as a result of parser callbacks which can occur at
2557 // many points during the parsing of a struct declaration (because
2558 // the #pragma tokens are effectively skipped over during the
2559 // parsing of the struct).
2560 if (unsigned Alignment = PackContext.getAlignment())
2561 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002562
2563 if (Attr)
2564 ProcessDeclAttributeList(New, Attr);
2565
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002566 // Set the lexical context. If the tag has a C++ scope specifier, the
2567 // lexical context will be different from the semantic context.
2568 New->setLexicalDeclContext(CurContext);
2569
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002570 return New;
2571}
2572
2573
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002574/// Collect the instance variables declared in an Objective-C object. Used in
2575/// the creation of structures from objects using the @defs directive.
Ted Kremenek01e67792008-08-20 03:26:33 +00002576static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002577 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002578 if (Class->getSuperClass())
Ted Kremenek01e67792008-08-20 03:26:33 +00002579 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2580
2581 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremeneka89d1972008-09-03 18:03:35 +00002582 for (ObjCInterfaceDecl::ivar_iterator
2583 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2584
Ted Kremenek01e67792008-08-20 03:26:33 +00002585 ObjCIvarDecl* ID = *I;
2586 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2587 ID->getIdentifier(),
2588 ID->getType(),
2589 ID->getBitWidth()));
2590 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002591}
2592
2593/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2594/// instance variables of ClassName into Decls.
2595void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2596 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002597 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002598 // Check that ClassName is a valid class
2599 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2600 if (!Class) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002601 Diag(DeclStart, diag::err_undef_interface) << ClassName;
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002602 return;
2603 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002604 // Collect the instance variables
Ted Kremenek01e67792008-08-20 03:26:33 +00002605 CollectIvars(Class, Context, Decls);
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002606}
2607
Chris Lattner1d353ba2008-11-12 21:17:48 +00002608/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2609/// types into constant array types in certain situations which would otherwise
2610/// be errors (for GCC compatibility).
2611static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2612 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002613 // This method tries to turn a variable array into a constant
2614 // array even when the size isn't an ICE. This is necessary
2615 // for compatibility with code that depends on gcc's buggy
2616 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00002617 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2618 if (!VLATy) return QualType();
2619
2620 APValue Result;
2621 if (!VLATy->getSizeExpr() ||
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002622 !VLATy->getSizeExpr()->Evaluate(Result, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00002623 return QualType();
2624
2625 assert(Result.isInt() && "Size expressions must be integers!");
2626 llvm::APSInt &Res = Result.getInt();
2627 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2628 return Context.getConstantArrayType(VLATy->getElementType(),
2629 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002630 return QualType();
2631}
2632
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002633bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
2634 QualType FieldTy, const Expr *BitWidth)
2635{
2636 // FIXME: 6.7.2.1p4 - verify the field type.
2637
2638 llvm::APSInt Value;
2639 if (VerifyIntegerConstantExpression(BitWidth, &Value))
2640 return true;
2641
2642 if (Value.isNegative()) {
2643 Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
2644 return true;
2645 }
2646
2647 uint64_t TypeSize = Context.getTypeSize(FieldTy);
2648 // FIXME: We won't need the 0 size once we check that the field type is valid.
2649 if (TypeSize && Value.getZExtValue() > TypeSize) {
2650 Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) <<
2651 FieldName << (unsigned)TypeSize;
2652 return true;
2653 }
2654
2655 return false;
2656}
2657
Steve Naroff08d92e42007-09-15 18:49:24 +00002658/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002659/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002660Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00002661 SourceLocation DeclStart,
2662 Declarator &D, ExprTy *BitfieldWidth) {
2663 IdentifierInfo *II = D.getIdentifier();
2664 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002665 SourceLocation Loc = DeclStart;
2666 if (II) Loc = D.getIdentifierLoc();
2667
2668 // FIXME: Unnamed fields can be handled in various different ways, for
2669 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00002670
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002672 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2673 bool InvalidDecl = false;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002674
Reid Spencer5f016e22007-07-11 17:01:13 +00002675 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2676 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002677 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00002678 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002679 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002680 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002681 T = FixedTy;
2682 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002683 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00002684 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002685 InvalidDecl = true;
2686 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002687 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002688
2689 if (BitWidth) {
2690 if (VerifyBitField(Loc, II, T, BitWidth))
2691 InvalidDecl = true;
2692 } else {
2693 // Not a bitfield.
2694
2695 // validate II.
2696
2697 }
2698
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002700 FieldDecl *NewFD;
2701
2702 if (getLangOptions().CPlusPlus) {
2703 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2704 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
Sebastian Redla11f42f2008-11-17 23:24:37 +00002705 Loc, II, T,
2706 D.getDeclSpec().getStorageClassSpec() ==
2707 DeclSpec::SCS_mutable, BitWidth);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002708 if (II)
2709 PushOnScopeChains(NewFD, S);
2710 }
2711 else
2712 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00002713
Chris Lattner3ff30c82008-06-29 00:02:00 +00002714 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002715
Steve Naroff5912a352007-08-28 20:14:24 +00002716 if (D.getInvalidType() || InvalidDecl)
2717 NewFD->setInvalidDecl();
2718 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002719}
2720
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002721/// TranslateIvarVisibility - Translate visibility from a token ID to an
2722/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002723static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002724TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002725 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002726 default: assert(0 && "Unknown visitibility kind");
2727 case tok::objc_private: return ObjCIvarDecl::Private;
2728 case tok::objc_public: return ObjCIvarDecl::Public;
2729 case tok::objc_protected: return ObjCIvarDecl::Protected;
2730 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002731 }
2732}
2733
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002734/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2735/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002736Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002737 SourceLocation DeclStart,
2738 Declarator &D, ExprTy *BitfieldWidth,
2739 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002740 IdentifierInfo *II = D.getIdentifier();
2741 Expr *BitWidth = (Expr*)BitfieldWidth;
2742 SourceLocation Loc = DeclStart;
2743 if (II) Loc = D.getIdentifierLoc();
2744
2745 // FIXME: Unnamed fields can be handled in various different ways, for
2746 // example, unnamed unions inject all members into the struct namespace!
2747
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002748 QualType T = GetTypeForDeclarator(D, S);
2749 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2750 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002751
2752 if (BitWidth) {
2753 // TODO: Validate.
2754 //printf("WARNING: BITFIELDS IGNORED!\n");
2755
2756 // 6.7.2.1p3
2757 // 6.7.2.1p4
2758
2759 } else {
2760 // Not a bitfield.
2761
2762 // validate II.
2763
2764 }
2765
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002766 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2767 // than a variably modified type.
2768 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002769 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002770 InvalidDecl = true;
2771 }
2772
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002773 // Get the visibility (access control) for this ivar.
2774 ObjCIvarDecl::AccessControl ac =
2775 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2776 : ObjCIvarDecl::None;
2777
2778 // Construct the decl.
2779 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002780 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002781
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002782 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002783 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002784
2785 if (D.getInvalidType() || InvalidDecl)
2786 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002787
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002788 return NewID;
2789}
2790
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002791void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002792 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002793 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002794 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002795 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002796 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2797 assert(EnclosingDecl && "missing record or interface decl");
2798 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2799
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002800 if (Record)
2801 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2802 // Diagnose code like:
2803 // struct S { struct S {} X; };
2804 // We discover this when we complete the outer S. Reject and ignore the
2805 // outer S.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002806 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002807 << DefRecord->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002808 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002809 Record->setInvalidDecl();
2810 return;
2811 }
2812
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 // Verify that all the fields are okay.
2814 unsigned NumNamedMembers = 0;
2815 llvm::SmallVector<FieldDecl*, 32> RecFields;
2816 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002817
Reid Spencer5f016e22007-07-11 17:01:13 +00002818 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002819
Steve Naroff74216642007-09-14 22:20:54 +00002820 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2821 assert(FD && "missing field decl");
2822
2823 // Remember all fields.
2824 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002825
2826 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002827 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002828
Reid Spencer5f016e22007-07-11 17:01:13 +00002829 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002830 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002831 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002832 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002833 FD->setInvalidDecl();
2834 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002835 continue;
2836 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002837 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2838 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002839 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002840 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002841 FD->setInvalidDecl();
2842 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002843 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002844 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002845 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002846 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002847 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002848 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002849 FD->setInvalidDecl();
2850 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002851 continue;
2852 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002853 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002854 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002855 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002856 FD->setInvalidDecl();
2857 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002858 continue;
2859 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002860 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002861 if (Record)
2862 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002863 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002864 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2865 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002866 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002867 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2868 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002869 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002870 Record->setHasFlexibleArrayMember(true);
2871 } else {
2872 // If this is a struct/class and this is not the last element, reject
2873 // it. Note that GCC supports variable sized arrays in the middle of
2874 // structures.
2875 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002876 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002877 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002878 FD->setInvalidDecl();
2879 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002880 continue;
2881 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002882 // We support flexible arrays at the end of structs in other structs
2883 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002884 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002885 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002886 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002887 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002888 }
2889 }
2890 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002891 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002892 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002893 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00002894 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002895 FD->setInvalidDecl();
2896 EnclosingDecl->setInvalidDecl();
2897 continue;
2898 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002899 // Keep track of the number of named members.
2900 if (IdentifierInfo *II = FD->getIdentifier()) {
2901 // Detect duplicate member names.
2902 if (!FieldIDs.insert(II)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002903 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002904 // Find the previous decl.
2905 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00002906 for (unsigned i = 0; ; ++i) {
2907 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00002908 if (RecFields[i]->getIdentifier() == II) {
2909 PrevLoc = RecFields[i]->getLocation();
2910 break;
2911 }
2912 }
Chris Lattner5f4a6822008-11-23 23:12:31 +00002913 Diag(PrevLoc, diag::note_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002914 FD->setInvalidDecl();
2915 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002916 continue;
2917 }
2918 ++NumNamedMembers;
2919 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002920 }
2921
Reid Spencer5f016e22007-07-11 17:01:13 +00002922 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002923 if (Record) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002924 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00002925 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2926 // Sema::ActOnFinishCXXClassDef.
2927 if (!isa<CXXRecordDecl>(Record))
2928 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00002929 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002930 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2931 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2932 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2933 else if (ObjCImplementationDecl *IMPDecl =
2934 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002935 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2936 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002937 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002938 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002939 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00002940
2941 if (Attr)
2942 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002943}
2944
Steve Naroff08d92e42007-09-15 18:49:24 +00002945Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002946 DeclTy *lastEnumConst,
2947 SourceLocation IdLoc, IdentifierInfo *Id,
2948 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002949 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002950 EnumConstantDecl *LastEnumConst =
2951 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2952 Expr *Val = static_cast<Expr*>(val);
2953
Chris Lattner31e05722007-08-26 06:24:45 +00002954 // The scope passed in may not be a decl scope. Zip up the scope tree until
2955 // we find one that is.
2956 while ((S->getFlags() & Scope::DeclScope) == 0)
2957 S = S->getParent();
2958
Reid Spencer5f016e22007-07-11 17:01:13 +00002959 // Verify that there isn't already something declared with this name in this
2960 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00002961 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
2962 if (PrevDecl && isTemplateParameterDecl(PrevDecl)) {
2963 // Maybe we will complain about the shadowed template parameter.
2964 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
2965 // Just pretend that we didn't see the previous declaration.
2966 PrevDecl = 0;
2967 }
2968
2969 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002970 // When in C++, we may get a TagDecl with the same name; in this case the
2971 // enum constant will 'hide' the tag.
2972 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2973 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002974 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002975 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00002976 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00002977 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002978 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002979 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002980 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002981 return 0;
2982 }
2983 }
2984
2985 llvm::APSInt EnumVal(32);
2986 QualType EltTy;
2987 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002988 // Make sure to promote the operand type to int.
2989 UsualUnaryConversions(Val);
2990
Reid Spencer5f016e22007-07-11 17:01:13 +00002991 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2992 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00002993 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00002994 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002995 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002996 } else {
2997 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002998 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002999 }
3000
3001 if (!Val) {
3002 if (LastEnumConst) {
3003 // Assign the last value + 1.
3004 EnumVal = LastEnumConst->getInitVal();
3005 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003006
3007 // Check for overflow on increment.
3008 if (EnumVal < LastEnumConst->getInitVal())
3009 Diag(IdLoc, diag::warn_enum_value_overflow);
3010
Chris Lattnerb7416f92007-08-27 17:37:24 +00003011 EltTy = LastEnumConst->getType();
3012 } else {
3013 // First value, set to zero.
3014 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003015 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003016 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003017 }
3018
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003019 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003020 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3021 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003022 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003023
3024 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003025 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00003026 return New;
3027}
3028
Steve Naroff02408c62008-08-07 14:08:16 +00003029// FIXME: For consistency with ActOnFields(), we should have the parser
3030// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003031void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003032 DeclTy **Elements, unsigned NumElements) {
3033 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00003034
Steve Naroff02408c62008-08-07 14:08:16 +00003035 if (Enum && Enum->isDefinition()) {
3036 // Diagnose code like:
3037 // enum e0 {
3038 // E0 = sizeof(enum e0 { E1 })
3039 // };
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003040 Diag(Enum->getLocation(), diag::err_nested_redefinition)
3041 << Enum->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003042 Diag(EnumLoc, diag::note_previous_definition);
Steve Naroff02408c62008-08-07 14:08:16 +00003043 Enum->setInvalidDecl();
3044 return;
3045 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00003046 // TODO: If the result value doesn't fit in an int, it must be a long or long
3047 // long value. ISO C does not support this, but GCC does as an extension,
3048 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003049 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003050
Chris Lattnerac609682007-08-28 06:15:15 +00003051 // Verify that all the values are okay, compute the size of the values, and
3052 // reverse the list.
3053 unsigned NumNegativeBits = 0;
3054 unsigned NumPositiveBits = 0;
3055
3056 // Keep track of whether all elements have type int.
3057 bool AllElementsInt = true;
3058
Reid Spencer5f016e22007-07-11 17:01:13 +00003059 EnumConstantDecl *EltList = 0;
3060 for (unsigned i = 0; i != NumElements; ++i) {
3061 EnumConstantDecl *ECD =
3062 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3063 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003064
3065 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003066 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003067 assert(InitVal.getBitWidth() >= IntWidth &&
3068 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003069 if (InitVal.getBitWidth() > IntWidth) {
3070 llvm::APSInt V(InitVal);
3071 V.trunc(IntWidth);
3072 V.extend(InitVal.getBitWidth());
3073 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003074 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3075 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003076 }
Chris Lattnerac609682007-08-28 06:15:15 +00003077
3078 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003079 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003080 NumPositiveBits = std::max(NumPositiveBits,
3081 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003082 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003083 NumNegativeBits = std::max(NumNegativeBits,
3084 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003085
Chris Lattnerac609682007-08-28 06:15:15 +00003086 // Keep track of whether every enum element has type int (very commmon).
3087 if (AllElementsInt)
3088 AllElementsInt = ECD->getType() == Context.IntTy;
3089
Reid Spencer5f016e22007-07-11 17:01:13 +00003090 ECD->setNextDeclarator(EltList);
3091 EltList = ECD;
3092 }
3093
Chris Lattnerac609682007-08-28 06:15:15 +00003094 // Figure out the type that should be used for this enum.
3095 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3096 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003097 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003098
3099 if (NumNegativeBits) {
3100 // If there is a negative value, figure out the smallest integer type (of
3101 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003102 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003103 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003104 BestWidth = IntWidth;
3105 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003106 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003107
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003108 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003109 BestType = Context.LongTy;
3110 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003111 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003112
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003113 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003114 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3115 BestType = Context.LongLongTy;
3116 }
3117 }
3118 } else {
3119 // If there is no negative value, figure out which of uint, ulong, ulonglong
3120 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003121 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003122 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003123 BestWidth = IntWidth;
3124 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003125 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003126 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003127 } else {
3128 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003129 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003130 "How could an initializer get larger than ULL?");
3131 BestType = Context.UnsignedLongLongTy;
3132 }
3133 }
3134
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003135 // Loop over all of the enumerator constants, changing their types to match
3136 // the type of the enum if needed.
3137 for (unsigned i = 0; i != NumElements; ++i) {
3138 EnumConstantDecl *ECD =
3139 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3140 if (!ECD) continue; // Already issued a diagnostic.
3141
3142 // Standard C says the enumerators have int type, but we allow, as an
3143 // extension, the enumerators to be larger than int size. If each
3144 // enumerator value fits in an int, type it as an int, otherwise type it the
3145 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3146 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003147 if (ECD->getType() == Context.IntTy) {
3148 // Make sure the init value is signed.
3149 llvm::APSInt IV = ECD->getInitVal();
3150 IV.setIsSigned(true);
3151 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003152 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003153 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003154
3155 // Determine whether the value fits into an int.
3156 llvm::APSInt InitVal = ECD->getInitVal();
3157 bool FitsInInt;
3158 if (InitVal.isUnsigned() || !InitVal.isNegative())
3159 FitsInInt = InitVal.getActiveBits() < IntWidth;
3160 else
3161 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3162
3163 // If it fits into an integer type, force it. Otherwise force it to match
3164 // the enum decl type.
3165 QualType NewTy;
3166 unsigned NewWidth;
3167 bool NewSign;
3168 if (FitsInInt) {
3169 NewTy = Context.IntTy;
3170 NewWidth = IntWidth;
3171 NewSign = true;
3172 } else if (ECD->getType() == BestType) {
3173 // Already the right type!
3174 continue;
3175 } else {
3176 NewTy = BestType;
3177 NewWidth = BestWidth;
3178 NewSign = BestType->isSignedIntegerType();
3179 }
3180
3181 // Adjust the APSInt value.
3182 InitVal.extOrTrunc(NewWidth);
3183 InitVal.setIsSigned(NewSign);
3184 ECD->setInitVal(InitVal);
3185
3186 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003187 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3188 /*isLvalue=*/false));
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003189 ECD->setType(NewTy);
3190 }
Chris Lattnerac609682007-08-28 06:15:15 +00003191
Chris Lattnere00b18c2007-08-28 18:24:31 +00003192 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003193 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003194}
3195
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003196Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3197 ExprTy *expr) {
3198 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3199
Chris Lattner8e25d862008-03-16 00:16:02 +00003200 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003201}
3202
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003203Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00003204 SourceLocation LBrace,
3205 SourceLocation RBrace,
3206 const char *Lang,
3207 unsigned StrSize,
3208 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003209 LinkageSpecDecl::LanguageIDs Language;
3210 Decl *dcl = static_cast<Decl *>(D);
3211 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3212 Language = LinkageSpecDecl::lang_c;
3213 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3214 Language = LinkageSpecDecl::lang_cxx;
3215 else {
3216 Diag(Loc, diag::err_bad_language);
3217 return 0;
3218 }
3219
3220 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00003221 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003222}
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003223
3224void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3225 ExprTy *alignment, SourceLocation PragmaLoc,
3226 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3227 Expr *Alignment = static_cast<Expr *>(alignment);
3228
3229 // If specified then alignment must be a "small" power of two.
3230 unsigned AlignmentVal = 0;
3231 if (Alignment) {
3232 llvm::APSInt Val;
3233 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3234 !Val.isPowerOf2() ||
3235 Val.getZExtValue() > 16) {
3236 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3237 delete Alignment;
3238 return; // Ignore
3239 }
3240
3241 AlignmentVal = (unsigned) Val.getZExtValue();
3242 }
3243
3244 switch (Kind) {
3245 case Action::PPK_Default: // pack([n])
3246 PackContext.setAlignment(AlignmentVal);
3247 break;
3248
3249 case Action::PPK_Show: // pack(show)
3250 // Show the current alignment, making sure to show the right value
3251 // for the default.
3252 AlignmentVal = PackContext.getAlignment();
3253 // FIXME: This should come from the target.
3254 if (AlignmentVal == 0)
3255 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003256 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003257 break;
3258
3259 case Action::PPK_Push: // pack(push [, id] [, [n])
3260 PackContext.push(Name);
3261 // Set the new alignment if specified.
3262 if (Alignment)
3263 PackContext.setAlignment(AlignmentVal);
3264 break;
3265
3266 case Action::PPK_Pop: // pack(pop [, id] [, n])
3267 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3268 // "#pragma pack(pop, identifier, n) is undefined"
3269 if (Alignment && Name)
3270 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3271
3272 // Do the pop.
3273 if (!PackContext.pop(Name)) {
3274 // If a name was specified then failure indicates the name
3275 // wasn't found. Otherwise failure indicates the stack was
3276 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003277 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3278 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003279
3280 // FIXME: Warn about popping named records as MSVC does.
3281 } else {
3282 // Pop succeeded, set the new alignment if specified.
3283 if (Alignment)
3284 PackContext.setAlignment(AlignmentVal);
3285 }
3286 break;
3287
3288 default:
3289 assert(0 && "Invalid #pragma pack kind.");
3290 }
3291}
3292
3293bool PragmaPackStack::pop(IdentifierInfo *Name) {
3294 if (Stack.empty())
3295 return false;
3296
3297 // If name is empty just pop top.
3298 if (!Name) {
3299 Alignment = Stack.back().first;
3300 Stack.pop_back();
3301 return true;
3302 }
3303
3304 // Otherwise, find the named record.
3305 for (unsigned i = Stack.size(); i != 0; ) {
3306 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003307 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003308 // Found it, pop up to and including this record.
3309 Alignment = Stack[i].first;
3310 Stack.erase(Stack.begin() + i, Stack.end());
3311 return true;
3312 }
3313 }
3314
3315 return false;
3316}