blob: 066969ce9e81687a0bdbc79c97d768f9cc4cb812 [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"
28using namespace clang;
29
Argiris Kirtzidis46403632008-08-01 10:35:27 +000030Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
Steve Naroff6384a012008-04-02 14:35:35 +000031 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
32
Douglas Gregor1d661552008-04-13 21:07:44 +000033 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
34 isa<ObjCInterfaceDecl>(IIDecl) ||
35 isa<TagDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000036 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000037 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000038}
39
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000040DeclContext *Sema::getDCParent(DeclContext *DC) {
41 // If CurContext is a ObjC method, getParent() will return NULL.
42 if (isa<ObjCMethodDecl>(DC))
43 return Context.getTranslationUnitDecl();
44
45 // A C++ inline method is parsed *after* the topmost class it was declared in
46 // is fully parsed (it's "complete").
47 // The parsing of a C++ inline method happens at the declaration context of
48 // the topmost (non-nested) class it is declared in.
49 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
50 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
51 DC = MD->getParent();
52 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
53 DC = RD;
54
55 // Return the declaration context of the topmost class the inline method is
56 // declared in.
57 return DC;
58 }
59
60 return DC->getParent();
61}
62
Chris Lattneref87a202008-04-22 18:39:57 +000063void Sema::PushDeclContext(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000064 assert(getDCParent(DC) == CurContext &&
65 "The next DeclContext should be directly contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000066 CurContext = DC;
Chris Lattnereee57c02008-04-04 06:12:32 +000067}
68
Chris Lattnerf3874bc2008-04-06 04:47:34 +000069void Sema::PopDeclContext() {
70 assert(CurContext && "DeclContext imbalance!");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000071 CurContext = getDCParent(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +000072}
73
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000074/// Add this decl to the scope shadowed decl chains.
75void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000076 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000077
78 // C++ [basic.scope]p4:
79 // -- exactly one declaration shall declare a class name or
80 // enumeration name that is not a typedef name and the other
81 // declarations shall all refer to the same object or
82 // enumerator, or all refer to functions and function templates;
83 // in this case the class name or enumeration name is hidden.
84 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
85 // We are pushing the name of a tag (enum or class).
Argiris Kirtzidis94805232008-07-17 17:49:50 +000086 IdentifierResolver::iterator
87 I = IdResolver.begin(TD->getIdentifier(),
88 TD->getDeclContext(), false/*LookInParentCtx*/);
89 if (I != IdResolver.end() &&
90 IdResolver.isDeclInScope(*I, TD->getDeclContext(), S)) {
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000091 // There is already a declaration with the same name in the same
92 // scope. It must be found before we find the new declaration,
93 // so swap the order on the shadowed declaration chain.
94
Argiris Kirtzidis94805232008-07-17 17:49:50 +000095 IdResolver.AddShadowedDecl(TD, *I);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000096 return;
97 }
98 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000099 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000100}
101
Steve Naroff9637a9b2007-10-09 22:01:59 +0000102void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000103 if (S->decl_empty()) return;
104 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000105
Chris Lattner4b009652007-07-25 00:24:17 +0000106 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
107 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000108 Decl *TmpD = static_cast<Decl*>(*I);
109 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000110
111 if (isa<CXXFieldDecl>(TmpD)) continue;
112
113 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
114 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000115
Chris Lattner4b009652007-07-25 00:24:17 +0000116 IdentifierInfo *II = D->getIdentifier();
117 if (!II) continue;
118
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000119 // We only want to remove the decls from the identifier decl chains for local
120 // scopes, when inside a function/method.
121 if (S->getFnParent() != 0)
122 IdResolver.RemoveDecl(D);
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000123
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000124 // Chain this decl to the containing DeclContext.
125 D->setNext(CurContext->getDeclChain());
126 CurContext->setDeclChain(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000127 }
128}
129
Steve Naroffe57c21a2008-04-01 23:04:06 +0000130/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
131/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000132ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000133 // The third "scope" argument is 0 since we aren't enabling lazy built-in
134 // creation from this context.
135 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000136
Steve Naroff6384a012008-04-02 14:35:35 +0000137 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000138}
139
Steve Naroffe57c21a2008-04-01 23:04:06 +0000140/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000141/// namespace.
Steve Naroff6384a012008-04-02 14:35:35 +0000142Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
143 Scope *S, bool enableLazyBuiltinCreation) {
Chris Lattner4b009652007-07-25 00:24:17 +0000144 if (II == 0) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000145 unsigned NS = NSI;
146 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
147 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000148
Chris Lattner4b009652007-07-25 00:24:17 +0000149 // Scan up the scope chain looking for a decl that matches this identifier
150 // that is in the appropriate namespace. This search should not take long, as
151 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000152 for (IdentifierResolver::iterator
Argiris Kirtzidis94805232008-07-17 17:49:50 +0000153 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000154 if ((*I)->getIdentifierNamespace() & NS)
155 return *I;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000156
Chris Lattner4b009652007-07-25 00:24:17 +0000157 // If we didn't find a use of this identifier, and if the identifier
158 // corresponds to a compiler builtin, create the decl object for the builtin
159 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000160 if (NS & Decl::IDNS_Ordinary) {
Steve Naroff6384a012008-04-02 14:35:35 +0000161 if (enableLazyBuiltinCreation) {
162 // If this is a builtin on this (or all) targets, create the decl.
163 if (unsigned BuiltinID = II->getBuiltinID())
164 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
165 }
Steve Naroffe57c21a2008-04-01 23:04:06 +0000166 if (getLangOptions().ObjC1) {
167 // @interface and @compatibility_alias introduce typedef-like names.
168 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000169 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000170 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000171 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
172 if (IDI != ObjCInterfaceDecls.end())
173 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000174 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
175 if (I != ObjCAliasDecls.end())
176 return I->second->getClassInterface();
177 }
Chris Lattner4b009652007-07-25 00:24:17 +0000178 }
179 return 0;
180}
181
Chris Lattnera9c87f22008-05-05 22:18:14 +0000182void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000183 if (!Context.getBuiltinVaListType().isNull())
184 return;
185
186 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000187 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000188 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000189 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
190}
191
Chris Lattner4b009652007-07-25 00:24:17 +0000192/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
193/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000194ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
195 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000196 Builtin::ID BID = (Builtin::ID)bid;
197
Anders Carlsson36760332007-10-15 20:28:48 +0000198 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattnera9c87f22008-05-05 22:18:14 +0000199 BID == Builtin::BI__builtin_va_copy ||
Chris Lattnerdf40dbf2008-07-09 17:26:36 +0000200 BID == Builtin::BI__builtin_va_end ||
201 BID == Builtin::BI__builtin_stdarg_start)
Anders Carlsson36760332007-10-15 20:28:48 +0000202 InitBuiltinVaListType();
203
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000204 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000205 FunctionDecl *New = FunctionDecl::Create(Context,
206 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000207 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000208 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000209
Chris Lattnera9c87f22008-05-05 22:18:14 +0000210 // Create Decl objects for each parameter, adding them to the
211 // FunctionDecl.
212 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
213 llvm::SmallVector<ParmVarDecl*, 16> Params;
214 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
215 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
216 FT->getArgType(i), VarDecl::None, 0,
217 0));
218 New->setParams(&Params[0], Params.size());
219 }
220
221
222
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000223 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000224 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000225 return New;
226}
227
228/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
229/// and scope as a previous declaration 'Old'. Figure out how to resolve this
230/// situation, merging decls or emitting diagnostics as appropriate.
231///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000232TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000233 // Verify the old decl was also a typedef.
234 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
235 if (!Old) {
236 Diag(New->getLocation(), diag::err_redefinition_different_kind,
237 New->getName());
238 Diag(OldD->getLocation(), diag::err_previous_definition);
239 return New;
240 }
241
Chris Lattnerbef8d622008-07-25 18:44:27 +0000242 // If the typedef types are not identical, reject them in all languages and
243 // with any extensions enabled.
244 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
245 Context.getCanonicalType(Old->getUnderlyingType()) !=
246 Context.getCanonicalType(New->getUnderlyingType())) {
247 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
248 New->getUnderlyingType().getAsString(),
249 Old->getUnderlyingType().getAsString());
250 Diag(Old->getLocation(), diag::err_previous_definition);
251 return Old;
252 }
253
Steve Naroffae84af82007-10-31 18:42:27 +0000254 // Allow multiple definitions for ObjC built-in typedefs.
255 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek42730c52008-01-07 19:49:32 +0000256 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroffae84af82007-10-31 18:42:27 +0000257 return Old;
Eli Friedman324d5032008-06-11 06:20:39 +0000258
259 if (getLangOptions().Microsoft) return New;
260
Steve Naroffa9eae582008-01-30 23:46:05 +0000261 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
262 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
263 // *either* declaration is in a system header. The code below implements
264 // this adhoc compatibility rule. FIXME: The following code will not
265 // work properly when compiling ".i" files (containing preprocessed output).
266 SourceManager &SrcMgr = Context.getSourceManager();
Steve Naroffa9eae582008-01-30 23:46:05 +0000267 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
Eli Friedman324d5032008-06-11 06:20:39 +0000268 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
269 if (OldDeclFile) {
270 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
271 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
272 if (OldDirType != DirectoryLookup::NormalHeaderDir)
273 return New;
274 }
275 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
276 if (NewDeclFile) {
277 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
278 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
279 if (NewDirType != DirectoryLookup::NormalHeaderDir)
280 return New;
281 }
282
Ted Kremenek64845ce2008-05-23 21:28:18 +0000283 Diag(New->getLocation(), diag::err_redefinition, New->getName());
284 Diag(Old->getLocation(), diag::err_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000285 return New;
286}
287
Chris Lattner6953a072008-06-26 18:38:35 +0000288/// DeclhasAttr - returns true if decl Declaration already has the target
289/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000290static bool DeclHasAttr(const Decl *decl, const Attr *target) {
291 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
292 if (attr->getKind() == target->getKind())
293 return true;
294
295 return false;
296}
297
298/// MergeAttributes - append attributes from the Old decl to the New one.
299static void MergeAttributes(Decl *New, Decl *Old) {
300 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
301
Chris Lattner402b3372008-03-03 03:28:21 +0000302 while (attr) {
303 tmp = attr;
304 attr = attr->getNext();
305
306 if (!DeclHasAttr(New, tmp)) {
307 New->addAttr(tmp);
308 } else {
309 tmp->setNext(0);
310 delete(tmp);
311 }
312 }
Nuno Lopes77654342008-06-01 22:53:53 +0000313
314 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000315}
316
Chris Lattner3e254fb2008-04-08 04:40:51 +0000317/// MergeFunctionDecl - We just parsed a function 'New' from
318/// declarator D which has the same name and scope as a previous
319/// declaration 'Old'. Figure out how to resolve this situation,
320/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor42214c52008-04-21 02:02:58 +0000321/// Redeclaration will be set true if thisNew is a redeclaration OldD.
322FunctionDecl *
323Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
324 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000325 // Verify the old decl was also a function.
326 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
327 if (!Old) {
328 Diag(New->getLocation(), diag::err_redefinition_different_kind,
329 New->getName());
330 Diag(OldD->getLocation(), diag::err_previous_definition);
331 return New;
332 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000333
Chris Lattner42a21742008-04-06 23:10:54 +0000334 QualType OldQType = Context.getCanonicalType(Old->getType());
335 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000336
Chris Lattner3e254fb2008-04-08 04:40:51 +0000337 // C++ [dcl.fct]p3:
338 // All declarations for a function shall agree exactly in both the
339 // return type and the parameter-type-list.
Douglas Gregor42214c52008-04-21 02:02:58 +0000340 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
341 MergeAttributes(New, Old);
342 Redeclaration = true;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000343 return MergeCXXFunctionDecl(New, Old);
Douglas Gregor42214c52008-04-21 02:02:58 +0000344 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000345
346 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000347 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000348 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000349 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000350 MergeAttributes(New, Old);
351 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000352 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000353 }
Chris Lattner1470b072007-11-06 06:07:26 +0000354
Steve Naroff6c9e7922008-01-16 15:01:34 +0000355 // A function that has already been declared has been redeclared or defined
356 // with a different type- show appropriate diagnostic
Steve Naroff9104f3c2008-04-04 14:32:09 +0000357 diag::kind PrevDiag;
Douglas Gregor42214c52008-04-21 02:02:58 +0000358 if (Old->isThisDeclarationADefinition())
Steve Naroff9104f3c2008-04-04 14:32:09 +0000359 PrevDiag = diag::err_previous_definition;
360 else if (Old->isImplicit())
361 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000362 else
Steve Naroff9104f3c2008-04-04 14:32:09 +0000363 PrevDiag = diag::err_previous_declaration;
Steve Naroff6c9e7922008-01-16 15:01:34 +0000364
Chris Lattner4b009652007-07-25 00:24:17 +0000365 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
366 // TODO: This is totally simplistic. It should handle merging functions
367 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000368 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
369 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000370 return New;
371}
372
Steve Naroffb5e78152008-08-08 17:50:35 +0000373/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000374static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000375 if (VD->isFileVarDecl())
376 return (!VD->getInit() &&
377 (VD->getStorageClass() == VarDecl::None ||
378 VD->getStorageClass() == VarDecl::Static));
379 return false;
380}
381
382/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
383/// when dealing with C "tentative" external object definitions (C99 6.9.2).
384void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
385 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000386 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000387
388 for (IdentifierResolver::iterator
389 I = IdResolver.begin(VD->getIdentifier(),
390 VD->getDeclContext(), false/*LookInParentCtx*/),
391 E = IdResolver.end(); I != E; ++I) {
392 if (*I != VD && IdResolver.isDeclInScope(*I, VD->getDeclContext(), S)) {
393 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
394
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000395 // Handle the following case:
396 // int a[10];
397 // int a[]; - the code below makes sure we set the correct type.
398 // int a[11]; - this is an error, size isn't 10.
399 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
400 OldDecl->getType()->isConstantArrayType())
401 VD->setType(OldDecl->getType());
402
Steve Naroffb5e78152008-08-08 17:50:35 +0000403 // Check for "tentative" definitions. We can't accomplish this in
404 // MergeVarDecl since the initializer hasn't been attached.
405 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
406 continue;
407
408 // Handle __private_extern__ just like extern.
409 if (OldDecl->getStorageClass() != VarDecl::Extern &&
410 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
411 VD->getStorageClass() != VarDecl::Extern &&
412 VD->getStorageClass() != VarDecl::PrivateExtern) {
413 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
414 Diag(OldDecl->getLocation(), diag::err_previous_definition);
415 }
416 }
417 }
418}
419
Chris Lattner4b009652007-07-25 00:24:17 +0000420/// MergeVarDecl - We just parsed a variable 'New' which has the same name
421/// and scope as a previous declaration 'Old'. Figure out how to resolve this
422/// situation, merging decls or emitting diagnostics as appropriate.
423///
Steve Naroffb5e78152008-08-08 17:50:35 +0000424/// Tentative definition rules (C99 6.9.2p2) are checked by
425/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
426/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000427///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000428VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000429 // Verify the old decl was also a variable.
430 VarDecl *Old = dyn_cast<VarDecl>(OldD);
431 if (!Old) {
432 Diag(New->getLocation(), diag::err_redefinition_different_kind,
433 New->getName());
434 Diag(OldD->getLocation(), diag::err_previous_definition);
435 return New;
436 }
Chris Lattner402b3372008-03-03 03:28:21 +0000437
438 MergeAttributes(New, Old);
439
Chris Lattner4b009652007-07-25 00:24:17 +0000440 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000441 QualType OldCType = Context.getCanonicalType(Old->getType());
442 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000443 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000444 Diag(New->getLocation(), diag::err_redefinition, New->getName());
445 Diag(Old->getLocation(), diag::err_previous_definition);
446 return New;
447 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000448 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
449 if (New->getStorageClass() == VarDecl::Static &&
450 (Old->getStorageClass() == VarDecl::None ||
451 Old->getStorageClass() == VarDecl::Extern)) {
452 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
453 Diag(Old->getLocation(), diag::err_previous_definition);
454 return New;
455 }
456 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
457 if (New->getStorageClass() != VarDecl::Static &&
458 Old->getStorageClass() == VarDecl::Static) {
459 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
460 Diag(Old->getLocation(), diag::err_previous_definition);
461 return New;
462 }
Steve Naroffb5e78152008-08-08 17:50:35 +0000463 // File scoped variables are analyzed in FinalizeDeclaratorGroup.
464 if (!New->isFileVarDecl()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000465 Diag(New->getLocation(), diag::err_redefinition, New->getName());
466 Diag(Old->getLocation(), diag::err_previous_definition);
467 }
468 return New;
469}
470
Chris Lattner3e254fb2008-04-08 04:40:51 +0000471/// CheckParmsForFunctionDef - Check that the parameters of the given
472/// function are appropriate for the definition of a function. This
473/// takes care of any checks that cannot be performed on the
474/// declaration itself, e.g., that the types of each of the function
475/// parameters are complete.
476bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
477 bool HasInvalidParm = false;
478 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
479 ParmVarDecl *Param = FD->getParamDecl(p);
480
481 // C99 6.7.5.3p4: the parameters in a parameter type list in a
482 // function declarator that is part of a function definition of
483 // that function shall not have incomplete type.
484 if (Param->getType()->isIncompleteType() &&
485 !Param->isInvalidDecl()) {
486 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
487 Param->getType().getAsString());
488 Param->setInvalidDecl();
489 HasInvalidParm = true;
490 }
491 }
492
493 return HasInvalidParm;
494}
495
496/// CreateImplicitParameter - Creates an implicit function parameter
497/// in the scope S and with the given type. This routine is used, for
498/// example, to create the implicit "self" parameter in an Objective-C
499/// method.
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000500ImplicitParamDecl *
Chris Lattner3e254fb2008-04-08 04:40:51 +0000501Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
502 SourceLocation IdLoc, QualType Type) {
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000503 ImplicitParamDecl *New = ImplicitParamDecl::Create(Context, CurContext,
504 IdLoc, Id, Type, 0);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000505 if (Id)
506 PushOnScopeChains(New, S);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000507
508 return New;
509}
510
Chris Lattner4b009652007-07-25 00:24:17 +0000511/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
512/// no declarator (e.g. "struct foo;") is parsed.
513Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
514 // TODO: emit error on 'int;' or 'const enum foo;'.
515 // TODO: emit error on 'typedef int;'
516 // if (!DS.isMissingDeclaratorOk()) Diag(...);
517
Steve Naroffedafc0b2007-11-17 21:37:36 +0000518 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000519}
520
Steve Narofff0b23542008-01-10 22:15:12 +0000521bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000522 // Get the type before calling CheckSingleAssignmentConstraints(), since
523 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000524 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000525
Chris Lattner005ed752008-01-04 18:04:52 +0000526 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
527 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
528 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000529}
530
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000531bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000532 const ArrayType *AT = Context.getAsArrayType(DeclT);
533
534 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000535 // C99 6.7.8p14. We have an array of character type with unknown size
536 // being initialized to a string literal.
537 llvm::APSInt ConstVal(32);
538 ConstVal = strLiteral->getByteLength() + 1;
539 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000540 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000541 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000542 } else {
543 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000544 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000545 // FIXME: Avoid truncation for 64-bit length strings.
546 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000547 Diag(strLiteral->getSourceRange().getBegin(),
548 diag::warn_initializer_string_for_char_array_too_long,
549 strLiteral->getSourceRange());
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000550 }
551 // Set type from "char *" to "constant array of char".
552 strLiteral->setType(DeclT);
553 // For now, we always return false (meaning success).
554 return false;
555}
556
557StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000558 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000559 if (AT && AT->getElementType()->isCharType()) {
560 return dyn_cast<StringLiteral>(Init);
561 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000562 return 0;
563}
564
Steve Narofff3cb5142008-01-25 00:51:06 +0000565bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff8e9337f2008-01-21 23:53:58 +0000566 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
567 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +0000568 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Steve Naroff8e9337f2008-01-21 23:53:58 +0000569 return Diag(VAT->getSizeExpr()->getLocStart(),
570 diag::err_variable_object_no_init,
571 VAT->getSizeExpr()->getSourceRange());
572
Steve Naroffcb69fb72007-12-10 22:44:33 +0000573 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
574 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000575 // FIXME: Handle wide strings
576 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
577 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000578
579 if (DeclType->isArrayType())
580 return Diag(Init->getLocStart(),
581 diag::err_array_init_list_required,
582 Init->getSourceRange());
583
Steve Narofff0b23542008-01-10 22:15:12 +0000584 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000585 }
Eli Friedman38b7a912008-06-06 19:40:52 +0000586
Steve Naroffc4d4a482008-05-01 22:18:59 +0000587 InitListChecker CheckInitList(this, InitList, DeclType);
588 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +0000589}
590
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000591Sema::DeclTy *
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000592Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000593 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000594 IdentifierInfo *II = D.getIdentifier();
595
596 // All of these full declarators require an identifier. If it doesn't have
597 // one, the ParsedFreeStandingDeclSpec action should be used.
598 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000599 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000600 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000601 D.getDeclSpec().getSourceRange(), D.getSourceRange());
602 return 0;
603 }
604
Chris Lattnera7549902007-08-26 06:24:45 +0000605 // The scope passed in may not be a decl scope. Zip up the scope tree until
606 // we find one that is.
607 while ((S->getFlags() & Scope::DeclScope) == 0)
608 S = S->getParent();
609
Chris Lattner4b009652007-07-25 00:24:17 +0000610 // See if this is a redefinition of a variable in the same scope.
Steve Naroff6384a012008-04-02 14:35:35 +0000611 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000612 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000613 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000614
615 // In C++, the previous declaration we find might be a tag type
616 // (class or enum). In this case, the new declaration will hide the
617 // tag type.
618 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
619 PrevDecl = 0;
620
Chris Lattner82bb4792007-11-14 06:34:38 +0000621 QualType R = GetTypeForDeclarator(D, S);
622 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
623
Chris Lattner4b009652007-07-25 00:24:17 +0000624 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000625 // Check that there are no default arguments (C++ only).
626 if (getLangOptions().CPlusPlus)
627 CheckExtraCXXDefaultArguments(D);
628
Chris Lattner82bb4792007-11-14 06:34:38 +0000629 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000630 if (!NewTD) return 0;
631
632 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000633 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +0000634 // Merge the decl with the existing one if appropriate. If the decl is
635 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000636 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000637 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
638 if (NewTD == 0) return 0;
639 }
640 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000641 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000642 // C99 6.7.7p2: If a typedef name specifies a variably modified type
643 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000644 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
645 // FIXME: Diagnostic needs to be fixed.
646 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000647 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000648 }
649 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000650 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000651 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000652 switch (D.getDeclSpec().getStorageClassSpec()) {
653 default: assert(0 && "Unknown storage class!");
654 case DeclSpec::SCS_auto:
655 case DeclSpec::SCS_register:
656 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
657 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000658 InvalidDecl = true;
659 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000660 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
661 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
662 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000663 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000664 }
665
Chris Lattner4c7802b2008-03-15 21:24:04 +0000666 bool isInline = D.getDeclSpec().isInlineSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000667 FunctionDecl *NewFD;
668 if (D.getContext() == Declarator::MemberContext) {
669 // This is a C++ method declaration.
670 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
671 D.getIdentifierLoc(), II, R,
672 (SC == FunctionDecl::Static), isInline,
673 LastDeclarator);
674 } else {
675 NewFD = FunctionDecl::Create(Context, CurContext,
676 D.getIdentifierLoc(),
677 II, R, SC, isInline,
678 LastDeclarator);
679 }
Ted Kremenek117f1862008-02-27 22:18:07 +0000680 // Handle attributes.
Chris Lattner9b384ca2008-06-29 00:02:00 +0000681 ProcessDeclAttributes(NewFD, D);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000682
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000683 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000684 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000685 // The parser guarantees this is a string.
686 StringLiteral *SE = cast<StringLiteral>(E);
687 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
688 SE->getByteLength())));
689 }
690
Chris Lattner3e254fb2008-04-08 04:40:51 +0000691 // Copy the parameter declarations from the declarator D to
692 // the function declaration NewFD, if they are available.
693 if (D.getNumTypeObjects() > 0 &&
694 D.getTypeObject(0).Fun.hasPrototype) {
695 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
696
697 // Create Decl objects for each parameter, adding them to the
698 // FunctionDecl.
699 llvm::SmallVector<ParmVarDecl*, 16> Params;
700
701 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
702 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000703 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +0000704 // We let through "const void" here because Sema::GetTypeForDeclarator
705 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000706 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
707 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +0000708 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
709 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000710 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
711
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000712 // In C++, the empty parameter-type-list must be spelled "void"; a
713 // typedef of void is not permitted.
714 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +0000715 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +0000716 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
717 }
718
Chris Lattner3e254fb2008-04-08 04:40:51 +0000719 } else {
720 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
721 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
722 }
723
724 NewFD->setParams(&Params[0], Params.size());
725 }
726
Steve Narofff8a09432008-01-09 23:34:55 +0000727 // Merge the decl with the existing one if appropriate. Since C functions
728 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000729 if (PrevDecl &&
730 (!getLangOptions().CPlusPlus ||
731 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000732 bool Redeclaration = false;
733 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Chris Lattner4b009652007-07-25 00:24:17 +0000734 if (NewFD == 0) return 0;
Douglas Gregor42214c52008-04-21 02:02:58 +0000735 if (Redeclaration) {
Eli Friedmand2701812008-05-27 05:07:37 +0000736 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregor42214c52008-04-21 02:02:58 +0000737 }
Chris Lattner4b009652007-07-25 00:24:17 +0000738 }
739 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000740
741 // In C++, check default arguments now that we have merged decls.
742 if (getLangOptions().CPlusPlus)
743 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +0000744 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000745 // Check that there are no default arguments (C++ only).
746 if (getLangOptions().CPlusPlus)
747 CheckExtraCXXDefaultArguments(D);
748
Ted Kremenek42730c52008-01-07 19:49:32 +0000749 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000750 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
751 D.getIdentifier()->getName());
752 InvalidDecl = true;
753 }
Chris Lattner4b009652007-07-25 00:24:17 +0000754
755 VarDecl *NewVD;
756 VarDecl::StorageClass SC;
757 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +0000758 default: assert(0 && "Unknown storage class!");
759 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
760 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
761 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
762 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
763 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
764 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000765 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000766 if (D.getContext() == Declarator::MemberContext) {
767 assert(SC == VarDecl::Static && "Invalid storage class for member!");
768 // This is a static data member for a C++ class.
769 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
770 D.getIdentifierLoc(), II,
771 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000772 } else {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000773 if (S->getFnParent() == 0) {
774 // C99 6.9p2: The storage-class specifiers auto and register shall not
775 // appear in the declaration specifiers in an external declaration.
776 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
777 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
778 R.getAsString());
779 InvalidDecl = true;
780 }
781 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
782 II, R, SC, LastDeclarator);
783 } else {
784 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
785 II, R, SC, LastDeclarator);
786 }
Steve Naroffcae537d2007-08-28 18:45:29 +0000787 }
Chris Lattner4b009652007-07-25 00:24:17 +0000788 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000789 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +0000790
Daniel Dunbarced89142008-08-06 00:03:29 +0000791 // Handle GNU asm-label extension (encoded as an attribute).
792 if (Expr *E = (Expr*) D.getAsmLabel()) {
793 // The parser guarantees this is a string.
794 StringLiteral *SE = cast<StringLiteral>(E);
795 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
796 SE->getByteLength())));
797 }
798
Nate Begemanea583262008-03-14 18:07:10 +0000799 // Emit an error if an address space was applied to decl with local storage.
800 // This includes arrays of objects with address space qualifiers, but not
801 // automatic variables that point to other address spaces.
802 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +0000803 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
804 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
805 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +0000806 }
Steve Narofff8a09432008-01-09 23:34:55 +0000807 // Merge the decl with the existing one if appropriate. If the decl is
808 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000809 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000810 NewVD = MergeVarDecl(NewVD, PrevDecl);
811 if (NewVD == 0) return 0;
812 }
Chris Lattner4b009652007-07-25 00:24:17 +0000813 New = NewVD;
814 }
815
816 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000817 if (II)
818 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000819 // If any semantic error occurred, mark the decl as invalid.
820 if (D.getInvalidType() || InvalidDecl)
821 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000822
823 return New;
824}
825
Eli Friedman02c22ce2008-05-20 13:48:25 +0000826bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
827 switch (Init->getStmtClass()) {
828 default:
829 Diag(Init->getExprLoc(),
830 diag::err_init_element_not_constant, Init->getSourceRange());
831 return true;
832 case Expr::ParenExprClass: {
833 const ParenExpr* PE = cast<ParenExpr>(Init);
834 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
835 }
836 case Expr::CompoundLiteralExprClass:
837 return cast<CompoundLiteralExpr>(Init)->isFileScope();
838 case Expr::DeclRefExprClass: {
839 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +0000840 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
841 if (VD->hasGlobalStorage())
842 return false;
843 Diag(Init->getExprLoc(),
844 diag::err_init_element_not_constant, Init->getSourceRange());
845 return true;
846 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000847 if (isa<FunctionDecl>(D))
848 return false;
849 Diag(Init->getExprLoc(),
850 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Narofff0b23542008-01-10 22:15:12 +0000851 return true;
852 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000853 case Expr::MemberExprClass: {
854 const MemberExpr *M = cast<MemberExpr>(Init);
855 if (M->isArrow())
856 return CheckAddressConstantExpression(M->getBase());
857 return CheckAddressConstantExpressionLValue(M->getBase());
858 }
859 case Expr::ArraySubscriptExprClass: {
860 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
861 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
862 return CheckAddressConstantExpression(ASE->getBase()) ||
863 CheckArithmeticConstantExpression(ASE->getIdx());
864 }
865 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +0000866 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +0000867 return false;
868 case Expr::UnaryOperatorClass: {
869 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
870
871 // C99 6.6p9
872 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +0000873 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +0000874
875 Diag(Init->getExprLoc(),
876 diag::err_init_element_not_constant, Init->getSourceRange());
877 return true;
878 }
879 }
880}
881
882bool Sema::CheckAddressConstantExpression(const Expr* Init) {
883 switch (Init->getStmtClass()) {
884 default:
885 Diag(Init->getExprLoc(),
886 diag::err_init_element_not_constant, Init->getSourceRange());
887 return true;
888 case Expr::ParenExprClass: {
889 const ParenExpr* PE = cast<ParenExpr>(Init);
890 return CheckAddressConstantExpression(PE->getSubExpr());
891 }
892 case Expr::StringLiteralClass:
893 case Expr::ObjCStringLiteralClass:
894 return false;
895 case Expr::CallExprClass: {
896 const CallExpr *CE = cast<CallExpr>(Init);
897 if (CE->isBuiltinConstantExpr())
898 return false;
899 Diag(Init->getExprLoc(),
900 diag::err_init_element_not_constant, Init->getSourceRange());
901 return true;
902 }
903 case Expr::UnaryOperatorClass: {
904 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
905
906 // C99 6.6p9
907 if (Exp->getOpcode() == UnaryOperator::AddrOf)
908 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
909
910 if (Exp->getOpcode() == UnaryOperator::Extension)
911 return CheckAddressConstantExpression(Exp->getSubExpr());
912
913 Diag(Init->getExprLoc(),
914 diag::err_init_element_not_constant, Init->getSourceRange());
915 return true;
916 }
917 case Expr::BinaryOperatorClass: {
918 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
919 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
920
921 Expr *PExp = Exp->getLHS();
922 Expr *IExp = Exp->getRHS();
923 if (IExp->getType()->isPointerType())
924 std::swap(PExp, IExp);
925
926 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
927 return CheckAddressConstantExpression(PExp) ||
928 CheckArithmeticConstantExpression(IExp);
929 }
Eli Friedman1fad3c62008-08-25 20:46:57 +0000930 case Expr::ImplicitCastExprClass:
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +0000931 case Expr::ExplicitCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +0000932 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +0000933 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
934 // Check for implicit promotion
935 if (SubExpr->getType()->isFunctionType() ||
936 SubExpr->getType()->isArrayType())
937 return CheckAddressConstantExpressionLValue(SubExpr);
938 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000939
940 // Check for pointer->pointer cast
941 if (SubExpr->getType()->isPointerType())
942 return CheckAddressConstantExpression(SubExpr);
943
Eli Friedman1fad3c62008-08-25 20:46:57 +0000944 if (SubExpr->getType()->isIntegralType()) {
945 // Check for the special-case of a pointer->int->pointer cast;
946 // this isn't standard, but some code requires it. See
947 // PR2720 for an example.
948 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
949 if (SubCast->getSubExpr()->getType()->isPointerType()) {
950 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
951 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
952 if (IntWidth >= PointerWidth) {
953 return CheckAddressConstantExpression(SubCast->getSubExpr());
954 }
955 }
956 }
957 }
958 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +0000959 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +0000960 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000961
962 Diag(Init->getExprLoc(),
963 diag::err_init_element_not_constant, Init->getSourceRange());
964 return true;
965 }
966 case Expr::ConditionalOperatorClass: {
967 // FIXME: Should we pedwarn here?
968 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
969 if (!Exp->getCond()->getType()->isArithmeticType()) {
970 Diag(Init->getExprLoc(),
971 diag::err_init_element_not_constant, Init->getSourceRange());
972 return true;
973 }
974 if (CheckArithmeticConstantExpression(Exp->getCond()))
975 return true;
976 if (Exp->getLHS() &&
977 CheckAddressConstantExpression(Exp->getLHS()))
978 return true;
979 return CheckAddressConstantExpression(Exp->getRHS());
980 }
981 case Expr::AddrLabelExprClass:
982 return false;
983 }
984}
985
Eli Friedman998dffb2008-06-09 05:05:07 +0000986static const Expr* FindExpressionBaseAddress(const Expr* E);
987
988static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
989 switch (E->getStmtClass()) {
990 default:
991 return E;
992 case Expr::ParenExprClass: {
993 const ParenExpr* PE = cast<ParenExpr>(E);
994 return FindExpressionBaseAddressLValue(PE->getSubExpr());
995 }
996 case Expr::MemberExprClass: {
997 const MemberExpr *M = cast<MemberExpr>(E);
998 if (M->isArrow())
999 return FindExpressionBaseAddress(M->getBase());
1000 return FindExpressionBaseAddressLValue(M->getBase());
1001 }
1002 case Expr::ArraySubscriptExprClass: {
1003 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1004 return FindExpressionBaseAddress(ASE->getBase());
1005 }
1006 case Expr::UnaryOperatorClass: {
1007 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1008
1009 if (Exp->getOpcode() == UnaryOperator::Deref)
1010 return FindExpressionBaseAddress(Exp->getSubExpr());
1011
1012 return E;
1013 }
1014 }
1015}
1016
1017static const Expr* FindExpressionBaseAddress(const Expr* E) {
1018 switch (E->getStmtClass()) {
1019 default:
1020 return E;
1021 case Expr::ParenExprClass: {
1022 const ParenExpr* PE = cast<ParenExpr>(E);
1023 return FindExpressionBaseAddress(PE->getSubExpr());
1024 }
1025 case Expr::UnaryOperatorClass: {
1026 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1027
1028 // C99 6.6p9
1029 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1030 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1031
1032 if (Exp->getOpcode() == UnaryOperator::Extension)
1033 return FindExpressionBaseAddress(Exp->getSubExpr());
1034
1035 return E;
1036 }
1037 case Expr::BinaryOperatorClass: {
1038 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1039
1040 Expr *PExp = Exp->getLHS();
1041 Expr *IExp = Exp->getRHS();
1042 if (IExp->getType()->isPointerType())
1043 std::swap(PExp, IExp);
1044
1045 return FindExpressionBaseAddress(PExp);
1046 }
1047 case Expr::ImplicitCastExprClass: {
1048 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1049
1050 // Check for implicit promotion
1051 if (SubExpr->getType()->isFunctionType() ||
1052 SubExpr->getType()->isArrayType())
1053 return FindExpressionBaseAddressLValue(SubExpr);
1054
1055 // Check for pointer->pointer cast
1056 if (SubExpr->getType()->isPointerType())
1057 return FindExpressionBaseAddress(SubExpr);
1058
1059 // We assume that we have an arithmetic expression here;
1060 // if we don't, we'll figure it out later
1061 return 0;
1062 }
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001063 case Expr::ExplicitCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001064 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1065
1066 // Check for pointer->pointer cast
1067 if (SubExpr->getType()->isPointerType())
1068 return FindExpressionBaseAddress(SubExpr);
1069
1070 // We assume that we have an arithmetic expression here;
1071 // if we don't, we'll figure it out later
1072 return 0;
1073 }
1074 }
1075}
1076
Eli Friedman02c22ce2008-05-20 13:48:25 +00001077bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1078 switch (Init->getStmtClass()) {
1079 default:
1080 Diag(Init->getExprLoc(),
1081 diag::err_init_element_not_constant, Init->getSourceRange());
1082 return true;
1083 case Expr::ParenExprClass: {
1084 const ParenExpr* PE = cast<ParenExpr>(Init);
1085 return CheckArithmeticConstantExpression(PE->getSubExpr());
1086 }
1087 case Expr::FloatingLiteralClass:
1088 case Expr::IntegerLiteralClass:
1089 case Expr::CharacterLiteralClass:
1090 case Expr::ImaginaryLiteralClass:
1091 case Expr::TypesCompatibleExprClass:
1092 case Expr::CXXBoolLiteralExprClass:
1093 return false;
1094 case Expr::CallExprClass: {
1095 const CallExpr *CE = cast<CallExpr>(Init);
1096 if (CE->isBuiltinConstantExpr())
1097 return false;
1098 Diag(Init->getExprLoc(),
1099 diag::err_init_element_not_constant, Init->getSourceRange());
1100 return true;
1101 }
1102 case Expr::DeclRefExprClass: {
1103 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1104 if (isa<EnumConstantDecl>(D))
1105 return false;
1106 Diag(Init->getExprLoc(),
1107 diag::err_init_element_not_constant, Init->getSourceRange());
1108 return true;
1109 }
1110 case Expr::CompoundLiteralExprClass:
1111 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1112 // but vectors are allowed to be magic.
1113 if (Init->getType()->isVectorType())
1114 return false;
1115 Diag(Init->getExprLoc(),
1116 diag::err_init_element_not_constant, Init->getSourceRange());
1117 return true;
1118 case Expr::UnaryOperatorClass: {
1119 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1120
1121 switch (Exp->getOpcode()) {
1122 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1123 // See C99 6.6p3.
1124 default:
1125 Diag(Init->getExprLoc(),
1126 diag::err_init_element_not_constant, Init->getSourceRange());
1127 return true;
1128 case UnaryOperator::SizeOf:
1129 case UnaryOperator::AlignOf:
1130 case UnaryOperator::OffsetOf:
1131 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1132 // See C99 6.5.3.4p2 and 6.6p3.
1133 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1134 return false;
1135 Diag(Init->getExprLoc(),
1136 diag::err_init_element_not_constant, Init->getSourceRange());
1137 return true;
1138 case UnaryOperator::Extension:
1139 case UnaryOperator::LNot:
1140 case UnaryOperator::Plus:
1141 case UnaryOperator::Minus:
1142 case UnaryOperator::Not:
1143 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1144 }
1145 }
1146 case Expr::SizeOfAlignOfTypeExprClass: {
1147 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1148 // Special check for void types, which are allowed as an extension
1149 if (Exp->getArgumentType()->isVoidType())
1150 return false;
1151 // alignof always evaluates to a constant.
1152 // FIXME: is sizeof(int[3.0]) a constant expression?
1153 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1154 Diag(Init->getExprLoc(),
1155 diag::err_init_element_not_constant, Init->getSourceRange());
1156 return true;
1157 }
1158 return false;
1159 }
1160 case Expr::BinaryOperatorClass: {
1161 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1162
1163 if (Exp->getLHS()->getType()->isArithmeticType() &&
1164 Exp->getRHS()->getType()->isArithmeticType()) {
1165 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1166 CheckArithmeticConstantExpression(Exp->getRHS());
1167 }
1168
Eli Friedman998dffb2008-06-09 05:05:07 +00001169 if (Exp->getLHS()->getType()->isPointerType() &&
1170 Exp->getRHS()->getType()->isPointerType()) {
1171 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1172 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1173
1174 // Only allow a null (constant integer) base; we could
1175 // allow some additional cases if necessary, but this
1176 // is sufficient to cover offsetof-like constructs.
1177 if (!LHSBase && !RHSBase) {
1178 return CheckAddressConstantExpression(Exp->getLHS()) ||
1179 CheckAddressConstantExpression(Exp->getRHS());
1180 }
1181 }
1182
Eli Friedman02c22ce2008-05-20 13:48:25 +00001183 Diag(Init->getExprLoc(),
1184 diag::err_init_element_not_constant, Init->getSourceRange());
1185 return true;
1186 }
1187 case Expr::ImplicitCastExprClass:
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001188 case Expr::ExplicitCastExprClass: {
1189 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman02c22ce2008-05-20 13:48:25 +00001190 if (SubExpr->getType()->isArithmeticType())
1191 return CheckArithmeticConstantExpression(SubExpr);
1192
1193 Diag(Init->getExprLoc(),
1194 diag::err_init_element_not_constant, Init->getSourceRange());
1195 return true;
1196 }
1197 case Expr::ConditionalOperatorClass: {
1198 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1199 if (CheckArithmeticConstantExpression(Exp->getCond()))
1200 return true;
1201 if (Exp->getLHS() &&
1202 CheckArithmeticConstantExpression(Exp->getLHS()))
1203 return true;
1204 return CheckArithmeticConstantExpression(Exp->getRHS());
1205 }
1206 }
1207}
1208
1209bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopese7280452008-07-07 16:46:50 +00001210 Init = Init->IgnoreParens();
1211
Eli Friedman02c22ce2008-05-20 13:48:25 +00001212 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1213 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1214 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1215
Nuno Lopese7280452008-07-07 16:46:50 +00001216 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1217 return CheckForConstantInitializer(e->getInitializer(), DclT);
1218
Eli Friedman02c22ce2008-05-20 13:48:25 +00001219 if (Init->getType()->isReferenceType()) {
1220 // FIXME: Work out how the heck reference types work
1221 return false;
1222#if 0
1223 // A reference is constant if the address of the expression
1224 // is constant
1225 // We look through initlists here to simplify
1226 // CheckAddressConstantExpressionLValue.
1227 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1228 assert(Exp->getNumInits() > 0 &&
1229 "Refernce initializer cannot be empty");
1230 Init = Exp->getInit(0);
1231 }
1232 return CheckAddressConstantExpressionLValue(Init);
1233#endif
1234 }
1235
1236 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1237 unsigned numInits = Exp->getNumInits();
1238 for (unsigned i = 0; i < numInits; i++) {
1239 // FIXME: Need to get the type of the declaration for C++,
1240 // because it could be a reference?
1241 if (CheckForConstantInitializer(Exp->getInit(i),
1242 Exp->getInit(i)->getType()))
1243 return true;
1244 }
1245 return false;
1246 }
1247
1248 if (Init->isNullPointerConstant(Context))
1249 return false;
1250 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001251 QualType InitTy = Context.getCanonicalType(Init->getType())
1252 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00001253 if (InitTy == Context.BoolTy) {
1254 // Special handling for pointers implicitly cast to bool;
1255 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1256 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1257 Expr* SubE = ICE->getSubExpr();
1258 if (SubE->getType()->isPointerType() ||
1259 SubE->getType()->isArrayType() ||
1260 SubE->getType()->isFunctionType()) {
1261 return CheckAddressConstantExpression(Init);
1262 }
1263 }
1264 } else if (InitTy->isIntegralType()) {
1265 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001266 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00001267 SubE = CE->getSubExpr();
1268 // Special check for pointer cast to int; we allow as an extension
1269 // an address constant cast to an integer if the integer
1270 // is of an appropriate width (this sort of code is apparently used
1271 // in some places).
1272 // FIXME: Add pedwarn?
1273 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1274 if (SubE && (SubE->getType()->isPointerType() ||
1275 SubE->getType()->isArrayType() ||
1276 SubE->getType()->isFunctionType())) {
1277 unsigned IntWidth = Context.getTypeSize(Init->getType());
1278 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1279 if (IntWidth >= PointerWidth)
1280 return CheckAddressConstantExpression(Init);
1281 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001282 }
1283
1284 return CheckArithmeticConstantExpression(Init);
1285 }
1286
1287 if (Init->getType()->isPointerType())
1288 return CheckAddressConstantExpression(Init);
1289
Eli Friedman25086f02008-05-30 18:14:48 +00001290 // An array type at the top level that isn't an init-list must
1291 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001292 if (Init->getType()->isArrayType())
1293 return false;
1294
1295 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1296 Init->getSourceRange());
1297 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001298}
1299
Steve Naroff6a0e2092007-09-12 14:07:44 +00001300void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001301 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001302 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001303 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001304
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001305 // If there is no declaration, there was an error parsing it. Just ignore
1306 // the initializer.
1307 if (RealDecl == 0) {
1308 delete Init;
1309 return;
1310 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001311
Steve Naroff420d0f52007-09-12 20:13:48 +00001312 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1313 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001314 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1315 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001316 RealDecl->setInvalidDecl();
1317 return;
1318 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001319 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001320 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001321 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001322 if (VDecl->isBlockVarDecl()) {
1323 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001324 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001325 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001326 VDecl->setInvalidDecl();
1327 } else if (!VDecl->isInvalidDecl()) {
Steve Narofff3cb5142008-01-25 00:51:06 +00001328 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001329 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00001330
1331 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1332 if (!getLangOptions().CPlusPlus) {
1333 if (SC == VarDecl::Static) // C99 6.7.8p4.
1334 CheckForConstantInitializer(Init, DclT);
1335 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001336 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001337 } else if (VDecl->isFileVarDecl()) {
1338 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001339 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001340 if (!VDecl->isInvalidDecl())
Steve Narofff3cb5142008-01-25 00:51:06 +00001341 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001342 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001343
Anders Carlssonea7140a2008-08-22 05:00:02 +00001344 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1345 if (!getLangOptions().CPlusPlus) {
1346 // C99 6.7.8p4. All file scoped initializers need to be constant.
1347 CheckForConstantInitializer(Init, DclT);
1348 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001349 }
1350 // If the type changed, it means we had an incomplete type that was
1351 // completed by the initializer. For example:
1352 // int ary[] = { 1, 3, 5 };
1353 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001354 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001355 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001356 Init->setType(DclT);
1357 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001358
1359 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001360 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001361 return;
1362}
1363
Chris Lattner4b009652007-07-25 00:24:17 +00001364/// The declarators are chained together backwards, reverse the list.
1365Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1366 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001367 Decl *GroupDecl = static_cast<Decl*>(group);
1368 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00001369 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00001370
1371 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1372 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001373 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00001374 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001375 else { // reverse the list.
1376 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001377 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001378 Group->setNextDeclarator(NewGroup);
1379 NewGroup = Group;
1380 Group = Next;
1381 }
1382 }
1383 // Perform semantic analysis that depends on having fully processed both
1384 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001385 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001386 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1387 if (!IDecl)
1388 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001389 QualType T = IDecl->getType();
1390
1391 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1392 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001393 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1394 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001395 if (T->isVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001396 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1397 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001398 }
1399 }
1400 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1401 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001402 if (IDecl->isBlockVarDecl() &&
1403 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001404 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001405 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1406 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001407 IDecl->setInvalidDecl();
1408 }
1409 }
1410 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1411 // object that has file scope without an initializer, and without a
1412 // storage-class specifier or with the storage-class specifier "static",
1413 // constitutes a tentative definition. Note: A tentative definition with
1414 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00001415 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001416 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001417 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1418 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001419 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001420 // C99 6.9.2p3: If the declaration of an identifier for an object is
1421 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1422 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001423 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1424 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001425 IDecl->setInvalidDecl();
1426 }
1427 }
Steve Naroffb5e78152008-08-08 17:50:35 +00001428 if (IDecl->isFileVarDecl())
1429 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001430 }
1431 return NewGroup;
1432}
Steve Naroff91b03f72007-08-28 03:03:08 +00001433
Chris Lattner3e254fb2008-04-08 04:40:51 +00001434/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1435/// to introduce parameters into function prototype scope.
1436Sema::DeclTy *
1437Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00001438 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001439
1440 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1441 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1442 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1443 Diag(DS.getStorageClassSpecLoc(),
1444 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001445 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001446 }
1447 if (DS.isThreadSpecified()) {
1448 Diag(DS.getThreadSpecLoc(),
1449 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001450 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001451 }
1452
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001453 // Check that there are no default arguments inside the type of this
1454 // parameter (C++ only).
1455 if (getLangOptions().CPlusPlus)
1456 CheckExtraCXXDefaultArguments(D);
1457
Chris Lattner3e254fb2008-04-08 04:40:51 +00001458 // In this context, we *do not* check D.getInvalidType(). If the declarator
1459 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1460 // though it will not reflect the user specified type.
1461 QualType parmDeclType = GetTypeForDeclarator(D, S);
1462
1463 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1464
Chris Lattner4b009652007-07-25 00:24:17 +00001465 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1466 // Can this happen for params? We already checked that they don't conflict
1467 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001468 IdentifierInfo *II = D.getIdentifier();
1469 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1470 if (S->isDeclScope(PrevDecl)) {
1471 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1472 dyn_cast<NamedDecl>(PrevDecl)->getName());
1473
1474 // Recover by removing the name
1475 II = 0;
1476 D.SetIdentifier(0, D.getIdentifierLoc());
1477 }
Chris Lattner4b009652007-07-25 00:24:17 +00001478 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001479
1480 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1481 // Doing the promotion here has a win and a loss. The win is the type for
1482 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1483 // code generator). The loss is the orginal type isn't preserved. For example:
1484 //
1485 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1486 // int blockvardecl[5];
1487 // sizeof(parmvardecl); // size == 4
1488 // sizeof(blockvardecl); // size == 20
1489 // }
1490 //
1491 // For expressions, all implicit conversions are captured using the
1492 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1493 //
1494 // FIXME: If a source translation tool needs to see the original type, then
1495 // we need to consider storing both types (in ParmVarDecl)...
1496 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001497 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001498 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001499 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001500 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001501 parmDeclType = Context.getPointerType(parmDeclType);
1502
Chris Lattner3e254fb2008-04-08 04:40:51 +00001503 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1504 D.getIdentifierLoc(), II,
1505 parmDeclType, VarDecl::None,
1506 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001507
Chris Lattner3e254fb2008-04-08 04:40:51 +00001508 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001509 New->setInvalidDecl();
1510
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001511 if (II)
1512 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001513
Chris Lattner9b384ca2008-06-29 00:02:00 +00001514 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00001515 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001516
Chris Lattner4b009652007-07-25 00:24:17 +00001517}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001518
Chris Lattnerea148702007-10-09 17:14:05 +00001519Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001520 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00001521 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1522 "Not a function declarator!");
1523 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001524
Chris Lattner4b009652007-07-25 00:24:17 +00001525 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1526 // for a K&R function.
1527 if (!FTI.hasPrototype) {
1528 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001529 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001530 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1531 FTI.ArgInfo[i].Ident->getName());
1532 // Implicitly declare the argument as type 'int' for lack of a better
1533 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001534 DeclSpec DS;
1535 const char* PrevSpec; // unused
1536 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1537 PrevSpec);
1538 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1539 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1540 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00001541 }
1542 }
Chris Lattnerec9361f2008-02-17 19:31:09 +00001543
Chris Lattner4b009652007-07-25 00:24:17 +00001544 // Since this is a function definition, act as though we have information
1545 // about the arguments.
Chris Lattnerec9361f2008-02-17 19:31:09 +00001546 if (FTI.NumArgs)
1547 FTI.hasPrototype = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001548 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001549 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00001550 }
1551
1552 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001553
1554 // See if this is a redefinition.
Steve Naroffe57c21a2008-04-01 23:04:06 +00001555 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroff6384a012008-04-02 14:35:35 +00001556 GlobalScope);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001557 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1558 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1559 const FunctionDecl *Definition;
1560 if (FD->getBody(Definition)) {
1561 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1562 D.getIdentifier()->getName());
1563 Diag(Definition->getLocation(), diag::err_previous_definition);
1564 }
Steve Naroff1d5bd642008-01-14 20:51:29 +00001565 }
1566 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001567
1568 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001569 ActOnDeclarator(GlobalScope, D, 0));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001570}
1571
1572Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1573 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00001574 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001575 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001576
1577 // Check the validity of our function parameters
1578 CheckParmsForFunctionDef(FD);
1579
1580 // Introduce our parameters into the function scope
1581 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1582 ParmVarDecl *Param = FD->getParamDecl(p);
1583 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001584 if (Param->getIdentifier())
1585 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001586 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001587
Chris Lattner4b009652007-07-25 00:24:17 +00001588 return FD;
1589}
1590
Steve Naroff99ee4302007-11-11 23:20:51 +00001591Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1592 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001593 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001594 FD->setBody((Stmt*)Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001595 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00001596 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001597 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001598 } else
1599 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001600 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00001601 // Verify and clean out per-function state.
1602
1603 // Check goto/label use.
1604 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1605 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1606 // Verify that we have no forward references left. If so, there was a goto
1607 // or address of a label taken, but no definition of it. Label fwd
1608 // definitions are indicated with a null substmt.
1609 if (I->second->getSubStmt() == 0) {
1610 LabelStmt *L = I->second;
1611 // Emit error.
1612 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1613
1614 // At this point, we have gotos that use the bogus label. Stitch it into
1615 // the function body so that they aren't leaked and that the AST is well
1616 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001617 if (Body) {
1618 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1619 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1620 } else {
1621 // The whole function wasn't parsed correctly, just delete this.
1622 delete L;
1623 }
Chris Lattner4b009652007-07-25 00:24:17 +00001624 }
1625 }
1626 LabelMap.clear();
1627
Steve Naroff99ee4302007-11-11 23:20:51 +00001628 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001629}
1630
Chris Lattner4b009652007-07-25 00:24:17 +00001631/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1632/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001633ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1634 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001635 // Extension in C99. Legal in C90, but warn about it.
1636 if (getLangOptions().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00001637 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001638 else
Chris Lattner4b009652007-07-25 00:24:17 +00001639 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1640
1641 // FIXME: handle stuff like:
1642 // void foo() { extern float X(); }
1643 // void bar() { X(); } <-- implicit decl for X in another scope.
1644
1645 // Set a Declarator for the implicit definition: int foo();
1646 const char *Dummy;
1647 DeclSpec DS;
1648 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1649 Error = Error; // Silence warning.
1650 assert(!Error && "Error setting up implicit decl!");
1651 Declarator D(DS, Declarator::BlockContext);
1652 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1653 D.SetIdentifier(&II, Loc);
1654
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001655 // Insert this function into translation-unit scope.
1656
1657 DeclContext *PrevDC = CurContext;
1658 CurContext = Context.getTranslationUnitDecl();
1659
Steve Naroff9104f3c2008-04-04 14:32:09 +00001660 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001661 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00001662 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001663
1664 CurContext = PrevDC;
1665
Steve Naroff9104f3c2008-04-04 14:32:09 +00001666 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00001667}
1668
1669
Chris Lattner82bb4792007-11-14 06:34:38 +00001670TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001671 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001672 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001673 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001674
1675 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00001676 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1677 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00001678 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00001679 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001680 if (D.getInvalidType())
1681 NewTD->setInvalidDecl();
1682 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001683}
1684
Steve Naroff0acc9c92007-09-15 18:49:24 +00001685/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001686/// former case, Name will be non-null. In the later case, Name will be null.
1687/// TagType indicates what kind of tag this is. TK indicates whether this is a
1688/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001689Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001690 SourceLocation KWLoc, IdentifierInfo *Name,
1691 SourceLocation NameLoc, AttributeList *Attr) {
1692 // If this is a use of an existing tag, it must have a name.
1693 assert((Name != 0 || TK == TK_Definition) &&
1694 "Nameless record must be a definition!");
1695
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001696 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00001697 switch (TagType) {
1698 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001699 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1700 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1701 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1702 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001703 }
1704
1705 // If this is a named struct, check to see if there was a previous forward
1706 // declaration or definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001707 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1708 if (ScopedDecl *PrevDecl =
1709 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Chris Lattner4b009652007-07-25 00:24:17 +00001710
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001711 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1712 "unexpected Decl type");
1713 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001714 // If this is a use of a previous tag, or if the tag is already declared
1715 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001716 // rementions the tag), reuse the decl.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001717 if (TK == TK_Reference ||
1718 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001719 // Make sure that this wasn't declared as an enum and now used as a
1720 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001721 if (PrevTagDecl->getTagKind() != Kind) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001722 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1723 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001724 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001725 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001726 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001727 } else {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001728 // If this is a use or a forward declaration, we're good.
1729 if (TK != TK_Definition)
1730 return PrevDecl;
1731
1732 // Diagnose attempts to redefine a tag.
1733 if (PrevTagDecl->isDefinition()) {
1734 Diag(NameLoc, diag::err_redefinition, Name->getName());
1735 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1736 // If this is a redefinition, recover by making this struct be
1737 // anonymous, which will make any later references get the previous
1738 // definition.
1739 Name = 0;
1740 } else {
1741 // Okay, this is definition of a previously declared or referenced
1742 // tag. Move the location of the decl to be the definition site.
1743 PrevDecl->setLocation(NameLoc);
1744 return PrevDecl;
1745 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001746 }
Chris Lattner4b009652007-07-25 00:24:17 +00001747 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001748 // If we get here, this is a definition of a new struct type in a nested
1749 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1750 // type.
1751 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00001752 // PrevDecl is a namespace.
1753 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1754 // The tag name clashes with a namespace name, issue an error and recover
1755 // by making this tag be anonymous.
1756 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1757 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1758 Name = 0;
1759 }
Chris Lattner4b009652007-07-25 00:24:17 +00001760 }
Chris Lattner4b009652007-07-25 00:24:17 +00001761 }
1762
1763 // If there is an identifier, use the location of the identifier as the
1764 // location of the decl, otherwise use the location of the struct/union
1765 // keyword.
1766 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1767
1768 // Otherwise, if this is the first time we've seen this tag, create the decl.
1769 TagDecl *New;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001770 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00001771 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1772 // enum X { A, B, C } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001773 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001774 // If this is an undefined enum, warn.
1775 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001776 } else {
1777 // struct/union/class
1778
Chris Lattner4b009652007-07-25 00:24:17 +00001779 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1780 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001781 if (getLangOptions().CPlusPlus)
1782 // FIXME: Look for a way to use RecordDecl for simple structs.
1783 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1784 else
1785 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1786 }
Chris Lattner4b009652007-07-25 00:24:17 +00001787
1788 // If this has an identifier, add it to the scope stack.
1789 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001790 // The scope passed in may not be a decl scope. Zip up the scope tree until
1791 // we find one that is.
1792 while ((S->getFlags() & Scope::DeclScope) == 0)
1793 S = S->getParent();
1794
1795 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001796 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00001797 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00001798
Chris Lattnerd7e83d82008-06-28 23:58:55 +00001799 if (Attr)
1800 ProcessDeclAttributeList(New, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00001801 return New;
1802}
1803
Chris Lattner1bf58f62008-06-21 19:39:06 +00001804/// Collect the instance variables declared in an Objective-C object. Used in
1805/// the creation of structures from objects using the @defs directive.
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001806static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattnere705e5e2008-07-21 22:17:28 +00001807 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00001808 if (Class->getSuperClass())
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001809 CollectIvars(Class->getSuperClass(), Ctx, ivars);
1810
1811 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1812 for (ObjCInterfaceDecl::ivar_iterator I=Class->ivar_begin(), E=Class->ivar_end();
1813 I!=E; ++I) {
1814
1815 ObjCIvarDecl* ID = *I;
1816 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
1817 ID->getIdentifier(),
1818 ID->getType(),
1819 ID->getBitWidth()));
1820 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00001821}
1822
1823/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1824/// instance variables of ClassName into Decls.
1825void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1826 IdentifierInfo *ClassName,
Chris Lattnere705e5e2008-07-21 22:17:28 +00001827 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00001828 // Check that ClassName is a valid class
1829 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1830 if (!Class) {
1831 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1832 return;
1833 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00001834 // Collect the instance variables
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001835 CollectIvars(Class, Context, Decls);
Chris Lattner1bf58f62008-06-21 19:39:06 +00001836}
1837
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001838QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1839 // This method tries to turn a variable array into a constant
1840 // array even when the size isn't an ICE. This is necessary
1841 // for compatibility with code that depends on gcc's buggy
1842 // constant expression folding, like struct {char x[(int)(char*)2];}
1843 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc7436af2008-07-03 04:20:39 +00001844 APValue Result;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001845 if (VLATy->getSizeExpr() &&
Chris Lattner334b1942008-07-11 19:19:21 +00001846 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
1847 llvm::APSInt &Res = Result.getInt();
1848 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1849 return Context.getConstantArrayType(VLATy->getElementType(),
1850 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001851 }
1852 }
1853 return QualType();
1854}
1855
Steve Naroff0acc9c92007-09-15 18:49:24 +00001856/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001857/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001858Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00001859 SourceLocation DeclStart,
1860 Declarator &D, ExprTy *BitfieldWidth) {
1861 IdentifierInfo *II = D.getIdentifier();
1862 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001863 SourceLocation Loc = DeclStart;
1864 if (II) Loc = D.getIdentifierLoc();
1865
1866 // FIXME: Unnamed fields can be handled in various different ways, for
1867 // example, unnamed unions inject all members into the struct namespace!
1868
1869
1870 if (BitWidth) {
1871 // TODO: Validate.
1872 //printf("WARNING: BITFIELDS IGNORED!\n");
1873
1874 // 6.7.2.1p3
1875 // 6.7.2.1p4
1876
1877 } else {
1878 // Not a bitfield.
1879
1880 // validate II.
1881
1882 }
1883
1884 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001885 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1886 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001887
Chris Lattner4b009652007-07-25 00:24:17 +00001888 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1889 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00001890 if (T->isVariablyModifiedType()) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001891 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1892 if (!FixedTy.isNull()) {
1893 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1894 T = FixedTy;
1895 } else {
1896 // FIXME: This diagnostic needs work
1897 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1898 InvalidDecl = true;
1899 }
Chris Lattner4b009652007-07-25 00:24:17 +00001900 }
Chris Lattner4b009652007-07-25 00:24:17 +00001901 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001902 FieldDecl *NewFD;
1903
1904 if (getLangOptions().CPlusPlus) {
1905 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
1906 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
1907 Loc, II, T, BitWidth);
1908 if (II)
1909 PushOnScopeChains(NewFD, S);
1910 }
1911 else
1912 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00001913
Chris Lattner9b384ca2008-06-29 00:02:00 +00001914 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00001915
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001916 if (D.getInvalidType() || InvalidDecl)
1917 NewFD->setInvalidDecl();
1918 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001919}
1920
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001921/// TranslateIvarVisibility - Translate visibility from a token ID to an
1922/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00001923static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001924TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001925 switch (ivarVisibility) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001926 case tok::objc_private: return ObjCIvarDecl::Private;
1927 case tok::objc_public: return ObjCIvarDecl::Public;
1928 case tok::objc_protected: return ObjCIvarDecl::Protected;
1929 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001930 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001931 }
1932}
1933
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001934/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1935/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001936Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001937 SourceLocation DeclStart,
1938 Declarator &D, ExprTy *BitfieldWidth,
1939 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001940 IdentifierInfo *II = D.getIdentifier();
1941 Expr *BitWidth = (Expr*)BitfieldWidth;
1942 SourceLocation Loc = DeclStart;
1943 if (II) Loc = D.getIdentifierLoc();
1944
1945 // FIXME: Unnamed fields can be handled in various different ways, for
1946 // example, unnamed unions inject all members into the struct namespace!
1947
1948
1949 if (BitWidth) {
1950 // TODO: Validate.
1951 //printf("WARNING: BITFIELDS IGNORED!\n");
1952
1953 // 6.7.2.1p3
1954 // 6.7.2.1p4
1955
1956 } else {
1957 // Not a bitfield.
1958
1959 // validate II.
1960
1961 }
1962
1963 QualType T = GetTypeForDeclarator(D, S);
1964 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1965 bool InvalidDecl = false;
1966
1967 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1968 // than a variably modified type.
1969 if (T->isVariablyModifiedType()) {
1970 // FIXME: This diagnostic needs work
1971 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1972 InvalidDecl = true;
1973 }
1974
Ted Kremenek173dd312008-07-23 18:04:17 +00001975 // Get the visibility (access control) for this ivar.
1976 ObjCIvarDecl::AccessControl ac =
1977 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
1978 : ObjCIvarDecl::None;
1979
1980 // Construct the decl.
1981 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00001982 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001983
Ted Kremenek173dd312008-07-23 18:04:17 +00001984 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00001985 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001986
1987 if (D.getInvalidType() || InvalidDecl)
1988 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00001989
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001990 return NewID;
1991}
1992
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001993void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001994 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001995 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001996 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001997 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1998 assert(EnclosingDecl && "missing record or interface decl");
1999 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2000
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002001 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002002 // Diagnose code like:
2003 // struct S { struct S {} X; };
2004 // We discover this when we complete the outer S. Reject and ignore the
2005 // outer S.
2006 Diag(Record->getLocation(), diag::err_nested_redefinition,
2007 Record->getKindName());
2008 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002009 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002010 return;
2011 }
Chris Lattner4b009652007-07-25 00:24:17 +00002012 // Verify that all the fields are okay.
2013 unsigned NumNamedMembers = 0;
2014 llvm::SmallVector<FieldDecl*, 32> RecFields;
2015 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00002016
Chris Lattner4b009652007-07-25 00:24:17 +00002017 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002018
Steve Naroff9bb759f2007-09-14 22:20:54 +00002019 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2020 assert(FD && "missing field decl");
2021
2022 // Remember all fields.
2023 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002024
2025 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002026 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002027
Chris Lattner4b009652007-07-25 00:24:17 +00002028 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002029 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002030 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00002031 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002032 FD->setInvalidDecl();
2033 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002034 continue;
2035 }
Chris Lattner4b009652007-07-25 00:24:17 +00002036 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2037 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002038 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002039 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002040 FD->setInvalidDecl();
2041 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002042 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002043 }
Chris Lattner4b009652007-07-25 00:24:17 +00002044 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002045 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002046 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00002047 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002048 FD->setInvalidDecl();
2049 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002050 continue;
2051 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002052 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00002053 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2054 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002055 FD->setInvalidDecl();
2056 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002057 continue;
2058 }
Chris Lattner4b009652007-07-25 00:24:17 +00002059 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002060 if (Record)
2061 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002062 }
Chris Lattner4b009652007-07-25 00:24:17 +00002063 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2064 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002065 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002066 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2067 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002068 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002069 Record->setHasFlexibleArrayMember(true);
2070 } else {
2071 // If this is a struct/class and this is not the last element, reject
2072 // it. Note that GCC supports variable sized arrays in the middle of
2073 // structures.
2074 if (i != NumFields-1) {
2075 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2076 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002077 FD->setInvalidDecl();
2078 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002079 continue;
2080 }
Chris Lattner4b009652007-07-25 00:24:17 +00002081 // We support flexible arrays at the end of structs in other structs
2082 // as an extension.
2083 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2084 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002085 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002086 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002087 }
2088 }
2089 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002090 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002091 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002092 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2093 FD->getName());
2094 FD->setInvalidDecl();
2095 EnclosingDecl->setInvalidDecl();
2096 continue;
2097 }
Chris Lattner4b009652007-07-25 00:24:17 +00002098 // Keep track of the number of named members.
2099 if (IdentifierInfo *II = FD->getIdentifier()) {
2100 // Detect duplicate member names.
2101 if (!FieldIDs.insert(II)) {
2102 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2103 // Find the previous decl.
2104 SourceLocation PrevLoc;
2105 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2106 assert(i != e && "Didn't find previous def!");
2107 if (RecFields[i]->getIdentifier() == II) {
2108 PrevLoc = RecFields[i]->getLocation();
2109 break;
2110 }
2111 }
2112 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002113 FD->setInvalidDecl();
2114 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002115 continue;
2116 }
2117 ++NumNamedMembers;
2118 }
Chris Lattner4b009652007-07-25 00:24:17 +00002119 }
2120
Chris Lattner4b009652007-07-25 00:24:17 +00002121 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00002122 if (Record) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002123 Record->defineBody(&RecFields[0], RecFields.size());
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00002124 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2125 // Sema::ActOnFinishCXXClassDef.
2126 if (!isa<CXXRecordDecl>(Record))
2127 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002128 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002129 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2130 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2131 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2132 else if (ObjCImplementationDecl *IMPDecl =
2133 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002134 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2135 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00002136 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00002137 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00002138 }
Chris Lattner4b009652007-07-25 00:24:17 +00002139}
2140
Steve Naroff0acc9c92007-09-15 18:49:24 +00002141Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00002142 DeclTy *lastEnumConst,
2143 SourceLocation IdLoc, IdentifierInfo *Id,
2144 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00002145 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002146 EnumConstantDecl *LastEnumConst =
2147 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2148 Expr *Val = static_cast<Expr*>(val);
2149
Chris Lattnera7549902007-08-26 06:24:45 +00002150 // The scope passed in may not be a decl scope. Zip up the scope tree until
2151 // we find one that is.
2152 while ((S->getFlags() & Scope::DeclScope) == 0)
2153 S = S->getParent();
2154
Chris Lattner4b009652007-07-25 00:24:17 +00002155 // Verify that there isn't already something declared with this name in this
2156 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00002157 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00002158 // When in C++, we may get a TagDecl with the same name; in this case the
2159 // enum constant will 'hide' the tag.
2160 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2161 "Received TagDecl when not in C++!");
2162 if (!isa<TagDecl>(PrevDecl) &&
2163 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002164 if (isa<EnumConstantDecl>(PrevDecl))
2165 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2166 else
2167 Diag(IdLoc, diag::err_redefinition, Id->getName());
2168 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002169 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00002170 return 0;
2171 }
2172 }
2173
2174 llvm::APSInt EnumVal(32);
2175 QualType EltTy;
2176 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00002177 // Make sure to promote the operand type to int.
2178 UsualUnaryConversions(Val);
2179
Chris Lattner4b009652007-07-25 00:24:17 +00002180 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2181 SourceLocation ExpLoc;
2182 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2183 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2184 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002185 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00002186 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00002187 } else {
2188 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002189 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00002190 }
2191
2192 if (!Val) {
2193 if (LastEnumConst) {
2194 // Assign the last value + 1.
2195 EnumVal = LastEnumConst->getInitVal();
2196 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00002197
2198 // Check for overflow on increment.
2199 if (EnumVal < LastEnumConst->getInitVal())
2200 Diag(IdLoc, diag::warn_enum_value_overflow);
2201
Chris Lattnere7f53a42007-08-27 17:37:24 +00002202 EltTy = LastEnumConst->getType();
2203 } else {
2204 // First value, set to zero.
2205 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002206 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00002207 }
Chris Lattner4b009652007-07-25 00:24:17 +00002208 }
2209
Chris Lattnere4650482008-03-15 06:12:44 +00002210 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00002211 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2212 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00002213 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00002214
2215 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002216 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002217 return New;
2218}
2219
Steve Naroffb0726b82008-08-07 14:08:16 +00002220// FIXME: For consistency with ActOnFields(), we should have the parser
2221// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002222void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00002223 DeclTy **Elements, unsigned NumElements) {
2224 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattner4b009652007-07-25 00:24:17 +00002225
Steve Naroffb0726b82008-08-07 14:08:16 +00002226 if (Enum && Enum->isDefinition()) {
2227 // Diagnose code like:
2228 // enum e0 {
2229 // E0 = sizeof(enum e0 { E1 })
2230 // };
2231 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2232 Enum->getName());
2233 Diag(EnumLoc, diag::err_previous_definition);
2234 Enum->setInvalidDecl();
2235 return;
2236 }
Chris Lattner435c3fd2007-08-28 05:10:31 +00002237 // TODO: If the result value doesn't fit in an int, it must be a long or long
2238 // long value. ISO C does not support this, but GCC does as an extension,
2239 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002240 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00002241
Chris Lattner206754a2007-08-28 06:15:15 +00002242 // Verify that all the values are okay, compute the size of the values, and
2243 // reverse the list.
2244 unsigned NumNegativeBits = 0;
2245 unsigned NumPositiveBits = 0;
2246
2247 // Keep track of whether all elements have type int.
2248 bool AllElementsInt = true;
2249
Chris Lattner4b009652007-07-25 00:24:17 +00002250 EnumConstantDecl *EltList = 0;
2251 for (unsigned i = 0; i != NumElements; ++i) {
2252 EnumConstantDecl *ECD =
2253 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2254 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002255
2256 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002257 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002258 assert(InitVal.getBitWidth() >= IntWidth &&
2259 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00002260 if (InitVal.getBitWidth() > IntWidth) {
2261 llvm::APSInt V(InitVal);
2262 V.trunc(IntWidth);
2263 V.extend(InitVal.getBitWidth());
2264 if (V != InitVal)
2265 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattneread053a2008-08-17 07:19:51 +00002266 InitVal.toString(10));
Chris Lattnercb33ae12007-08-28 05:27:00 +00002267 }
Chris Lattner206754a2007-08-28 06:15:15 +00002268
2269 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002270 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00002271 NumPositiveBits = std::max(NumPositiveBits,
2272 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00002273 else
Chris Lattneraff63f02008-01-14 21:47:29 +00002274 NumNegativeBits = std::max(NumNegativeBits,
2275 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00002276
Chris Lattner206754a2007-08-28 06:15:15 +00002277 // Keep track of whether every enum element has type int (very commmon).
2278 if (AllElementsInt)
2279 AllElementsInt = ECD->getType() == Context.IntTy;
2280
Chris Lattner4b009652007-07-25 00:24:17 +00002281 ECD->setNextDeclarator(EltList);
2282 EltList = ECD;
2283 }
2284
Chris Lattner206754a2007-08-28 06:15:15 +00002285 // Figure out the type that should be used for this enum.
2286 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2287 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002288 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00002289
2290 if (NumNegativeBits) {
2291 // If there is a negative value, figure out the smallest integer type (of
2292 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002293 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002294 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002295 BestWidth = IntWidth;
2296 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002297 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002298
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002299 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002300 BestType = Context.LongTy;
2301 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002302 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002303
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002304 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002305 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2306 BestType = Context.LongLongTy;
2307 }
2308 }
2309 } else {
2310 // If there is no negative value, figure out which of uint, ulong, ulonglong
2311 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002312 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002313 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002314 BestWidth = IntWidth;
2315 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00002316 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00002317 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002318 } else {
2319 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002320 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00002321 "How could an initializer get larger than ULL?");
2322 BestType = Context.UnsignedLongLongTy;
2323 }
2324 }
2325
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002326 // Loop over all of the enumerator constants, changing their types to match
2327 // the type of the enum if needed.
2328 for (unsigned i = 0; i != NumElements; ++i) {
2329 EnumConstantDecl *ECD =
2330 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2331 if (!ECD) continue; // Already issued a diagnostic.
2332
2333 // Standard C says the enumerators have int type, but we allow, as an
2334 // extension, the enumerators to be larger than int size. If each
2335 // enumerator value fits in an int, type it as an int, otherwise type it the
2336 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2337 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002338 if (ECD->getType() == Context.IntTy) {
2339 // Make sure the init value is signed.
2340 llvm::APSInt IV = ECD->getInitVal();
2341 IV.setIsSigned(true);
2342 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002343 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002344 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002345
2346 // Determine whether the value fits into an int.
2347 llvm::APSInt InitVal = ECD->getInitVal();
2348 bool FitsInInt;
2349 if (InitVal.isUnsigned() || !InitVal.isNegative())
2350 FitsInInt = InitVal.getActiveBits() < IntWidth;
2351 else
2352 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2353
2354 // If it fits into an integer type, force it. Otherwise force it to match
2355 // the enum decl type.
2356 QualType NewTy;
2357 unsigned NewWidth;
2358 bool NewSign;
2359 if (FitsInInt) {
2360 NewTy = Context.IntTy;
2361 NewWidth = IntWidth;
2362 NewSign = true;
2363 } else if (ECD->getType() == BestType) {
2364 // Already the right type!
2365 continue;
2366 } else {
2367 NewTy = BestType;
2368 NewWidth = BestWidth;
2369 NewSign = BestType->isSignedIntegerType();
2370 }
2371
2372 // Adjust the APSInt value.
2373 InitVal.extOrTrunc(NewWidth);
2374 InitVal.setIsSigned(NewSign);
2375 ECD->setInitVal(InitVal);
2376
2377 // Adjust the Expr initializer and type.
2378 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2379 ECD->setType(NewTy);
2380 }
Chris Lattner206754a2007-08-28 06:15:15 +00002381
Chris Lattner90a018d2007-08-28 18:24:31 +00002382 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002383 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00002384}
2385
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002386Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2387 ExprTy *expr) {
2388 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2389
Chris Lattner81db64a2008-03-16 00:16:02 +00002390 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002391}
2392
Chris Lattner806a5f52008-01-12 07:05:38 +00002393Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00002394 SourceLocation LBrace,
2395 SourceLocation RBrace,
2396 const char *Lang,
2397 unsigned StrSize,
2398 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00002399 LinkageSpecDecl::LanguageIDs Language;
2400 Decl *dcl = static_cast<Decl *>(D);
2401 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2402 Language = LinkageSpecDecl::lang_c;
2403 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2404 Language = LinkageSpecDecl::lang_cxx;
2405 else {
2406 Diag(Loc, diag::err_bad_language);
2407 return 0;
2408 }
2409
2410 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00002411 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00002412}