blob: 6c71d508953dcb1a387ba9499b47d6f5b34b5ea9 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6953a072008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-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 Lattner33aad6e2008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
Daniel Dunbar81c7d472008-10-14 05:35:18 +000028#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000031Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S,
32 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000033 DeclContext *DC = 0;
34 if (SS) {
35 if (SS->isInvalid())
36 return 0;
37 DC = static_cast<DeclContext*>(SS->getScopeRep());
38 }
39 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroff6384a012008-04-02 14:35:35 +000040
Douglas Gregor1d661552008-04-13 21:07:44 +000041 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
42 isa<ObjCInterfaceDecl>(IIDecl) ||
43 isa<TagDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000044 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000045 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000046}
47
Douglas Gregor3ef6c972008-11-07 20:08:42 +000048std::string Sema::getTypeAsString(TypeTy *Type) {
49 QualType Ty = QualType::getFromOpaquePtr(Type);
50 return Ty.getAsString();
51}
52
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000053DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000054 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000055 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000056 if (MD->isOutOfLineDefinition())
57 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000058
59 // A C++ inline method is parsed *after* the topmost class it was declared in
60 // is fully parsed (it's "complete").
61 // The parsing of a C++ inline method happens at the declaration context of
62 // the topmost (non-nested) class it is declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000063 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
64 DC = MD->getParent();
65 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
66 DC = RD;
67
68 // Return the declaration context of the topmost class the inline method is
69 // declared in.
70 return DC;
71 }
72
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000073 if (isa<ObjCMethodDecl>(DC))
74 return Context.getTranslationUnitDecl();
75
76 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
77 return SD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000078
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000079 return DC->getParent();
80}
81
Chris Lattneref87a202008-04-22 18:39:57 +000082void Sema::PushDeclContext(DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000083 assert(getContainingDC(DC) == CurContext &&
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000084 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000085 CurContext = DC;
Chris Lattnereee57c02008-04-04 06:12:32 +000086}
87
Chris Lattnerf3874bc2008-04-06 04:47:34 +000088void Sema::PopDeclContext() {
89 assert(CurContext && "DeclContext imbalance!");
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000090 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +000091}
92
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000093/// Add this decl to the scope shadowed decl chains.
94void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000095 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000096
97 // C++ [basic.scope]p4:
98 // -- exactly one declaration shall declare a class name or
99 // enumeration name that is not a typedef name and the other
100 // declarations shall all refer to the same object or
101 // enumerator, or all refer to functions and function templates;
102 // in this case the class name or enumeration name is hidden.
103 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
104 // We are pushing the name of a tag (enum or class).
Argiris Kirtzidis94805232008-07-17 17:49:50 +0000105 IdentifierResolver::iterator
106 I = IdResolver.begin(TD->getIdentifier(),
107 TD->getDeclContext(), false/*LookInParentCtx*/);
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000108 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000109 // There is already a declaration with the same name in the same
110 // scope. It must be found before we find the new declaration,
111 // so swap the order on the shadowed declaration chain.
112
Argiris Kirtzidis94805232008-07-17 17:49:50 +0000113 IdResolver.AddShadowedDecl(TD, *I);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000114 return;
115 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000116 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
117 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000118 // We are pushing the name of a function, which might be an
119 // overloaded name.
120 IdentifierResolver::iterator
121 I = IdResolver.begin(FD->getIdentifier(),
122 FD->getDeclContext(), false/*LookInParentCtx*/);
123 if (I != IdResolver.end() &&
124 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
125 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
126 // There is already a declaration with the same name in the same
127 // scope. It must be a function or an overloaded function.
128 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
129 if (!Ovl) {
130 // We haven't yet overloaded this function. Take the existing
131 // FunctionDecl and put it into an OverloadedFunctionDecl.
132 Ovl = OverloadedFunctionDecl::Create(Context,
133 FD->getDeclContext(),
134 FD->getIdentifier());
135 Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
136
137 // Remove the name binding to the existing FunctionDecl...
138 IdResolver.RemoveDecl(*I);
139
140 // ... and put the OverloadedFunctionDecl in its place.
141 IdResolver.AddDecl(Ovl);
142 }
143
144 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
145 // to its list of overloads.
146 Ovl->addOverload(FD);
147
148 return;
149 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000150 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000151
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000152 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000153}
154
Steve Naroff9637a9b2007-10-09 22:01:59 +0000155void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000156 if (S->decl_empty()) return;
157 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000158
Chris Lattner4b009652007-07-25 00:24:17 +0000159 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
160 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000161 Decl *TmpD = static_cast<Decl*>(*I);
162 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000163
164 if (isa<CXXFieldDecl>(TmpD)) continue;
165
166 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
167 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000168
Chris Lattner4b009652007-07-25 00:24:17 +0000169 IdentifierInfo *II = D->getIdentifier();
170 if (!II) continue;
171
Ted Kremenek40e70e72008-09-03 18:03:35 +0000172 // We only want to remove the decls from the identifier decl chains for
173 // local scopes, when inside a function/method.
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000174 if (S->getFnParent() != 0)
175 IdResolver.RemoveDecl(D);
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000176
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000177 // Chain this decl to the containing DeclContext.
178 D->setNext(CurContext->getDeclChain());
179 CurContext->setDeclChain(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000180 }
181}
182
Steve Naroffe57c21a2008-04-01 23:04:06 +0000183/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
184/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000185ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000186 // The third "scope" argument is 0 since we aren't enabling lazy built-in
187 // creation from this context.
188 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000189
Steve Naroff6384a012008-04-02 14:35:35 +0000190 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000191}
192
Steve Naroffe57c21a2008-04-01 23:04:06 +0000193/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000194/// namespace.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000195Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI, Scope *S,
196 DeclContext *LookupCtx, bool enableLazyBuiltinCreation) {
Chris Lattner4b009652007-07-25 00:24:17 +0000197 if (II == 0) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000198 unsigned NS = NSI;
199 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
200 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000201
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000202 IdentifierResolver::iterator
203 I = LookupCtx ? IdResolver.begin(II, LookupCtx, false/*LookInParentCtx*/) :
204 IdResolver.begin(II, CurContext, true/*LookInParentCtx*/);
Chris Lattner4b009652007-07-25 00:24:17 +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.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000208 for (; I != IdResolver.end(); ++I)
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000209 if ((*I)->getIdentifierNamespace() & NS)
210 return *I;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000211
Chris Lattner4b009652007-07-25 00:24:17 +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 Gregor1d661552008-04-13 21:07:44 +0000215 if (NS & Decl::IDNS_Ordinary) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000216 if (enableLazyBuiltinCreation &&
217 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroff6384a012008-04-02 14:35:35 +0000218 // If this is a builtin on this (or all) targets, create the decl.
219 if (unsigned BuiltinID = II->getBuiltinID())
220 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
221 }
Steve Naroffe57c21a2008-04-01 23:04:06 +0000222 if (getLangOptions().ObjC1) {
223 // @interface and @compatibility_alias introduce typedef-like names.
224 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000225 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000226 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000227 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
228 if (IDI != ObjCInterfaceDecls.end())
229 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000230 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
231 if (I != ObjCAliasDecls.end())
232 return I->second->getClassInterface();
233 }
Chris Lattner4b009652007-07-25 00:24:17 +0000234 }
235 return 0;
236}
237
Chris Lattnera9c87f22008-05-05 22:18:14 +0000238void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000239 if (!Context.getBuiltinVaListType().isNull())
240 return;
241
242 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000243 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000244 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000245 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
246}
247
Chris Lattner4b009652007-07-25 00:24:17 +0000248/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
249/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000250ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
251 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000252 Builtin::ID BID = (Builtin::ID)bid;
253
Chris Lattnerb23469f2008-09-28 05:54:29 +0000254 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000255 InitBuiltinVaListType();
256
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000257 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000258 FunctionDecl *New = FunctionDecl::Create(Context,
259 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000260 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000261 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000262
Chris Lattnera9c87f22008-05-05 22:18:14 +0000263 // Create Decl objects for each parameter, adding them to the
264 // FunctionDecl.
265 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
266 llvm::SmallVector<ParmVarDecl*, 16> Params;
267 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
268 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
269 FT->getArgType(i), VarDecl::None, 0,
270 0));
271 New->setParams(&Params[0], Params.size());
272 }
273
274
275
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000276 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000277 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000278 return New;
279}
280
281/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
282/// and scope as a previous declaration 'Old'. Figure out how to resolve this
283/// situation, merging decls or emitting diagnostics as appropriate.
284///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000285TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff453a8782008-09-09 14:32:20 +0000286 // Allow multiple definitions for ObjC built-in typedefs.
287 // FIXME: Verify the underlying types are equivalent!
288 if (getLangOptions().ObjC1) {
289 const IdentifierInfo *typeIdent = New->getIdentifier();
290 if (typeIdent == Ident_id) {
291 Context.setObjCIdType(New);
292 return New;
293 } else if (typeIdent == Ident_Class) {
294 Context.setObjCClassType(New);
295 return New;
296 } else if (typeIdent == Ident_SEL) {
297 Context.setObjCSelType(New);
298 return New;
299 } else if (typeIdent == Ident_Protocol) {
300 Context.setObjCProtoType(New->getUnderlyingType());
301 return New;
302 }
303 // Fall through - the typedef name was not a builtin type.
304 }
Chris Lattner4b009652007-07-25 00:24:17 +0000305 // Verify the old decl was also a typedef.
306 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
307 if (!Old) {
308 Diag(New->getLocation(), diag::err_redefinition_different_kind,
309 New->getName());
310 Diag(OldD->getLocation(), diag::err_previous_definition);
311 return New;
312 }
313
Chris Lattnerbef8d622008-07-25 18:44:27 +0000314 // If the typedef types are not identical, reject them in all languages and
315 // with any extensions enabled.
316 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
317 Context.getCanonicalType(Old->getUnderlyingType()) !=
318 Context.getCanonicalType(New->getUnderlyingType())) {
319 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
320 New->getUnderlyingType().getAsString(),
321 Old->getUnderlyingType().getAsString());
322 Diag(Old->getLocation(), diag::err_previous_definition);
323 return Old;
324 }
325
Eli Friedman324d5032008-06-11 06:20:39 +0000326 if (getLangOptions().Microsoft) return New;
327
Steve Naroffa9eae582008-01-30 23:46:05 +0000328 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
329 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
330 // *either* declaration is in a system header. The code below implements
331 // this adhoc compatibility rule. FIXME: The following code will not
332 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000333 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
334 SourceManager &SrcMgr = Context.getSourceManager();
335 if (SrcMgr.isInSystemHeader(Old->getLocation()))
336 return New;
337 if (SrcMgr.isInSystemHeader(New->getLocation()))
338 return New;
339 }
Eli Friedman324d5032008-06-11 06:20:39 +0000340
Ted Kremenek64845ce2008-05-23 21:28:18 +0000341 Diag(New->getLocation(), diag::err_redefinition, New->getName());
342 Diag(Old->getLocation(), diag::err_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000343 return New;
344}
345
Chris Lattner6953a072008-06-26 18:38:35 +0000346/// DeclhasAttr - returns true if decl Declaration already has the target
347/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000348static bool DeclHasAttr(const Decl *decl, const Attr *target) {
349 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
350 if (attr->getKind() == target->getKind())
351 return true;
352
353 return false;
354}
355
356/// MergeAttributes - append attributes from the Old decl to the New one.
357static void MergeAttributes(Decl *New, Decl *Old) {
358 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
359
Chris Lattner402b3372008-03-03 03:28:21 +0000360 while (attr) {
361 tmp = attr;
362 attr = attr->getNext();
363
364 if (!DeclHasAttr(New, tmp)) {
365 New->addAttr(tmp);
366 } else {
367 tmp->setNext(0);
368 delete(tmp);
369 }
370 }
Nuno Lopes77654342008-06-01 22:53:53 +0000371
372 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000373}
374
Chris Lattner3e254fb2008-04-08 04:40:51 +0000375/// MergeFunctionDecl - We just parsed a function 'New' from
376/// declarator D which has the same name and scope as a previous
377/// declaration 'Old'. Figure out how to resolve this situation,
378/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000379/// Redeclaration will be set true if this New is a redeclaration OldD.
380///
381/// In C++, New and Old must be declarations that are not
382/// overloaded. Use IsOverload to determine whether New and Old are
383/// overloaded, and to select the Old declaration that New should be
384/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000385FunctionDecl *
386Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000387 assert(!isa<OverloadedFunctionDecl>(OldD) &&
388 "Cannot merge with an overloaded function declaration");
389
Douglas Gregor42214c52008-04-21 02:02:58 +0000390 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000391 // Verify the old decl was also a function.
392 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
393 if (!Old) {
394 Diag(New->getLocation(), diag::err_redefinition_different_kind,
395 New->getName());
396 Diag(OldD->getLocation(), diag::err_previous_definition);
397 return New;
398 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000399
400 // Determine whether the previous declaration was a definition,
401 // implicit declaration, or a declaration.
402 diag::kind PrevDiag;
403 if (Old->isThisDeclarationADefinition())
404 PrevDiag = diag::err_previous_definition;
405 else if (Old->isImplicit())
406 PrevDiag = diag::err_previous_implicit_declaration;
407 else
408 PrevDiag = diag::err_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000409
Chris Lattner42a21742008-04-06 23:10:54 +0000410 QualType OldQType = Context.getCanonicalType(Old->getType());
411 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000412
Douglas Gregord2baafd2008-10-21 16:13:35 +0000413 if (getLangOptions().CPlusPlus) {
414 // (C++98 13.1p2):
415 // Certain function declarations cannot be overloaded:
416 // -- Function declarations that differ only in the return type
417 // cannot be overloaded.
418 QualType OldReturnType
419 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
420 QualType NewReturnType
421 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
422 if (OldReturnType != NewReturnType) {
423 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
424 Diag(Old->getLocation(), PrevDiag);
425 return New;
426 }
427
428 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
429 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
430 if (OldMethod && NewMethod) {
431 // -- Member function declarations with the same name and the
432 // same parameter types cannot be overloaded if any of them
433 // is a static member function declaration.
434 if (OldMethod->isStatic() || NewMethod->isStatic()) {
435 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
436 Diag(Old->getLocation(), PrevDiag);
437 return New;
438 }
439 }
440
441 // (C++98 8.3.5p3):
442 // All declarations for a function shall agree exactly in both the
443 // return type and the parameter-type-list.
444 if (OldQType == NewQType) {
445 // We have a redeclaration.
446 MergeAttributes(New, Old);
447 Redeclaration = true;
448 return MergeCXXFunctionDecl(New, Old);
449 }
450
451 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000452 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000453
454 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000455 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000456 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000457 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000458 MergeAttributes(New, Old);
459 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000460 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000461 }
Chris Lattner1470b072007-11-06 06:07:26 +0000462
Steve Naroff6c9e7922008-01-16 15:01:34 +0000463 // A function that has already been declared has been redeclared or defined
464 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000465
Chris Lattner4b009652007-07-25 00:24:17 +0000466 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
467 // TODO: This is totally simplistic. It should handle merging functions
468 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000469 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
470 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000471 return New;
472}
473
Steve Naroffb5e78152008-08-08 17:50:35 +0000474/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000475static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000476 if (VD->isFileVarDecl())
477 return (!VD->getInit() &&
478 (VD->getStorageClass() == VarDecl::None ||
479 VD->getStorageClass() == VarDecl::Static));
480 return false;
481}
482
483/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
484/// when dealing with C "tentative" external object definitions (C99 6.9.2).
485void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
486 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000487 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000488
489 for (IdentifierResolver::iterator
490 I = IdResolver.begin(VD->getIdentifier(),
491 VD->getDeclContext(), false/*LookInParentCtx*/),
492 E = IdResolver.end(); I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000493 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000494 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
495
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000496 // Handle the following case:
497 // int a[10];
498 // int a[]; - the code below makes sure we set the correct type.
499 // int a[11]; - this is an error, size isn't 10.
500 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
501 OldDecl->getType()->isConstantArrayType())
502 VD->setType(OldDecl->getType());
503
Steve Naroffb5e78152008-08-08 17:50:35 +0000504 // Check for "tentative" definitions. We can't accomplish this in
505 // MergeVarDecl since the initializer hasn't been attached.
506 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
507 continue;
508
509 // Handle __private_extern__ just like extern.
510 if (OldDecl->getStorageClass() != VarDecl::Extern &&
511 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
512 VD->getStorageClass() != VarDecl::Extern &&
513 VD->getStorageClass() != VarDecl::PrivateExtern) {
514 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
515 Diag(OldDecl->getLocation(), diag::err_previous_definition);
516 }
517 }
518 }
519}
520
Chris Lattner4b009652007-07-25 00:24:17 +0000521/// MergeVarDecl - We just parsed a variable 'New' which has the same name
522/// and scope as a previous declaration 'Old'. Figure out how to resolve this
523/// situation, merging decls or emitting diagnostics as appropriate.
524///
Steve Naroffb5e78152008-08-08 17:50:35 +0000525/// Tentative definition rules (C99 6.9.2p2) are checked by
526/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
527/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000528///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000529VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000530 // Verify the old decl was also a variable.
531 VarDecl *Old = dyn_cast<VarDecl>(OldD);
532 if (!Old) {
533 Diag(New->getLocation(), diag::err_redefinition_different_kind,
534 New->getName());
535 Diag(OldD->getLocation(), diag::err_previous_definition);
536 return New;
537 }
Chris Lattner402b3372008-03-03 03:28:21 +0000538
539 MergeAttributes(New, Old);
540
Chris Lattner4b009652007-07-25 00:24:17 +0000541 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000542 QualType OldCType = Context.getCanonicalType(Old->getType());
543 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000544 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000545 Diag(New->getLocation(), diag::err_redefinition, New->getName());
546 Diag(Old->getLocation(), diag::err_previous_definition);
547 return New;
548 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000549 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
550 if (New->getStorageClass() == VarDecl::Static &&
551 (Old->getStorageClass() == VarDecl::None ||
552 Old->getStorageClass() == VarDecl::Extern)) {
553 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
554 Diag(Old->getLocation(), diag::err_previous_definition);
555 return New;
556 }
557 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
558 if (New->getStorageClass() != VarDecl::Static &&
559 Old->getStorageClass() == VarDecl::Static) {
560 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
561 Diag(Old->getLocation(), diag::err_previous_definition);
562 return New;
563 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000564 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
565 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000566 Diag(New->getLocation(), diag::err_redefinition, New->getName());
567 Diag(Old->getLocation(), diag::err_previous_definition);
568 }
569 return New;
570}
571
Chris Lattner3e254fb2008-04-08 04:40:51 +0000572/// CheckParmsForFunctionDef - Check that the parameters of the given
573/// function are appropriate for the definition of a function. This
574/// takes care of any checks that cannot be performed on the
575/// declaration itself, e.g., that the types of each of the function
576/// parameters are complete.
577bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
578 bool HasInvalidParm = false;
579 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
580 ParmVarDecl *Param = FD->getParamDecl(p);
581
582 // C99 6.7.5.3p4: the parameters in a parameter type list in a
583 // function declarator that is part of a function definition of
584 // that function shall not have incomplete type.
585 if (Param->getType()->isIncompleteType() &&
586 !Param->isInvalidDecl()) {
587 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
588 Param->getType().getAsString());
589 Param->setInvalidDecl();
590 HasInvalidParm = true;
591 }
592 }
593
594 return HasInvalidParm;
595}
596
Chris Lattner4b009652007-07-25 00:24:17 +0000597/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
598/// no declarator (e.g. "struct foo;") is parsed.
599Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
600 // TODO: emit error on 'int;' or 'const enum foo;'.
601 // TODO: emit error on 'typedef int;'
602 // if (!DS.isMissingDeclaratorOk()) Diag(...);
603
Steve Naroffedafc0b2007-11-17 21:37:36 +0000604 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000605}
606
Steve Narofff0b23542008-01-10 22:15:12 +0000607bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000608 // Get the type before calling CheckSingleAssignmentConstraints(), since
609 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000610 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000611
Chris Lattner005ed752008-01-04 18:04:52 +0000612 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
613 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
614 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000615}
616
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000617bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000618 const ArrayType *AT = Context.getAsArrayType(DeclT);
619
620 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000621 // C99 6.7.8p14. We have an array of character type with unknown size
622 // being initialized to a string literal.
623 llvm::APSInt ConstVal(32);
624 ConstVal = strLiteral->getByteLength() + 1;
625 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000626 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000627 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000628 } else {
629 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000630 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000631 // FIXME: Avoid truncation for 64-bit length strings.
632 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000633 Diag(strLiteral->getSourceRange().getBegin(),
634 diag::warn_initializer_string_for_char_array_too_long,
635 strLiteral->getSourceRange());
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000636 }
637 // Set type from "char *" to "constant array of char".
638 strLiteral->setType(DeclT);
639 // For now, we always return false (meaning success).
640 return false;
641}
642
643StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000644 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000645 if (AT && AT->getElementType()->isCharType()) {
646 return dyn_cast<StringLiteral>(Init);
647 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000648 return 0;
649}
650
Douglas Gregor6428e762008-11-05 15:29:30 +0000651bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
652 SourceLocation InitLoc,
653 std::string InitEntity) {
Douglas Gregor81c29152008-10-29 00:13:59 +0000654 // C++ [dcl.init.ref]p1:
655 // A variable declared to be a T&, that is “reference to type T”
656 // (8.3.2), shall be initialized by an object, or function, of
657 // type T or by an object that can be converted into a T.
658 if (DeclType->isReferenceType())
659 return CheckReferenceInit(Init, DeclType);
660
Steve Naroff8e9337f2008-01-21 23:53:58 +0000661 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
662 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +0000663 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Douglas Gregor6428e762008-11-05 15:29:30 +0000664 return Diag(InitLoc,
Steve Naroff8e9337f2008-01-21 23:53:58 +0000665 diag::err_variable_object_no_init,
666 VAT->getSizeExpr()->getSourceRange());
667
Steve Naroffcb69fb72007-12-10 22:44:33 +0000668 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
669 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000670 // FIXME: Handle wide strings
671 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
672 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000673
Douglas Gregor6428e762008-11-05 15:29:30 +0000674 // C++ [dcl.init]p14:
675 // -- If the destination type is a (possibly cv-qualified) class
676 // type:
677 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
678 QualType DeclTypeC = Context.getCanonicalType(DeclType);
679 QualType InitTypeC = Context.getCanonicalType(Init->getType());
680
681 // -- If the initialization is direct-initialization, or if it is
682 // copy-initialization where the cv-unqualified version of the
683 // source type is the same class as, or a derived class of, the
684 // class of the destination, constructors are considered.
685 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
686 IsDerivedFrom(InitTypeC, DeclTypeC)) {
687 CXXConstructorDecl *Constructor
688 = PerformInitializationByConstructor(DeclType, &Init, 1,
689 InitLoc, Init->getSourceRange(),
690 InitEntity, IK_Copy);
691 return Constructor == 0;
692 }
693
694 // -- Otherwise (i.e., for the remaining copy-initialization
695 // cases), user-defined conversion sequences that can
696 // convert from the source type to the destination type or
697 // (when a conversion function is used) to a derived class
698 // thereof are enumerated as described in 13.3.1.4, and the
699 // best one is chosen through overload resolution
700 // (13.3). If the conversion cannot be done or is
701 // ambiguous, the initialization is ill-formed. The
702 // function selected is called with the initializer
703 // expression as its argument; if the function is a
704 // constructor, the call initializes a temporary of the
705 // destination type.
706 // FIXME: We're pretending to do copy elision here; return to
707 // this when we have ASTs for such things.
708 if (PerformImplicitConversion(Init, DeclType))
709 return Diag(InitLoc,
710 diag::err_typecheck_convert_incompatible,
711 DeclType.getAsString(), InitEntity,
712 "initializing",
713 Init->getSourceRange());
714 else
715 return false;
716 }
717
Steve Naroffb2f72412008-09-29 20:07:05 +0000718 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +0000719 if (DeclType->isArrayType())
720 return Diag(Init->getLocStart(),
721 diag::err_array_init_list_required,
722 Init->getSourceRange());
723
Steve Narofff0b23542008-01-10 22:15:12 +0000724 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor15e04622008-11-05 16:20:31 +0000725 } else if (getLangOptions().CPlusPlus) {
726 // C++ [dcl.init]p14:
727 // [...] If the class is an aggregate (8.5.1), and the initializer
728 // is a brace-enclosed list, see 8.5.1.
729 //
730 // Note: 8.5.1 is handled below; here, we diagnose the case where
731 // we have an initializer list and a destination type that is not
732 // an aggregate.
733 // FIXME: In C++0x, this is yet another form of initialization.
734 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
735 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
736 if (!ClassDecl->isAggregate())
737 return Diag(InitLoc,
738 diag::err_init_non_aggr_init_list,
739 DeclType.getAsString(),
740 Init->getSourceRange());
741 }
Steve Naroffcb69fb72007-12-10 22:44:33 +0000742 }
Eli Friedman38b7a912008-06-06 19:40:52 +0000743
Steve Naroffc4d4a482008-05-01 22:18:59 +0000744 InitListChecker CheckInitList(this, InitList, DeclType);
745 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +0000746}
747
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000748Sema::DeclTy *
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000749Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000750 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000751 IdentifierInfo *II = D.getIdentifier();
752
753 // All of these full declarators require an identifier. If it doesn't have
754 // one, the ParsedFreeStandingDeclSpec action should be used.
755 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000756 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000757 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000758 D.getDeclSpec().getSourceRange(), D.getSourceRange());
759 return 0;
760 }
761
Chris Lattnera7549902007-08-26 06:24:45 +0000762 // The scope passed in may not be a decl scope. Zip up the scope tree until
763 // we find one that is.
764 while ((S->getFlags() & Scope::DeclScope) == 0)
765 S = S->getParent();
766
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000767 DeclContext *DC;
768 Decl *PrevDecl;
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000769 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000770 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000771
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000772 // See if this is a redefinition of a variable in the same scope.
773 if (!D.getCXXScopeSpec().isSet()) {
774 DC = CurContext;
775 PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
776 } else { // Something like "int foo::x;"
777 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
778 PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S, DC);
779
780 // C++ 7.3.1.2p2:
781 // Members (including explicit specializations of templates) of a named
782 // namespace can also be defined outside that namespace by explicit
783 // qualification of the name being defined, provided that the entity being
784 // defined was already declared in the namespace and the definition appears
785 // after the point of declaration in a namespace that encloses the
786 // declarations namespace.
787 //
788 if (PrevDecl == 0) {
789 // No previous declaration in the qualifying scope.
790 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member,
791 II->getName(), D.getCXXScopeSpec().getRange());
792 } else if (!CurContext->Encloses(DC)) {
793 // The qualifying scope doesn't enclose the original declaration.
794 // Emit diagnostic based on current scope.
795 SourceLocation L = D.getIdentifierLoc();
796 SourceRange R = D.getCXXScopeSpec().getRange();
797 if (isa<FunctionDecl>(CurContext)) {
798 Diag(L, diag::err_invalid_declarator_in_function, II->getName(), R);
799 } else {
800 Diag(L, diag::err_invalid_declarator_scope, II->getName(),
801 cast<NamedDecl>(DC)->getName(), R);
802 }
803 }
804 }
805
Douglas Gregor1d661552008-04-13 21:07:44 +0000806 // In C++, the previous declaration we find might be a tag type
807 // (class or enum). In this case, the new declaration will hide the
808 // tag type.
809 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
810 PrevDecl = 0;
811
Chris Lattner82bb4792007-11-14 06:34:38 +0000812 QualType R = GetTypeForDeclarator(D, S);
813 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
814
Chris Lattner4b009652007-07-25 00:24:17 +0000815 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000816 // Check that there are no default arguments (C++ only).
817 if (getLangOptions().CPlusPlus)
818 CheckExtraCXXDefaultArguments(D);
819
Chris Lattner82bb4792007-11-14 06:34:38 +0000820 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000821 if (!NewTD) return 0;
822
823 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000824 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +0000825 // Merge the decl with the existing one if appropriate. If the decl is
826 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000827 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000828 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
829 if (NewTD == 0) return 0;
830 }
831 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000832 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000833 // C99 6.7.7p2: If a typedef name specifies a variably modified type
834 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000835 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
836 // FIXME: Diagnostic needs to be fixed.
837 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000838 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000839 }
840 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000841 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000842 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000843 switch (D.getDeclSpec().getStorageClassSpec()) {
844 default: assert(0 && "Unknown storage class!");
845 case DeclSpec::SCS_auto:
846 case DeclSpec::SCS_register:
847 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
848 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000849 InvalidDecl = true;
850 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000851 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
852 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
853 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000854 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000855 }
856
Chris Lattner4c7802b2008-03-15 21:24:04 +0000857 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000858 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000859 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
860
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000861 FunctionDecl *NewFD;
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000862 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000863 // This is a C++ constructor declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000864 assert(DC->isCXXRecord() &&
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000865 "Constructors can only be declared in a member context");
866
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000867 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000868
869 // Create the new declaration
870 NewFD = CXXConstructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000871 cast<CXXRecordDecl>(DC),
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000872 D.getIdentifierLoc(), II, R,
873 isExplicit, isInline,
874 /*isImplicitlyDeclared=*/false);
875
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000876 if (isInvalidDecl)
877 NewFD->setInvalidDecl();
878 } else if (D.getKind() == Declarator::DK_Destructor) {
879 // This is a C++ destructor declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000880 if (DC->isCXXRecord()) {
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000881 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000882
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000883 NewFD = CXXDestructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000884 cast<CXXRecordDecl>(DC),
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000885 D.getIdentifierLoc(), II, R,
886 isInline,
887 /*isImplicitlyDeclared=*/false);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000888
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000889 if (isInvalidDecl)
890 NewFD->setInvalidDecl();
891 } else {
892 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
893 // Create a FunctionDecl to satisfy the function definition parsing
894 // code path.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000895 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000896 II, R, SC, isInline, LastDeclarator,
897 // FIXME: Move to DeclGroup...
898 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000899 NewFD->setInvalidDecl();
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000900 }
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000901 } else if (D.getKind() == Declarator::DK_Conversion) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000902 if (!DC->isCXXRecord()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000903 Diag(D.getIdentifierLoc(),
904 diag::err_conv_function_not_member);
905 return 0;
906 } else {
907 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
908
909 NewFD = CXXConversionDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000910 cast<CXXRecordDecl>(DC),
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000911 D.getIdentifierLoc(), II, R,
912 isInline, isExplicit);
913
914 if (isInvalidDecl)
915 NewFD->setInvalidDecl();
916 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000917 } else if (DC->isCXXRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000918 // This is a C++ method declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000919 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000920 D.getIdentifierLoc(), II, R,
921 (SC == FunctionDecl::Static), isInline,
922 LastDeclarator);
923 } else {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000924 NewFD = FunctionDecl::Create(Context, DC,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000925 D.getIdentifierLoc(),
Steve Naroff71cd7762008-10-03 00:02:03 +0000926 II, R, SC, isInline, LastDeclarator,
927 // FIXME: Move to DeclGroup...
928 D.getDeclSpec().getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000929 }
Ted Kremenek117f1862008-02-27 22:18:07 +0000930 // Handle attributes.
Chris Lattner9b384ca2008-06-29 00:02:00 +0000931 ProcessDeclAttributes(NewFD, D);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000932
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000933 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000934 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000935 // The parser guarantees this is a string.
936 StringLiteral *SE = cast<StringLiteral>(E);
937 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
938 SE->getByteLength())));
939 }
940
Chris Lattner3e254fb2008-04-08 04:40:51 +0000941 // Copy the parameter declarations from the declarator D to
942 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +0000943 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000944 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
945
946 // Create Decl objects for each parameter, adding them to the
947 // FunctionDecl.
948 llvm::SmallVector<ParmVarDecl*, 16> Params;
949
950 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
951 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000952 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +0000953 // We let through "const void" here because Sema::GetTypeForDeclarator
954 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000955 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
956 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +0000957 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
958 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000959 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
960
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000961 // In C++, the empty parameter-type-list must be spelled "void"; a
962 // typedef of void is not permitted.
963 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +0000964 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +0000965 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
966 }
Eli Friedman769e7302008-08-25 21:31:01 +0000967 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000968 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
969 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
970 }
971
972 NewFD->setParams(&Params[0], Params.size());
Douglas Gregorba3e8b72008-10-24 18:09:54 +0000973 } else if (R->getAsTypedefType()) {
974 // When we're declaring a function with a typedef, as in the
975 // following example, we'll need to synthesize (unnamed)
976 // parameters for use in the declaration.
977 //
978 // @code
979 // typedef void fn(int);
980 // fn f;
981 // @endcode
982 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
983 if (!FT) {
984 // This is a typedef of a function with no prototype, so we
985 // don't need to do anything.
986 } else if ((FT->getNumArgs() == 0) ||
987 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
988 FT->getArgType(0)->isVoidType())) {
989 // This is a zero-argument function. We don't need to do anything.
990 } else {
991 // Synthesize a parameter for each argument type.
992 llvm::SmallVector<ParmVarDecl*, 16> Params;
993 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
994 ArgType != FT->arg_type_end(); ++ArgType) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000995 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregorba3e8b72008-10-24 18:09:54 +0000996 SourceLocation(), 0,
997 *ArgType, VarDecl::None,
998 0, 0));
999 }
1000
1001 NewFD->setParams(&Params[0], Params.size());
1002 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001003 }
1004
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001005 // C++ constructors and destructors are handled by separate
1006 // routines, since they don't require any declaration merging (C++
1007 // [class.mfct]p2) and they aren't ever pushed into scope, because
1008 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1009 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1010 return ActOnConstructorDeclarator(Constructor);
1011 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1012 return ActOnDestructorDeclarator(Destructor);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001013 else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1014 return ActOnConversionDeclarator(Conversion);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001015
Douglas Gregore60e5d32008-11-06 22:13:31 +00001016 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1017 if (NewFD->isOverloadedOperator() &&
1018 CheckOverloadedOperatorDeclaration(NewFD))
1019 NewFD->setInvalidDecl();
1020
Steve Narofff8a09432008-01-09 23:34:55 +00001021 // Merge the decl with the existing one if appropriate. Since C functions
1022 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001023 if (PrevDecl &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001024 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregor42214c52008-04-21 02:02:58 +00001025 bool Redeclaration = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001026
1027 // If C++, determine whether NewFD is an overload of PrevDecl or
1028 // a declaration that requires merging. If it's an overload,
1029 // there's no more work to do here; we'll just add the new
1030 // function to the scope.
1031 OverloadedFunctionDecl::function_iterator MatchedDecl;
1032 if (!getLangOptions().CPlusPlus ||
1033 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1034 Decl *OldDecl = PrevDecl;
1035
1036 // If PrevDecl was an overloaded function, extract the
1037 // FunctionDecl that matched.
1038 if (isa<OverloadedFunctionDecl>(PrevDecl))
1039 OldDecl = *MatchedDecl;
1040
1041 // NewFD and PrevDecl represent declarations that need to be
1042 // merged.
1043 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1044
1045 if (NewFD == 0) return 0;
1046 if (Redeclaration) {
1047 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1048
1049 if (OldDecl == PrevDecl) {
1050 // Remove the name binding for the previous
1051 // declaration. We'll add the binding back later, but then
1052 // it will refer to the new declaration (which will
1053 // contain more information).
1054 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1055 } else {
1056 // We need to update the OverloadedFunctionDecl with the
1057 // latest declaration of this function, so that name
1058 // lookup will always refer to the latest declaration of
1059 // this function.
1060 *MatchedDecl = NewFD;
1061
1062 // Add the redeclaration to the current scope, since we'll
1063 // be skipping PushOnScopeChains.
1064 S->AddDecl(NewFD);
1065
1066 return NewFD;
1067 }
1068 }
Douglas Gregor42214c52008-04-21 02:02:58 +00001069 }
Chris Lattner4b009652007-07-25 00:24:17 +00001070 }
1071 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001072
1073 // In C++, check default arguments now that we have merged decls.
1074 if (getLangOptions().CPlusPlus)
1075 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +00001076 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001077 // Check that there are no default arguments (C++ only).
1078 if (getLangOptions().CPlusPlus)
1079 CheckExtraCXXDefaultArguments(D);
1080
Ted Kremenek42730c52008-01-07 19:49:32 +00001081 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001082 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
1083 D.getIdentifier()->getName());
1084 InvalidDecl = true;
1085 }
Chris Lattner4b009652007-07-25 00:24:17 +00001086
1087 VarDecl *NewVD;
1088 VarDecl::StorageClass SC;
1089 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +00001090 default: assert(0 && "Unknown storage class!");
1091 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1092 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1093 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1094 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1095 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1096 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001097 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001098 if (DC->isCXXRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001099 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1100 // This is a static data member for a C++ class.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001101 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001102 D.getIdentifierLoc(), II,
1103 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +00001104 } else {
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001105 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001106 if (S->getFnParent() == 0) {
1107 // C99 6.9p2: The storage-class specifiers auto and register shall not
1108 // appear in the declaration specifiers in an external declaration.
1109 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1110 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
1111 R.getAsString());
1112 InvalidDecl = true;
1113 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001114 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001115 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Steve Naroff71cd7762008-10-03 00:02:03 +00001116 II, R, SC, LastDeclarator,
1117 // FIXME: Move to DeclGroup...
1118 D.getDeclSpec().getSourceRange().getBegin());
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001119 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroffcae537d2007-08-28 18:45:29 +00001120 }
Chris Lattner4b009652007-07-25 00:24:17 +00001121 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +00001122 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +00001123
Daniel Dunbarced89142008-08-06 00:03:29 +00001124 // Handle GNU asm-label extension (encoded as an attribute).
1125 if (Expr *E = (Expr*) D.getAsmLabel()) {
1126 // The parser guarantees this is a string.
1127 StringLiteral *SE = cast<StringLiteral>(E);
1128 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1129 SE->getByteLength())));
1130 }
1131
Nate Begemanea583262008-03-14 18:07:10 +00001132 // Emit an error if an address space was applied to decl with local storage.
1133 // This includes arrays of objects with address space qualifiers, but not
1134 // automatic variables that point to other address spaces.
1135 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +00001136 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1137 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1138 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +00001139 }
Steve Narofff8a09432008-01-09 23:34:55 +00001140 // Merge the decl with the existing one if appropriate. If the decl is
1141 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001142 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001143 NewVD = MergeVarDecl(NewVD, PrevDecl);
1144 if (NewVD == 0) return 0;
1145 }
Chris Lattner4b009652007-07-25 00:24:17 +00001146 New = NewVD;
1147 }
1148
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001149 // Set the lexical context. If the declarator has a C++ scope specifier, the
1150 // lexical context will be different from the semantic context.
1151 New->setLexicalDeclContext(CurContext);
1152
Chris Lattner4b009652007-07-25 00:24:17 +00001153 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001154 if (II)
1155 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001156 // If any semantic error occurred, mark the decl as invalid.
1157 if (D.getInvalidType() || InvalidDecl)
1158 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001159
1160 return New;
1161}
1162
Steve Narofffc08f5e2008-10-27 11:34:16 +00001163void Sema::InitializerElementNotConstant(const Expr *Init) {
1164 Diag(Init->getExprLoc(),
1165 diag::err_init_element_not_constant, Init->getSourceRange());
1166}
1167
Eli Friedman02c22ce2008-05-20 13:48:25 +00001168bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1169 switch (Init->getStmtClass()) {
1170 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001171 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001172 return true;
1173 case Expr::ParenExprClass: {
1174 const ParenExpr* PE = cast<ParenExpr>(Init);
1175 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1176 }
1177 case Expr::CompoundLiteralExprClass:
1178 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1179 case Expr::DeclRefExprClass: {
1180 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001181 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1182 if (VD->hasGlobalStorage())
1183 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001184 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001185 return true;
1186 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001187 if (isa<FunctionDecl>(D))
1188 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001189 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001190 return true;
1191 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001192 case Expr::MemberExprClass: {
1193 const MemberExpr *M = cast<MemberExpr>(Init);
1194 if (M->isArrow())
1195 return CheckAddressConstantExpression(M->getBase());
1196 return CheckAddressConstantExpressionLValue(M->getBase());
1197 }
1198 case Expr::ArraySubscriptExprClass: {
1199 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1200 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1201 return CheckAddressConstantExpression(ASE->getBase()) ||
1202 CheckArithmeticConstantExpression(ASE->getIdx());
1203 }
1204 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001205 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001206 return false;
1207 case Expr::UnaryOperatorClass: {
1208 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1209
1210 // C99 6.6p9
1211 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001212 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001213
Steve Narofffc08f5e2008-10-27 11:34:16 +00001214 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001215 return true;
1216 }
1217 }
1218}
1219
1220bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1221 switch (Init->getStmtClass()) {
1222 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001223 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001224 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001225 case Expr::ParenExprClass:
1226 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001227 case Expr::StringLiteralClass:
1228 case Expr::ObjCStringLiteralClass:
1229 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001230 case Expr::CallExprClass:
1231 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1232 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1233 Builtin::BI__builtin___CFStringMakeConstantString)
1234 return false;
1235
Steve Narofffc08f5e2008-10-27 11:34:16 +00001236 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001237 return true;
1238
Eli Friedman02c22ce2008-05-20 13:48:25 +00001239 case Expr::UnaryOperatorClass: {
1240 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1241
1242 // C99 6.6p9
1243 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1244 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1245
1246 if (Exp->getOpcode() == UnaryOperator::Extension)
1247 return CheckAddressConstantExpression(Exp->getSubExpr());
1248
Steve Narofffc08f5e2008-10-27 11:34:16 +00001249 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001250 return true;
1251 }
1252 case Expr::BinaryOperatorClass: {
1253 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1254 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1255
1256 Expr *PExp = Exp->getLHS();
1257 Expr *IExp = Exp->getRHS();
1258 if (IExp->getType()->isPointerType())
1259 std::swap(PExp, IExp);
1260
1261 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1262 return CheckAddressConstantExpression(PExp) ||
1263 CheckArithmeticConstantExpression(IExp);
1264 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001265 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001266 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001267 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001268 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1269 // Check for implicit promotion
1270 if (SubExpr->getType()->isFunctionType() ||
1271 SubExpr->getType()->isArrayType())
1272 return CheckAddressConstantExpressionLValue(SubExpr);
1273 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001274
1275 // Check for pointer->pointer cast
1276 if (SubExpr->getType()->isPointerType())
1277 return CheckAddressConstantExpression(SubExpr);
1278
Eli Friedman1fad3c62008-08-25 20:46:57 +00001279 if (SubExpr->getType()->isIntegralType()) {
1280 // Check for the special-case of a pointer->int->pointer cast;
1281 // this isn't standard, but some code requires it. See
1282 // PR2720 for an example.
1283 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1284 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1285 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1286 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1287 if (IntWidth >= PointerWidth) {
1288 return CheckAddressConstantExpression(SubCast->getSubExpr());
1289 }
1290 }
1291 }
1292 }
1293 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001294 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001295 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001296
Steve Narofffc08f5e2008-10-27 11:34:16 +00001297 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001298 return true;
1299 }
1300 case Expr::ConditionalOperatorClass: {
1301 // FIXME: Should we pedwarn here?
1302 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1303 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001304 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001305 return true;
1306 }
1307 if (CheckArithmeticConstantExpression(Exp->getCond()))
1308 return true;
1309 if (Exp->getLHS() &&
1310 CheckAddressConstantExpression(Exp->getLHS()))
1311 return true;
1312 return CheckAddressConstantExpression(Exp->getRHS());
1313 }
1314 case Expr::AddrLabelExprClass:
1315 return false;
1316 }
1317}
1318
Eli Friedman998dffb2008-06-09 05:05:07 +00001319static const Expr* FindExpressionBaseAddress(const Expr* E);
1320
1321static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1322 switch (E->getStmtClass()) {
1323 default:
1324 return E;
1325 case Expr::ParenExprClass: {
1326 const ParenExpr* PE = cast<ParenExpr>(E);
1327 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1328 }
1329 case Expr::MemberExprClass: {
1330 const MemberExpr *M = cast<MemberExpr>(E);
1331 if (M->isArrow())
1332 return FindExpressionBaseAddress(M->getBase());
1333 return FindExpressionBaseAddressLValue(M->getBase());
1334 }
1335 case Expr::ArraySubscriptExprClass: {
1336 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1337 return FindExpressionBaseAddress(ASE->getBase());
1338 }
1339 case Expr::UnaryOperatorClass: {
1340 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1341
1342 if (Exp->getOpcode() == UnaryOperator::Deref)
1343 return FindExpressionBaseAddress(Exp->getSubExpr());
1344
1345 return E;
1346 }
1347 }
1348}
1349
1350static const Expr* FindExpressionBaseAddress(const Expr* E) {
1351 switch (E->getStmtClass()) {
1352 default:
1353 return E;
1354 case Expr::ParenExprClass: {
1355 const ParenExpr* PE = cast<ParenExpr>(E);
1356 return FindExpressionBaseAddress(PE->getSubExpr());
1357 }
1358 case Expr::UnaryOperatorClass: {
1359 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1360
1361 // C99 6.6p9
1362 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1363 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1364
1365 if (Exp->getOpcode() == UnaryOperator::Extension)
1366 return FindExpressionBaseAddress(Exp->getSubExpr());
1367
1368 return E;
1369 }
1370 case Expr::BinaryOperatorClass: {
1371 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1372
1373 Expr *PExp = Exp->getLHS();
1374 Expr *IExp = Exp->getRHS();
1375 if (IExp->getType()->isPointerType())
1376 std::swap(PExp, IExp);
1377
1378 return FindExpressionBaseAddress(PExp);
1379 }
1380 case Expr::ImplicitCastExprClass: {
1381 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1382
1383 // Check for implicit promotion
1384 if (SubExpr->getType()->isFunctionType() ||
1385 SubExpr->getType()->isArrayType())
1386 return FindExpressionBaseAddressLValue(SubExpr);
1387
1388 // Check for pointer->pointer cast
1389 if (SubExpr->getType()->isPointerType())
1390 return FindExpressionBaseAddress(SubExpr);
1391
1392 // We assume that we have an arithmetic expression here;
1393 // if we don't, we'll figure it out later
1394 return 0;
1395 }
Douglas Gregor035d0882008-10-28 15:36:24 +00001396 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001397 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1398
1399 // Check for pointer->pointer cast
1400 if (SubExpr->getType()->isPointerType())
1401 return FindExpressionBaseAddress(SubExpr);
1402
1403 // We assume that we have an arithmetic expression here;
1404 // if we don't, we'll figure it out later
1405 return 0;
1406 }
1407 }
1408}
1409
Eli Friedman02c22ce2008-05-20 13:48:25 +00001410bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1411 switch (Init->getStmtClass()) {
1412 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001413 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001414 return true;
1415 case Expr::ParenExprClass: {
1416 const ParenExpr* PE = cast<ParenExpr>(Init);
1417 return CheckArithmeticConstantExpression(PE->getSubExpr());
1418 }
1419 case Expr::FloatingLiteralClass:
1420 case Expr::IntegerLiteralClass:
1421 case Expr::CharacterLiteralClass:
1422 case Expr::ImaginaryLiteralClass:
1423 case Expr::TypesCompatibleExprClass:
1424 case Expr::CXXBoolLiteralExprClass:
1425 return false;
1426 case Expr::CallExprClass: {
1427 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001428
1429 // Allow any constant foldable calls to builtins.
1430 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001431 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001432
Steve Narofffc08f5e2008-10-27 11:34:16 +00001433 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001434 return true;
1435 }
1436 case Expr::DeclRefExprClass: {
1437 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1438 if (isa<EnumConstantDecl>(D))
1439 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001440 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001441 return true;
1442 }
1443 case Expr::CompoundLiteralExprClass:
1444 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1445 // but vectors are allowed to be magic.
1446 if (Init->getType()->isVectorType())
1447 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001448 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001449 return true;
1450 case Expr::UnaryOperatorClass: {
1451 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1452
1453 switch (Exp->getOpcode()) {
1454 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1455 // See C99 6.6p3.
1456 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001457 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001458 return true;
1459 case UnaryOperator::SizeOf:
1460 case UnaryOperator::AlignOf:
1461 case UnaryOperator::OffsetOf:
1462 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1463 // See C99 6.5.3.4p2 and 6.6p3.
1464 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1465 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001466 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001467 return true;
1468 case UnaryOperator::Extension:
1469 case UnaryOperator::LNot:
1470 case UnaryOperator::Plus:
1471 case UnaryOperator::Minus:
1472 case UnaryOperator::Not:
1473 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1474 }
1475 }
1476 case Expr::SizeOfAlignOfTypeExprClass: {
1477 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1478 // Special check for void types, which are allowed as an extension
1479 if (Exp->getArgumentType()->isVoidType())
1480 return false;
1481 // alignof always evaluates to a constant.
1482 // FIXME: is sizeof(int[3.0]) a constant expression?
1483 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001484 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001485 return true;
1486 }
1487 return false;
1488 }
1489 case Expr::BinaryOperatorClass: {
1490 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1491
1492 if (Exp->getLHS()->getType()->isArithmeticType() &&
1493 Exp->getRHS()->getType()->isArithmeticType()) {
1494 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1495 CheckArithmeticConstantExpression(Exp->getRHS());
1496 }
1497
Eli Friedman998dffb2008-06-09 05:05:07 +00001498 if (Exp->getLHS()->getType()->isPointerType() &&
1499 Exp->getRHS()->getType()->isPointerType()) {
1500 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1501 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1502
1503 // Only allow a null (constant integer) base; we could
1504 // allow some additional cases if necessary, but this
1505 // is sufficient to cover offsetof-like constructs.
1506 if (!LHSBase && !RHSBase) {
1507 return CheckAddressConstantExpression(Exp->getLHS()) ||
1508 CheckAddressConstantExpression(Exp->getRHS());
1509 }
1510 }
1511
Steve Narofffc08f5e2008-10-27 11:34:16 +00001512 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001513 return true;
1514 }
1515 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001516 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001517 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00001518 if (SubExpr->getType()->isArithmeticType())
1519 return CheckArithmeticConstantExpression(SubExpr);
1520
Eli Friedman266df142008-09-02 09:37:00 +00001521 if (SubExpr->getType()->isPointerType()) {
1522 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1523 // If the pointer has a null base, this is an offsetof-like construct
1524 if (!Base)
1525 return CheckAddressConstantExpression(SubExpr);
1526 }
1527
Steve Narofffc08f5e2008-10-27 11:34:16 +00001528 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00001529 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001530 }
1531 case Expr::ConditionalOperatorClass: {
1532 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00001533
1534 // If GNU extensions are disabled, we require all operands to be arithmetic
1535 // constant expressions.
1536 if (getLangOptions().NoExtensions) {
1537 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1538 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1539 CheckArithmeticConstantExpression(Exp->getRHS());
1540 }
1541
1542 // Otherwise, we have to emulate some of the behavior of fold here.
1543 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1544 // because it can constant fold things away. To retain compatibility with
1545 // GCC code, we see if we can fold the condition to a constant (which we
1546 // should always be able to do in theory). If so, we only require the
1547 // specified arm of the conditional to be a constant. This is a horrible
1548 // hack, but is require by real world code that uses __builtin_constant_p.
1549 APValue Val;
1550 if (!Exp->getCond()->tryEvaluate(Val, Context)) {
1551 // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression
1552 // won't be able to either. Use it to emit the diagnostic though.
1553 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
1554 assert(Res && "tryEvaluate couldn't evaluate this constant?");
1555 return Res;
1556 }
1557
1558 // Verify that the side following the condition is also a constant.
1559 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1560 if (Val.getInt() == 0)
1561 std::swap(TrueSide, FalseSide);
1562
1563 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001564 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00001565
1566 // Okay, the evaluated side evaluates to a constant, so we accept this.
1567 // Check to see if the other side is obviously not a constant. If so,
1568 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001569 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00001570 Diag(Init->getExprLoc(),
1571 diag::ext_typecheck_expression_not_constant_but_accepted,
1572 FalseSide->getSourceRange());
1573 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001574 }
1575 }
1576}
1577
1578bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopese7280452008-07-07 16:46:50 +00001579 Init = Init->IgnoreParens();
1580
Eli Friedman02c22ce2008-05-20 13:48:25 +00001581 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1582 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1583 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1584
Nuno Lopese7280452008-07-07 16:46:50 +00001585 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1586 return CheckForConstantInitializer(e->getInitializer(), DclT);
1587
Eli Friedman02c22ce2008-05-20 13:48:25 +00001588 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1589 unsigned numInits = Exp->getNumInits();
1590 for (unsigned i = 0; i < numInits; i++) {
1591 // FIXME: Need to get the type of the declaration for C++,
1592 // because it could be a reference?
1593 if (CheckForConstantInitializer(Exp->getInit(i),
1594 Exp->getInit(i)->getType()))
1595 return true;
1596 }
1597 return false;
1598 }
1599
1600 if (Init->isNullPointerConstant(Context))
1601 return false;
1602 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001603 QualType InitTy = Context.getCanonicalType(Init->getType())
1604 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00001605 if (InitTy == Context.BoolTy) {
1606 // Special handling for pointers implicitly cast to bool;
1607 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1608 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1609 Expr* SubE = ICE->getSubExpr();
1610 if (SubE->getType()->isPointerType() ||
1611 SubE->getType()->isArrayType() ||
1612 SubE->getType()->isFunctionType()) {
1613 return CheckAddressConstantExpression(Init);
1614 }
1615 }
1616 } else if (InitTy->isIntegralType()) {
1617 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001618 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00001619 SubE = CE->getSubExpr();
1620 // Special check for pointer cast to int; we allow as an extension
1621 // an address constant cast to an integer if the integer
1622 // is of an appropriate width (this sort of code is apparently used
1623 // in some places).
1624 // FIXME: Add pedwarn?
1625 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1626 if (SubE && (SubE->getType()->isPointerType() ||
1627 SubE->getType()->isArrayType() ||
1628 SubE->getType()->isFunctionType())) {
1629 unsigned IntWidth = Context.getTypeSize(Init->getType());
1630 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1631 if (IntWidth >= PointerWidth)
1632 return CheckAddressConstantExpression(Init);
1633 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001634 }
1635
1636 return CheckArithmeticConstantExpression(Init);
1637 }
1638
1639 if (Init->getType()->isPointerType())
1640 return CheckAddressConstantExpression(Init);
1641
Eli Friedman25086f02008-05-30 18:14:48 +00001642 // An array type at the top level that isn't an init-list must
1643 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001644 if (Init->getType()->isArrayType())
1645 return false;
1646
Nuno Lopes1dc26762008-09-01 18:42:41 +00001647 if (Init->getType()->isFunctionType())
1648 return false;
1649
Steve Naroffdff3fb22008-10-02 17:12:56 +00001650 // Allow block exprs at top level.
1651 if (Init->getType()->isBlockPointerType())
1652 return false;
1653
Steve Narofffc08f5e2008-10-27 11:34:16 +00001654 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001655 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001656}
1657
Steve Naroff6a0e2092007-09-12 14:07:44 +00001658void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001659 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001660 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001661 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001662
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001663 // If there is no declaration, there was an error parsing it. Just ignore
1664 // the initializer.
1665 if (RealDecl == 0) {
1666 delete Init;
1667 return;
1668 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001669
Steve Naroff420d0f52007-09-12 20:13:48 +00001670 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1671 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001672 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1673 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001674 RealDecl->setInvalidDecl();
1675 return;
1676 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001677 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001678 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001679 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001680 if (VDecl->isBlockVarDecl()) {
1681 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001682 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001683 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001684 VDecl->setInvalidDecl();
1685 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001686 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1687 VDecl->getName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001688 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00001689
1690 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1691 if (!getLangOptions().CPlusPlus) {
1692 if (SC == VarDecl::Static) // C99 6.7.8p4.
1693 CheckForConstantInitializer(Init, DclT);
1694 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001695 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001696 } else if (VDecl->isFileVarDecl()) {
1697 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001698 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001699 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00001700 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1701 VDecl->getName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001702 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001703
Anders Carlssonea7140a2008-08-22 05:00:02 +00001704 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1705 if (!getLangOptions().CPlusPlus) {
1706 // C99 6.7.8p4. All file scoped initializers need to be constant.
1707 CheckForConstantInitializer(Init, DclT);
1708 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001709 }
1710 // If the type changed, it means we had an incomplete type that was
1711 // completed by the initializer. For example:
1712 // int ary[] = { 1, 3, 5 };
1713 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001714 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001715 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001716 Init->setType(DclT);
1717 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001718
1719 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001720 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001721 return;
1722}
1723
Douglas Gregor81c29152008-10-29 00:13:59 +00001724void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1725 Decl *RealDecl = static_cast<Decl *>(dcl);
1726
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00001727 // If there is no declaration, there was an error parsing it. Just ignore it.
1728 if (RealDecl == 0)
1729 return;
1730
Douglas Gregor81c29152008-10-29 00:13:59 +00001731 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1732 QualType Type = Var->getType();
1733 // C++ [dcl.init.ref]p3:
1734 // The initializer can be omitted for a reference only in a
1735 // parameter declaration (8.3.5), in the declaration of a
1736 // function return type, in the declaration of a class member
1737 // within its class declaration (9.2), and where the extern
1738 // specifier is explicitly used.
Douglas Gregor5870a952008-11-03 20:45:27 +00001739 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001740 Diag(Var->getLocation(),
1741 diag::err_reference_var_requires_init,
1742 Var->getName(),
1743 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor5870a952008-11-03 20:45:27 +00001744 Var->setInvalidDecl();
1745 return;
1746 }
1747
1748 // C++ [dcl.init]p9:
1749 //
1750 // If no initializer is specified for an object, and the object
1751 // is of (possibly cv-qualified) non-POD class type (or array
1752 // thereof), the object shall be default-initialized; if the
1753 // object is of const-qualified type, the underlying class type
1754 // shall have a user-declared default constructor.
1755 if (getLangOptions().CPlusPlus) {
1756 QualType InitType = Type;
1757 if (const ArrayType *Array = Context.getAsArrayType(Type))
1758 InitType = Array->getElementType();
1759 if (InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001760 const CXXConstructorDecl *Constructor
1761 = PerformInitializationByConstructor(InitType, 0, 0,
1762 Var->getLocation(),
1763 SourceRange(Var->getLocation(),
1764 Var->getLocation()),
1765 Var->getName(),
1766 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00001767 if (!Constructor)
1768 Var->setInvalidDecl();
1769 }
1770 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001771
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001772#if 0
1773 // FIXME: Temporarily disabled because we are not properly parsing
1774 // linkage specifications on declarations, e.g.,
1775 //
1776 // extern "C" const CGPoint CGPointerZero;
1777 //
Douglas Gregor81c29152008-10-29 00:13:59 +00001778 // C++ [dcl.init]p9:
1779 //
1780 // If no initializer is specified for an object, and the
1781 // object is of (possibly cv-qualified) non-POD class type (or
1782 // array thereof), the object shall be default-initialized; if
1783 // the object is of const-qualified type, the underlying class
1784 // type shall have a user-declared default
1785 // constructor. Otherwise, if no initializer is specified for
1786 // an object, the object and its subobjects, if any, have an
1787 // indeterminate initial value; if the object or any of its
1788 // subobjects are of const-qualified type, the program is
1789 // ill-formed.
1790 //
1791 // This isn't technically an error in C, so we don't diagnose it.
1792 //
1793 // FIXME: Actually perform the POD/user-defined default
1794 // constructor check.
1795 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001796 Context.getCanonicalType(Type).isConstQualified() &&
1797 Var->getStorageClass() != VarDecl::Extern)
Douglas Gregor81c29152008-10-29 00:13:59 +00001798 Diag(Var->getLocation(),
1799 diag::err_const_var_requires_init,
1800 Var->getName(),
1801 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001802#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00001803 }
1804}
1805
Chris Lattner4b009652007-07-25 00:24:17 +00001806/// The declarators are chained together backwards, reverse the list.
1807Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1808 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001809 Decl *GroupDecl = static_cast<Decl*>(group);
1810 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00001811 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00001812
1813 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1814 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001815 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00001816 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001817 else { // reverse the list.
1818 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001819 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001820 Group->setNextDeclarator(NewGroup);
1821 NewGroup = Group;
1822 Group = Next;
1823 }
1824 }
1825 // Perform semantic analysis that depends on having fully processed both
1826 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001827 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001828 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1829 if (!IDecl)
1830 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001831 QualType T = IDecl->getType();
1832
1833 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1834 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001835 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1836 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001837 if (T->isVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001838 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1839 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001840 }
1841 }
1842 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1843 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001844 if (IDecl->isBlockVarDecl() &&
1845 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001846 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001847 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1848 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001849 IDecl->setInvalidDecl();
1850 }
1851 }
1852 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1853 // object that has file scope without an initializer, and without a
1854 // storage-class specifier or with the storage-class specifier "static",
1855 // constitutes a tentative definition. Note: A tentative definition with
1856 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00001857 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001858 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001859 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1860 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001861 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001862 // C99 6.9.2p3: If the declaration of an identifier for an object is
1863 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1864 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001865 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1866 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001867 IDecl->setInvalidDecl();
1868 }
1869 }
Steve Naroffb5e78152008-08-08 17:50:35 +00001870 if (IDecl->isFileVarDecl())
1871 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001872 }
1873 return NewGroup;
1874}
Steve Naroff91b03f72007-08-28 03:03:08 +00001875
Chris Lattner3e254fb2008-04-08 04:40:51 +00001876/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1877/// to introduce parameters into function prototype scope.
1878Sema::DeclTy *
1879Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001880 // FIXME: disallow CXXScopeSpec for param declarators.
Chris Lattner5e77ade2008-06-26 06:49:43 +00001881 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001882
1883 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001884 VarDecl::StorageClass StorageClass = VarDecl::None;
1885 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1886 StorageClass = VarDecl::Register;
1887 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001888 Diag(DS.getStorageClassSpecLoc(),
1889 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001890 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001891 }
1892 if (DS.isThreadSpecified()) {
1893 Diag(DS.getThreadSpecLoc(),
1894 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001895 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001896 }
1897
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001898 // Check that there are no default arguments inside the type of this
1899 // parameter (C++ only).
1900 if (getLangOptions().CPlusPlus)
1901 CheckExtraCXXDefaultArguments(D);
1902
Chris Lattner3e254fb2008-04-08 04:40:51 +00001903 // In this context, we *do not* check D.getInvalidType(). If the declarator
1904 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1905 // though it will not reflect the user specified type.
1906 QualType parmDeclType = GetTypeForDeclarator(D, S);
1907
1908 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1909
Chris Lattner4b009652007-07-25 00:24:17 +00001910 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1911 // Can this happen for params? We already checked that they don't conflict
1912 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001913 IdentifierInfo *II = D.getIdentifier();
1914 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1915 if (S->isDeclScope(PrevDecl)) {
1916 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1917 dyn_cast<NamedDecl>(PrevDecl)->getName());
1918
1919 // Recover by removing the name
1920 II = 0;
1921 D.SetIdentifier(0, D.getIdentifierLoc());
1922 }
Chris Lattner4b009652007-07-25 00:24:17 +00001923 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001924
1925 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1926 // Doing the promotion here has a win and a loss. The win is the type for
1927 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1928 // code generator). The loss is the orginal type isn't preserved. For example:
1929 //
1930 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1931 // int blockvardecl[5];
1932 // sizeof(parmvardecl); // size == 4
1933 // sizeof(blockvardecl); // size == 20
1934 // }
1935 //
1936 // For expressions, all implicit conversions are captured using the
1937 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1938 //
1939 // FIXME: If a source translation tool needs to see the original type, then
1940 // we need to consider storing both types (in ParmVarDecl)...
1941 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001942 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001943 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001944 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001945 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001946 parmDeclType = Context.getPointerType(parmDeclType);
1947
Chris Lattner3e254fb2008-04-08 04:40:51 +00001948 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1949 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001950 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001951 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001952
Chris Lattner3e254fb2008-04-08 04:40:51 +00001953 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001954 New->setInvalidDecl();
1955
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001956 if (II)
1957 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001958
Chris Lattner9b384ca2008-06-29 00:02:00 +00001959 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00001960 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001961
Chris Lattner4b009652007-07-25 00:24:17 +00001962}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001963
Chris Lattnerea148702007-10-09 17:14:05 +00001964Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001965 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00001966 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1967 "Not a function declarator!");
1968 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001969
Chris Lattner4b009652007-07-25 00:24:17 +00001970 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1971 // for a K&R function.
1972 if (!FTI.hasPrototype) {
1973 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001974 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001975 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1976 FTI.ArgInfo[i].Ident->getName());
1977 // Implicitly declare the argument as type 'int' for lack of a better
1978 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001979 DeclSpec DS;
1980 const char* PrevSpec; // unused
1981 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1982 PrevSpec);
1983 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1984 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1985 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00001986 }
1987 }
Chris Lattner4b009652007-07-25 00:24:17 +00001988 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001989 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00001990 }
1991
1992 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001993
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001994 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001995 ActOnDeclarator(GlobalScope, D, 0));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001996}
1997
1998Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1999 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002000 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002001
2002 // See if this is a redefinition.
2003 const FunctionDecl *Definition;
2004 if (FD->getBody(Definition)) {
2005 Diag(FD->getLocation(), diag::err_redefinition,
2006 FD->getName());
2007 Diag(Definition->getLocation(), diag::err_previous_definition);
2008 }
2009
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002010 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00002011
2012 // Check the validity of our function parameters
2013 CheckParmsForFunctionDef(FD);
2014
2015 // Introduce our parameters into the function scope
2016 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2017 ParmVarDecl *Param = FD->getParamDecl(p);
2018 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002019 if (Param->getIdentifier())
2020 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002021 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002022
Chris Lattner4b009652007-07-25 00:24:17 +00002023 return FD;
2024}
2025
Steve Naroff99ee4302007-11-11 23:20:51 +00002026Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2027 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002028 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002029 FD->setBody((Stmt*)Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002030 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002031 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002032 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002033 } else
2034 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002035 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002036 // Verify and clean out per-function state.
2037
2038 // Check goto/label use.
2039 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2040 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2041 // Verify that we have no forward references left. If so, there was a goto
2042 // or address of a label taken, but no definition of it. Label fwd
2043 // definitions are indicated with a null substmt.
2044 if (I->second->getSubStmt() == 0) {
2045 LabelStmt *L = I->second;
2046 // Emit error.
2047 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
2048
2049 // At this point, we have gotos that use the bogus label. Stitch it into
2050 // the function body so that they aren't leaked and that the AST is well
2051 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002052 if (Body) {
2053 L->setSubStmt(new NullStmt(L->getIdentLoc()));
2054 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2055 } else {
2056 // The whole function wasn't parsed correctly, just delete this.
2057 delete L;
2058 }
Chris Lattner4b009652007-07-25 00:24:17 +00002059 }
2060 }
2061 LabelMap.clear();
2062
Steve Naroff99ee4302007-11-11 23:20:51 +00002063 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002064}
2065
Chris Lattner4b009652007-07-25 00:24:17 +00002066/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2067/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00002068ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2069 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002070 // Extension in C99. Legal in C90, but warn about it.
2071 if (getLangOptions().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00002072 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002073 else
Chris Lattner4b009652007-07-25 00:24:17 +00002074 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
2075
2076 // FIXME: handle stuff like:
2077 // void foo() { extern float X(); }
2078 // void bar() { X(); } <-- implicit decl for X in another scope.
2079
2080 // Set a Declarator for the implicit definition: int foo();
2081 const char *Dummy;
2082 DeclSpec DS;
2083 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2084 Error = Error; // Silence warning.
2085 assert(!Error && "Error setting up implicit decl!");
2086 Declarator D(DS, Declarator::BlockContext);
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00002087 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Chris Lattner4b009652007-07-25 00:24:17 +00002088 D.SetIdentifier(&II, Loc);
2089
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002090 // Insert this function into translation-unit scope.
2091
2092 DeclContext *PrevDC = CurContext;
2093 CurContext = Context.getTranslationUnitDecl();
2094
Steve Naroff9104f3c2008-04-04 14:32:09 +00002095 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002096 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002097 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002098
2099 CurContext = PrevDC;
2100
Steve Naroff9104f3c2008-04-04 14:32:09 +00002101 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002102}
2103
2104
Chris Lattner82bb4792007-11-14 06:34:38 +00002105TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00002106 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002107 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002108 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002109
2110 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002111 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2112 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002113 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00002114 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002115 if (D.getInvalidType())
2116 NewTD->setInvalidDecl();
2117 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002118}
2119
Steve Naroff0acc9c92007-09-15 18:49:24 +00002120/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002121/// former case, Name will be non-null. In the later case, Name will be null.
2122/// TagType indicates what kind of tag this is. TK indicates whether this is a
2123/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002124Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002125 SourceLocation KWLoc, const CXXScopeSpec &SS,
2126 IdentifierInfo *Name, SourceLocation NameLoc,
2127 AttributeList *Attr) {
Chris Lattner4b009652007-07-25 00:24:17 +00002128 // If this is a use of an existing tag, it must have a name.
2129 assert((Name != 0 || TK == TK_Definition) &&
2130 "Nameless record must be a definition!");
2131
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002132 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00002133 switch (TagType) {
2134 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002135 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2136 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2137 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2138 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002139 }
2140
Ted Kremenek46a837c2008-09-05 17:16:31 +00002141 // Two code paths: a new one for structs/unions/classes where we create
2142 // separate decls for forward declarations, and an old (eventually to
2143 // be removed) code path for enums.
2144 if (Kind != TagDecl::TK_enum)
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002145 return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
Ted Kremenek46a837c2008-09-05 17:16:31 +00002146
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002147 DeclContext *DC = CurContext;
2148 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002149
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002150 if (Name && SS.isNotEmpty()) {
2151 // We have a nested-name tag ('struct foo::bar').
2152
2153 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002154 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002155 Name = 0;
2156 goto CreateNewDecl;
2157 }
2158
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002159 DC = static_cast<DeclContext*>(SS.getScopeRep());
2160 // Look-up name inside 'foo::'.
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002161 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2162
2163 // A tag 'foo::bar' must already exist.
2164 if (PrevDecl == 0) {
2165 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2166 SS.getRange());
2167 Name = 0;
2168 goto CreateNewDecl;
2169 }
2170 } else {
2171 // If this is a named struct, check to see if there was a previous forward
2172 // declaration or definition.
2173 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2174 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2175 }
2176
Ted Kremenekd4434152008-09-02 21:26:19 +00002177 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002178 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2179 "unexpected Decl type");
2180 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002181 // If this is a use of a previous tag, or if the tag is already declared
2182 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002183 // rementions the tag), reuse the decl.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002184 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002185 // Make sure that this wasn't declared as an enum and now used as a
2186 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002187 if (PrevTagDecl->getTagKind() != Kind) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002188 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2189 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002190 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002191 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002192 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002193 } else {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002194 // If this is a use or a forward declaration, we're good.
2195 if (TK != TK_Definition)
2196 return PrevDecl;
2197
2198 // Diagnose attempts to redefine a tag.
2199 if (PrevTagDecl->isDefinition()) {
2200 Diag(NameLoc, diag::err_redefinition, Name->getName());
2201 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2202 // If this is a redefinition, recover by making this struct be
2203 // anonymous, which will make any later references get the previous
2204 // definition.
2205 Name = 0;
2206 } else {
2207 // Okay, this is definition of a previously declared or referenced
2208 // tag. Move the location of the decl to be the definition site.
2209 PrevDecl->setLocation(NameLoc);
2210 return PrevDecl;
2211 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002212 }
Chris Lattner4b009652007-07-25 00:24:17 +00002213 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002214 // If we get here, this is a definition of a new struct type in a nested
2215 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2216 // type.
2217 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002218 // PrevDecl is a namespace.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002219 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002220 // The tag name clashes with a namespace name, issue an error and
2221 // recover by making this tag be anonymous.
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002222 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2223 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2224 Name = 0;
2225 }
Chris Lattner4b009652007-07-25 00:24:17 +00002226 }
Chris Lattner4b009652007-07-25 00:24:17 +00002227 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002228
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002229 CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00002230
2231 // If there is an identifier, use the location of the identifier as the
2232 // location of the decl, otherwise use the location of the struct/union
2233 // keyword.
2234 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2235
2236 // Otherwise, if this is the first time we've seen this tag, create the decl.
2237 TagDecl *New;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002238 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00002239 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2240 // enum X { A, B, C } D; D should chain to X.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002241 New = EnumDecl::Create(Context, DC, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002242 // If this is an undefined enum, warn.
2243 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002244 } else {
2245 // struct/union/class
2246
Chris Lattner4b009652007-07-25 00:24:17 +00002247 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2248 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002249 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002250 // FIXME: Look for a way to use RecordDecl for simple structs.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002251 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002252 else
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002253 New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002254 }
Chris Lattner4b009652007-07-25 00:24:17 +00002255
2256 // If this has an identifier, add it to the scope stack.
2257 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00002258 // The scope passed in may not be a decl scope. Zip up the scope tree until
2259 // we find one that is.
2260 while ((S->getFlags() & Scope::DeclScope) == 0)
2261 S = S->getParent();
2262
2263 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002264 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002265 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00002266
Chris Lattnerd7e83d82008-06-28 23:58:55 +00002267 if (Attr)
2268 ProcessDeclAttributeList(New, Attr);
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00002269
2270 // Set the lexical context. If the tag has a C++ scope specifier, the
2271 // lexical context will be different from the semantic context.
2272 New->setLexicalDeclContext(CurContext);
2273
Chris Lattner4b009652007-07-25 00:24:17 +00002274 return New;
2275}
2276
Ted Kremenek46a837c2008-09-05 17:16:31 +00002277/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2278/// the logic for enums, we create separate decls for forward declarations.
2279/// This is called by ActOnTag, but eventually will replace its logic.
2280Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002281 SourceLocation KWLoc, const CXXScopeSpec &SS,
2282 IdentifierInfo *Name, SourceLocation NameLoc,
2283 AttributeList *Attr) {
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002284 DeclContext *DC = CurContext;
2285 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002286
2287 if (Name && SS.isNotEmpty()) {
2288 // We have a nested-name tag ('struct foo::bar').
2289
2290 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002291 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002292 Name = 0;
2293 goto CreateNewDecl;
2294 }
2295
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002296 DC = static_cast<DeclContext*>(SS.getScopeRep());
2297 // Look-up name inside 'foo::'.
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002298 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2299
2300 // A tag 'foo::bar' must already exist.
2301 if (PrevDecl == 0) {
2302 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2303 SS.getRange());
2304 Name = 0;
2305 goto CreateNewDecl;
2306 }
2307 } else {
2308 // If this is a named struct, check to see if there was a previous forward
2309 // declaration or definition.
2310 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2311 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2312 }
Ted Kremenek46a837c2008-09-05 17:16:31 +00002313
2314 if (PrevDecl) {
2315 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2316 "unexpected Decl type");
2317
2318 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2319 // If this is a use of a previous tag, or if the tag is already declared
2320 // in the same scope (so that the definition/declaration completes or
2321 // rementions the tag), reuse the decl.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002322 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002323 // Make sure that this wasn't declared as an enum and now used as a
2324 // struct or something similar.
2325 if (PrevTagDecl->getTagKind() != Kind) {
2326 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2327 Diag(PrevDecl->getLocation(), diag::err_previous_use);
2328 // Recover by making this an anonymous redefinition.
2329 Name = 0;
2330 PrevDecl = 0;
2331 } else {
2332 // If this is a use, return the original decl.
2333
2334 // FIXME: In the future, return a variant or some other clue
2335 // for the consumer of this Decl to know it doesn't own it.
2336 // For our current ASTs this shouldn't be a problem, but will
2337 // need to be changed with DeclGroups.
2338 if (TK == TK_Reference)
2339 return PrevDecl;
2340
2341 // The new decl is a definition?
2342 if (TK == TK_Definition) {
2343 // Diagnose attempts to redefine a tag.
2344 if (RecordDecl* DefRecord =
2345 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
2346 Diag(NameLoc, diag::err_redefinition, Name->getName());
2347 Diag(DefRecord->getLocation(), diag::err_previous_definition);
2348 // If this is a redefinition, recover by making this struct be
2349 // anonymous, which will make any later references get the previous
2350 // definition.
2351 Name = 0;
2352 PrevDecl = 0;
2353 }
2354 // Okay, this is definition of a previously declared or referenced
2355 // tag. We're going to create a new Decl.
2356 }
2357 }
2358 // If we get here we have (another) forward declaration. Just create
2359 // a new decl.
2360 }
2361 else {
2362 // If we get here, this is a definition of a new struct type in a nested
2363 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2364 // new decl/type. We set PrevDecl to NULL so that the Records
2365 // have distinct types.
2366 PrevDecl = 0;
2367 }
2368 } else {
2369 // PrevDecl is a namespace.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002370 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002371 // The tag name clashes with a namespace name, issue an error and
2372 // recover by making this tag be anonymous.
2373 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2374 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2375 Name = 0;
2376 }
2377 }
2378 }
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002379
2380 CreateNewDecl:
2381
Ted Kremenek46a837c2008-09-05 17:16:31 +00002382 // If there is an identifier, use the location of the identifier as the
2383 // location of the decl, otherwise use the location of the struct/union
2384 // keyword.
2385 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2386
2387 // Otherwise, if this is the first time we've seen this tag, create the decl.
2388 TagDecl *New;
2389
2390 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2391 // struct X { int A; } D; D should chain to X.
2392 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002393 // FIXME: Look for a way to use RecordDecl for simple structs.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002394 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek46a837c2008-09-05 17:16:31 +00002395 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2396 else
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002397 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek46a837c2008-09-05 17:16:31 +00002398 dyn_cast_or_null<RecordDecl>(PrevDecl));
2399
2400 // If this has an identifier, add it to the scope stack.
2401 if ((TK == TK_Definition || !PrevDecl) && Name) {
2402 // The scope passed in may not be a decl scope. Zip up the scope tree until
2403 // we find one that is.
2404 while ((S->getFlags() & Scope::DeclScope) == 0)
2405 S = S->getParent();
2406
2407 // Add it to the decl chain.
2408 PushOnScopeChains(New, S);
2409 }
Daniel Dunbar2cb762f2008-10-16 02:34:03 +00002410
2411 // Handle #pragma pack: if the #pragma pack stack has non-default
2412 // alignment, make up a packed attribute for this decl. These
2413 // attributes are checked when the ASTContext lays out the
2414 // structure.
2415 //
2416 // It is important for implementing the correct semantics that this
2417 // happen here (in act on tag decl). The #pragma pack stack is
2418 // maintained as a result of parser callbacks which can occur at
2419 // many points during the parsing of a struct declaration (because
2420 // the #pragma tokens are effectively skipped over during the
2421 // parsing of the struct).
2422 if (unsigned Alignment = PackContext.getAlignment())
2423 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek46a837c2008-09-05 17:16:31 +00002424
2425 if (Attr)
2426 ProcessDeclAttributeList(New, Attr);
2427
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00002428 // Set the lexical context. If the tag has a C++ scope specifier, the
2429 // lexical context will be different from the semantic context.
2430 New->setLexicalDeclContext(CurContext);
2431
Ted Kremenek46a837c2008-09-05 17:16:31 +00002432 return New;
2433}
2434
2435
Chris Lattner1bf58f62008-06-21 19:39:06 +00002436/// Collect the instance variables declared in an Objective-C object. Used in
2437/// the creation of structures from objects using the @defs directive.
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002438static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002439 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002440 if (Class->getSuperClass())
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002441 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2442
2443 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremenek40e70e72008-09-03 18:03:35 +00002444 for (ObjCInterfaceDecl::ivar_iterator
2445 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2446
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002447 ObjCIvarDecl* ID = *I;
2448 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2449 ID->getIdentifier(),
2450 ID->getType(),
2451 ID->getBitWidth()));
2452 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002453}
2454
2455/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2456/// instance variables of ClassName into Decls.
2457void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2458 IdentifierInfo *ClassName,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002459 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002460 // Check that ClassName is a valid class
2461 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2462 if (!Class) {
2463 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
2464 return;
2465 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002466 // Collect the instance variables
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002467 CollectIvars(Class, Context, Decls);
Chris Lattner1bf58f62008-06-21 19:39:06 +00002468}
2469
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002470QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
2471 // This method tries to turn a variable array into a constant
2472 // array even when the size isn't an ICE. This is necessary
2473 // for compatibility with code that depends on gcc's buggy
2474 // constant expression folding, like struct {char x[(int)(char*)2];}
2475 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc7436af2008-07-03 04:20:39 +00002476 APValue Result;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002477 if (VLATy->getSizeExpr() &&
Chris Lattner334b1942008-07-11 19:19:21 +00002478 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
2479 llvm::APSInt &Res = Result.getInt();
2480 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2481 return Context.getConstantArrayType(VLATy->getElementType(),
2482 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002483 }
2484 }
2485 return QualType();
2486}
2487
Steve Naroff0acc9c92007-09-15 18:49:24 +00002488/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00002489/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002490Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00002491 SourceLocation DeclStart,
2492 Declarator &D, ExprTy *BitfieldWidth) {
2493 IdentifierInfo *II = D.getIdentifier();
2494 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00002495 SourceLocation Loc = DeclStart;
2496 if (II) Loc = D.getIdentifierLoc();
2497
2498 // FIXME: Unnamed fields can be handled in various different ways, for
2499 // example, unnamed unions inject all members into the struct namespace!
Ted Kremenek40e70e72008-09-03 18:03:35 +00002500
Chris Lattner4b009652007-07-25 00:24:17 +00002501 if (BitWidth) {
2502 // TODO: Validate.
2503 //printf("WARNING: BITFIELDS IGNORED!\n");
2504
2505 // 6.7.2.1p3
2506 // 6.7.2.1p4
2507
2508 } else {
2509 // Not a bitfield.
2510
2511 // validate II.
2512
2513 }
2514
2515 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002516 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2517 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00002518
Chris Lattner4b009652007-07-25 00:24:17 +00002519 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2520 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00002521 if (T->isVariablyModifiedType()) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002522 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
2523 if (!FixedTy.isNull()) {
2524 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
2525 T = FixedTy;
2526 } else {
2527 // FIXME: This diagnostic needs work
2528 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2529 InvalidDecl = true;
2530 }
Chris Lattner4b009652007-07-25 00:24:17 +00002531 }
Chris Lattner4b009652007-07-25 00:24:17 +00002532 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002533 FieldDecl *NewFD;
2534
2535 if (getLangOptions().CPlusPlus) {
2536 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2537 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2538 Loc, II, T, BitWidth);
2539 if (II)
2540 PushOnScopeChains(NewFD, S);
2541 }
2542 else
2543 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00002544
Chris Lattner9b384ca2008-06-29 00:02:00 +00002545 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002546
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002547 if (D.getInvalidType() || InvalidDecl)
2548 NewFD->setInvalidDecl();
2549 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00002550}
2551
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002552/// TranslateIvarVisibility - Translate visibility from a token ID to an
2553/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00002554static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002555TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00002556 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00002557 default: assert(0 && "Unknown visitibility kind");
2558 case tok::objc_private: return ObjCIvarDecl::Private;
2559 case tok::objc_public: return ObjCIvarDecl::Public;
2560 case tok::objc_protected: return ObjCIvarDecl::Protected;
2561 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00002562 }
2563}
2564
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002565/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2566/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002567Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002568 SourceLocation DeclStart,
2569 Declarator &D, ExprTy *BitfieldWidth,
2570 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002571 IdentifierInfo *II = D.getIdentifier();
2572 Expr *BitWidth = (Expr*)BitfieldWidth;
2573 SourceLocation Loc = DeclStart;
2574 if (II) Loc = D.getIdentifierLoc();
2575
2576 // FIXME: Unnamed fields can be handled in various different ways, for
2577 // example, unnamed unions inject all members into the struct namespace!
2578
2579
2580 if (BitWidth) {
2581 // TODO: Validate.
2582 //printf("WARNING: BITFIELDS IGNORED!\n");
2583
2584 // 6.7.2.1p3
2585 // 6.7.2.1p4
2586
2587 } else {
2588 // Not a bitfield.
2589
2590 // validate II.
2591
2592 }
2593
2594 QualType T = GetTypeForDeclarator(D, S);
2595 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2596 bool InvalidDecl = false;
2597
2598 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2599 // than a variably modified type.
2600 if (T->isVariablyModifiedType()) {
2601 // FIXME: This diagnostic needs work
2602 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2603 InvalidDecl = true;
2604 }
2605
Ted Kremenek173dd312008-07-23 18:04:17 +00002606 // Get the visibility (access control) for this ivar.
2607 ObjCIvarDecl::AccessControl ac =
2608 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2609 : ObjCIvarDecl::None;
2610
2611 // Construct the decl.
2612 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00002613 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002614
Ted Kremenek173dd312008-07-23 18:04:17 +00002615 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00002616 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002617
2618 if (D.getInvalidType() || InvalidDecl)
2619 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00002620
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002621 return NewID;
2622}
2623
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00002624void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002625 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00002626 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00002627 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00002628 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002629 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2630 assert(EnclosingDecl && "missing record or interface decl");
2631 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2632
Ted Kremenek46a837c2008-09-05 17:16:31 +00002633 if (Record)
2634 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2635 // Diagnose code like:
2636 // struct S { struct S {} X; };
2637 // We discover this when we complete the outer S. Reject and ignore the
2638 // outer S.
2639 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2640 DefRecord->getKindName());
2641 Diag(RecLoc, diag::err_previous_definition);
2642 Record->setInvalidDecl();
2643 return;
2644 }
2645
Chris Lattner4b009652007-07-25 00:24:17 +00002646 // Verify that all the fields are okay.
2647 unsigned NumNamedMembers = 0;
2648 llvm::SmallVector<FieldDecl*, 32> RecFields;
2649 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00002650
Chris Lattner4b009652007-07-25 00:24:17 +00002651 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002652
Steve Naroff9bb759f2007-09-14 22:20:54 +00002653 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2654 assert(FD && "missing field decl");
2655
2656 // Remember all fields.
2657 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002658
2659 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002660 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002661
Chris Lattner4b009652007-07-25 00:24:17 +00002662 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002663 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002664 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00002665 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002666 FD->setInvalidDecl();
2667 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002668 continue;
2669 }
Chris Lattner4b009652007-07-25 00:24:17 +00002670 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2671 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002672 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002673 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002674 FD->setInvalidDecl();
2675 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002676 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002677 }
Chris Lattner4b009652007-07-25 00:24:17 +00002678 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002679 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002680 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00002681 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002682 FD->setInvalidDecl();
2683 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002684 continue;
2685 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002686 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00002687 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2688 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002689 FD->setInvalidDecl();
2690 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002691 continue;
2692 }
Chris Lattner4b009652007-07-25 00:24:17 +00002693 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002694 if (Record)
2695 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002696 }
Chris Lattner4b009652007-07-25 00:24:17 +00002697 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2698 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002699 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002700 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2701 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002702 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002703 Record->setHasFlexibleArrayMember(true);
2704 } else {
2705 // If this is a struct/class and this is not the last element, reject
2706 // it. Note that GCC supports variable sized arrays in the middle of
2707 // structures.
2708 if (i != NumFields-1) {
2709 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2710 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002711 FD->setInvalidDecl();
2712 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002713 continue;
2714 }
Chris Lattner4b009652007-07-25 00:24:17 +00002715 // We support flexible arrays at the end of structs in other structs
2716 // as an extension.
2717 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2718 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002719 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002720 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002721 }
2722 }
2723 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002724 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002725 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002726 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2727 FD->getName());
2728 FD->setInvalidDecl();
2729 EnclosingDecl->setInvalidDecl();
2730 continue;
2731 }
Chris Lattner4b009652007-07-25 00:24:17 +00002732 // Keep track of the number of named members.
2733 if (IdentifierInfo *II = FD->getIdentifier()) {
2734 // Detect duplicate member names.
2735 if (!FieldIDs.insert(II)) {
2736 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2737 // Find the previous decl.
2738 SourceLocation PrevLoc;
Chris Lattner504c5432008-10-12 00:28:42 +00002739 for (unsigned i = 0; ; ++i) {
2740 assert(i != RecFields.size() && "Didn't find previous def!");
Chris Lattner4b009652007-07-25 00:24:17 +00002741 if (RecFields[i]->getIdentifier() == II) {
2742 PrevLoc = RecFields[i]->getLocation();
2743 break;
2744 }
2745 }
2746 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002747 FD->setInvalidDecl();
2748 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002749 continue;
2750 }
2751 ++NumNamedMembers;
2752 }
Chris Lattner4b009652007-07-25 00:24:17 +00002753 }
2754
Chris Lattner4b009652007-07-25 00:24:17 +00002755 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00002756 if (Record) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002757 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00002758 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2759 // Sema::ActOnFinishCXXClassDef.
2760 if (!isa<CXXRecordDecl>(Record))
2761 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002762 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002763 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2764 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2765 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2766 else if (ObjCImplementationDecl *IMPDecl =
2767 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002768 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2769 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00002770 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00002771 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00002772 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00002773
2774 if (Attr)
2775 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002776}
2777
Steve Naroff0acc9c92007-09-15 18:49:24 +00002778Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00002779 DeclTy *lastEnumConst,
2780 SourceLocation IdLoc, IdentifierInfo *Id,
2781 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00002782 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002783 EnumConstantDecl *LastEnumConst =
2784 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2785 Expr *Val = static_cast<Expr*>(val);
2786
Chris Lattnera7549902007-08-26 06:24:45 +00002787 // The scope passed in may not be a decl scope. Zip up the scope tree until
2788 // we find one that is.
2789 while ((S->getFlags() & Scope::DeclScope) == 0)
2790 S = S->getParent();
2791
Chris Lattner4b009652007-07-25 00:24:17 +00002792 // Verify that there isn't already something declared with this name in this
2793 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00002794 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00002795 // When in C++, we may get a TagDecl with the same name; in this case the
2796 // enum constant will 'hide' the tag.
2797 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2798 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002799 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002800 if (isa<EnumConstantDecl>(PrevDecl))
2801 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2802 else
2803 Diag(IdLoc, diag::err_redefinition, Id->getName());
2804 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002805 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00002806 return 0;
2807 }
2808 }
2809
2810 llvm::APSInt EnumVal(32);
2811 QualType EltTy;
2812 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00002813 // Make sure to promote the operand type to int.
2814 UsualUnaryConversions(Val);
2815
Chris Lattner4b009652007-07-25 00:24:17 +00002816 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2817 SourceLocation ExpLoc;
2818 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2819 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2820 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002821 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00002822 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00002823 } else {
2824 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002825 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00002826 }
2827
2828 if (!Val) {
2829 if (LastEnumConst) {
2830 // Assign the last value + 1.
2831 EnumVal = LastEnumConst->getInitVal();
2832 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00002833
2834 // Check for overflow on increment.
2835 if (EnumVal < LastEnumConst->getInitVal())
2836 Diag(IdLoc, diag::warn_enum_value_overflow);
2837
Chris Lattnere7f53a42007-08-27 17:37:24 +00002838 EltTy = LastEnumConst->getType();
2839 } else {
2840 // First value, set to zero.
2841 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002842 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00002843 }
Chris Lattner4b009652007-07-25 00:24:17 +00002844 }
2845
Chris Lattnere4650482008-03-15 06:12:44 +00002846 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00002847 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2848 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00002849 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00002850
2851 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002852 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002853 return New;
2854}
2855
Steve Naroffb0726b82008-08-07 14:08:16 +00002856// FIXME: For consistency with ActOnFields(), we should have the parser
2857// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002858void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00002859 DeclTy **Elements, unsigned NumElements) {
2860 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattner4b009652007-07-25 00:24:17 +00002861
Steve Naroffb0726b82008-08-07 14:08:16 +00002862 if (Enum && Enum->isDefinition()) {
2863 // Diagnose code like:
2864 // enum e0 {
2865 // E0 = sizeof(enum e0 { E1 })
2866 // };
2867 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2868 Enum->getName());
2869 Diag(EnumLoc, diag::err_previous_definition);
2870 Enum->setInvalidDecl();
2871 return;
2872 }
Chris Lattner435c3fd2007-08-28 05:10:31 +00002873 // TODO: If the result value doesn't fit in an int, it must be a long or long
2874 // long value. ISO C does not support this, but GCC does as an extension,
2875 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002876 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00002877
Chris Lattner206754a2007-08-28 06:15:15 +00002878 // Verify that all the values are okay, compute the size of the values, and
2879 // reverse the list.
2880 unsigned NumNegativeBits = 0;
2881 unsigned NumPositiveBits = 0;
2882
2883 // Keep track of whether all elements have type int.
2884 bool AllElementsInt = true;
2885
Chris Lattner4b009652007-07-25 00:24:17 +00002886 EnumConstantDecl *EltList = 0;
2887 for (unsigned i = 0; i != NumElements; ++i) {
2888 EnumConstantDecl *ECD =
2889 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2890 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002891
2892 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002893 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002894 assert(InitVal.getBitWidth() >= IntWidth &&
2895 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00002896 if (InitVal.getBitWidth() > IntWidth) {
2897 llvm::APSInt V(InitVal);
2898 V.trunc(IntWidth);
2899 V.extend(InitVal.getBitWidth());
2900 if (V != InitVal)
2901 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattneread053a2008-08-17 07:19:51 +00002902 InitVal.toString(10));
Chris Lattnercb33ae12007-08-28 05:27:00 +00002903 }
Chris Lattner206754a2007-08-28 06:15:15 +00002904
2905 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002906 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00002907 NumPositiveBits = std::max(NumPositiveBits,
2908 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00002909 else
Chris Lattneraff63f02008-01-14 21:47:29 +00002910 NumNegativeBits = std::max(NumNegativeBits,
2911 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00002912
Chris Lattner206754a2007-08-28 06:15:15 +00002913 // Keep track of whether every enum element has type int (very commmon).
2914 if (AllElementsInt)
2915 AllElementsInt = ECD->getType() == Context.IntTy;
2916
Chris Lattner4b009652007-07-25 00:24:17 +00002917 ECD->setNextDeclarator(EltList);
2918 EltList = ECD;
2919 }
2920
Chris Lattner206754a2007-08-28 06:15:15 +00002921 // Figure out the type that should be used for this enum.
2922 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2923 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002924 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00002925
2926 if (NumNegativeBits) {
2927 // If there is a negative value, figure out the smallest integer type (of
2928 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002929 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002930 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002931 BestWidth = IntWidth;
2932 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002933 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002934
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002935 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002936 BestType = Context.LongTy;
2937 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002938 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002939
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002940 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002941 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2942 BestType = Context.LongLongTy;
2943 }
2944 }
2945 } else {
2946 // If there is no negative value, figure out which of uint, ulong, ulonglong
2947 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002948 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002949 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002950 BestWidth = IntWidth;
2951 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00002952 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00002953 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002954 } else {
2955 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002956 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00002957 "How could an initializer get larger than ULL?");
2958 BestType = Context.UnsignedLongLongTy;
2959 }
2960 }
2961
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002962 // Loop over all of the enumerator constants, changing their types to match
2963 // the type of the enum if needed.
2964 for (unsigned i = 0; i != NumElements; ++i) {
2965 EnumConstantDecl *ECD =
2966 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2967 if (!ECD) continue; // Already issued a diagnostic.
2968
2969 // Standard C says the enumerators have int type, but we allow, as an
2970 // extension, the enumerators to be larger than int size. If each
2971 // enumerator value fits in an int, type it as an int, otherwise type it the
2972 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2973 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002974 if (ECD->getType() == Context.IntTy) {
2975 // Make sure the init value is signed.
2976 llvm::APSInt IV = ECD->getInitVal();
2977 IV.setIsSigned(true);
2978 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002979 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002980 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002981
2982 // Determine whether the value fits into an int.
2983 llvm::APSInt InitVal = ECD->getInitVal();
2984 bool FitsInInt;
2985 if (InitVal.isUnsigned() || !InitVal.isNegative())
2986 FitsInInt = InitVal.getActiveBits() < IntWidth;
2987 else
2988 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2989
2990 // If it fits into an integer type, force it. Otherwise force it to match
2991 // the enum decl type.
2992 QualType NewTy;
2993 unsigned NewWidth;
2994 bool NewSign;
2995 if (FitsInInt) {
2996 NewTy = Context.IntTy;
2997 NewWidth = IntWidth;
2998 NewSign = true;
2999 } else if (ECD->getType() == BestType) {
3000 // Already the right type!
3001 continue;
3002 } else {
3003 NewTy = BestType;
3004 NewWidth = BestWidth;
3005 NewSign = BestType->isSignedIntegerType();
3006 }
3007
3008 // Adjust the APSInt value.
3009 InitVal.extOrTrunc(NewWidth);
3010 InitVal.setIsSigned(NewSign);
3011 ECD->setInitVal(InitVal);
3012
3013 // Adjust the Expr initializer and type.
3014 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
3015 ECD->setType(NewTy);
3016 }
Chris Lattner206754a2007-08-28 06:15:15 +00003017
Chris Lattner90a018d2007-08-28 18:24:31 +00003018 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003019 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003020}
3021
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003022Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3023 ExprTy *expr) {
3024 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3025
Chris Lattner81db64a2008-03-16 00:16:02 +00003026 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003027}
3028
Chris Lattner806a5f52008-01-12 07:05:38 +00003029Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00003030 SourceLocation LBrace,
3031 SourceLocation RBrace,
3032 const char *Lang,
3033 unsigned StrSize,
3034 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00003035 LinkageSpecDecl::LanguageIDs Language;
3036 Decl *dcl = static_cast<Decl *>(D);
3037 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3038 Language = LinkageSpecDecl::lang_c;
3039 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3040 Language = LinkageSpecDecl::lang_cxx;
3041 else {
3042 Diag(Loc, diag::err_bad_language);
3043 return 0;
3044 }
3045
3046 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00003047 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00003048}
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003049
3050void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3051 ExprTy *alignment, SourceLocation PragmaLoc,
3052 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3053 Expr *Alignment = static_cast<Expr *>(alignment);
3054
3055 // If specified then alignment must be a "small" power of two.
3056 unsigned AlignmentVal = 0;
3057 if (Alignment) {
3058 llvm::APSInt Val;
3059 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3060 !Val.isPowerOf2() ||
3061 Val.getZExtValue() > 16) {
3062 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3063 delete Alignment;
3064 return; // Ignore
3065 }
3066
3067 AlignmentVal = (unsigned) Val.getZExtValue();
3068 }
3069
3070 switch (Kind) {
3071 case Action::PPK_Default: // pack([n])
3072 PackContext.setAlignment(AlignmentVal);
3073 break;
3074
3075 case Action::PPK_Show: // pack(show)
3076 // Show the current alignment, making sure to show the right value
3077 // for the default.
3078 AlignmentVal = PackContext.getAlignment();
3079 // FIXME: This should come from the target.
3080 if (AlignmentVal == 0)
3081 AlignmentVal = 8;
3082 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal));
3083 break;
3084
3085 case Action::PPK_Push: // pack(push [, id] [, [n])
3086 PackContext.push(Name);
3087 // Set the new alignment if specified.
3088 if (Alignment)
3089 PackContext.setAlignment(AlignmentVal);
3090 break;
3091
3092 case Action::PPK_Pop: // pack(pop [, id] [, n])
3093 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3094 // "#pragma pack(pop, identifier, n) is undefined"
3095 if (Alignment && Name)
3096 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3097
3098 // Do the pop.
3099 if (!PackContext.pop(Name)) {
3100 // If a name was specified then failure indicates the name
3101 // wasn't found. Otherwise failure indicates the stack was
3102 // empty.
3103 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
3104 Name ? "no record matching name" : "stack empty");
3105
3106 // FIXME: Warn about popping named records as MSVC does.
3107 } else {
3108 // Pop succeeded, set the new alignment if specified.
3109 if (Alignment)
3110 PackContext.setAlignment(AlignmentVal);
3111 }
3112 break;
3113
3114 default:
3115 assert(0 && "Invalid #pragma pack kind.");
3116 }
3117}
3118
3119bool PragmaPackStack::pop(IdentifierInfo *Name) {
3120 if (Stack.empty())
3121 return false;
3122
3123 // If name is empty just pop top.
3124 if (!Name) {
3125 Alignment = Stack.back().first;
3126 Stack.pop_back();
3127 return true;
3128 }
3129
3130 // Otherwise, find the named record.
3131 for (unsigned i = Stack.size(); i != 0; ) {
3132 --i;
3133 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) {
3134 // Found it, pop up to and including this record.
3135 Alignment = Stack[i].first;
3136 Stack.erase(Stack.begin() + i, Stack.end());
3137 return true;
3138 }
3139 }
3140
3141 return false;
3142}