blob: c6f8c22b087959cb5be6d885a59198d198a71d5f [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
Chris Lattner4b009652007-07-25 00:24:17 +0000496/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
497/// no declarator (e.g. "struct foo;") is parsed.
498Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
499 // TODO: emit error on 'int;' or 'const enum foo;'.
500 // TODO: emit error on 'typedef int;'
501 // if (!DS.isMissingDeclaratorOk()) Diag(...);
502
Steve Naroffedafc0b2007-11-17 21:37:36 +0000503 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000504}
505
Steve Narofff0b23542008-01-10 22:15:12 +0000506bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000507 // Get the type before calling CheckSingleAssignmentConstraints(), since
508 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000509 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000510
Chris Lattner005ed752008-01-04 18:04:52 +0000511 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
512 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
513 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000514}
515
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000516bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000517 const ArrayType *AT = Context.getAsArrayType(DeclT);
518
519 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000520 // C99 6.7.8p14. We have an array of character type with unknown size
521 // being initialized to a string literal.
522 llvm::APSInt ConstVal(32);
523 ConstVal = strLiteral->getByteLength() + 1;
524 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000525 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000526 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000527 } else {
528 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000529 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000530 // FIXME: Avoid truncation for 64-bit length strings.
531 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000532 Diag(strLiteral->getSourceRange().getBegin(),
533 diag::warn_initializer_string_for_char_array_too_long,
534 strLiteral->getSourceRange());
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000535 }
536 // Set type from "char *" to "constant array of char".
537 strLiteral->setType(DeclT);
538 // For now, we always return false (meaning success).
539 return false;
540}
541
542StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000543 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000544 if (AT && AT->getElementType()->isCharType()) {
545 return dyn_cast<StringLiteral>(Init);
546 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000547 return 0;
548}
549
Steve Narofff3cb5142008-01-25 00:51:06 +0000550bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff8e9337f2008-01-21 23:53:58 +0000551 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
552 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +0000553 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Steve Naroff8e9337f2008-01-21 23:53:58 +0000554 return Diag(VAT->getSizeExpr()->getLocStart(),
555 diag::err_variable_object_no_init,
556 VAT->getSizeExpr()->getSourceRange());
557
Steve Naroffcb69fb72007-12-10 22:44:33 +0000558 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
559 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000560 // FIXME: Handle wide strings
561 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
562 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000563
564 if (DeclType->isArrayType())
565 return Diag(Init->getLocStart(),
566 diag::err_array_init_list_required,
567 Init->getSourceRange());
568
Steve Narofff0b23542008-01-10 22:15:12 +0000569 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000570 }
Eli Friedman38b7a912008-06-06 19:40:52 +0000571
Steve Naroffc4d4a482008-05-01 22:18:59 +0000572 InitListChecker CheckInitList(this, InitList, DeclType);
573 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +0000574}
575
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000576Sema::DeclTy *
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000577Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000578 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000579 IdentifierInfo *II = D.getIdentifier();
580
581 // All of these full declarators require an identifier. If it doesn't have
582 // one, the ParsedFreeStandingDeclSpec action should be used.
583 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000584 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000585 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000586 D.getDeclSpec().getSourceRange(), D.getSourceRange());
587 return 0;
588 }
589
Chris Lattnera7549902007-08-26 06:24:45 +0000590 // The scope passed in may not be a decl scope. Zip up the scope tree until
591 // we find one that is.
592 while ((S->getFlags() & Scope::DeclScope) == 0)
593 S = S->getParent();
594
Chris Lattner4b009652007-07-25 00:24:17 +0000595 // See if this is a redefinition of a variable in the same scope.
Steve Naroff6384a012008-04-02 14:35:35 +0000596 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000597 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000598 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000599
600 // In C++, the previous declaration we find might be a tag type
601 // (class or enum). In this case, the new declaration will hide the
602 // tag type.
603 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
604 PrevDecl = 0;
605
Chris Lattner82bb4792007-11-14 06:34:38 +0000606 QualType R = GetTypeForDeclarator(D, S);
607 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
608
Chris Lattner4b009652007-07-25 00:24:17 +0000609 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000610 // Check that there are no default arguments (C++ only).
611 if (getLangOptions().CPlusPlus)
612 CheckExtraCXXDefaultArguments(D);
613
Chris Lattner82bb4792007-11-14 06:34:38 +0000614 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000615 if (!NewTD) return 0;
616
617 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000618 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +0000619 // Merge the decl with the existing one if appropriate. If the decl is
620 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000621 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000622 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
623 if (NewTD == 0) return 0;
624 }
625 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000626 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000627 // C99 6.7.7p2: If a typedef name specifies a variably modified type
628 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000629 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
630 // FIXME: Diagnostic needs to be fixed.
631 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000632 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000633 }
634 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000635 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000636 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000637 switch (D.getDeclSpec().getStorageClassSpec()) {
638 default: assert(0 && "Unknown storage class!");
639 case DeclSpec::SCS_auto:
640 case DeclSpec::SCS_register:
641 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
642 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000643 InvalidDecl = true;
644 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000645 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
646 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
647 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000648 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000649 }
650
Chris Lattner4c7802b2008-03-15 21:24:04 +0000651 bool isInline = D.getDeclSpec().isInlineSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000652 FunctionDecl *NewFD;
653 if (D.getContext() == Declarator::MemberContext) {
654 // This is a C++ method declaration.
655 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
656 D.getIdentifierLoc(), II, R,
657 (SC == FunctionDecl::Static), isInline,
658 LastDeclarator);
659 } else {
660 NewFD = FunctionDecl::Create(Context, CurContext,
661 D.getIdentifierLoc(),
662 II, R, SC, isInline,
663 LastDeclarator);
664 }
Ted Kremenek117f1862008-02-27 22:18:07 +0000665 // Handle attributes.
Chris Lattner9b384ca2008-06-29 00:02:00 +0000666 ProcessDeclAttributes(NewFD, D);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000667
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000668 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000669 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000670 // The parser guarantees this is a string.
671 StringLiteral *SE = cast<StringLiteral>(E);
672 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
673 SE->getByteLength())));
674 }
675
Chris Lattner3e254fb2008-04-08 04:40:51 +0000676 // Copy the parameter declarations from the declarator D to
677 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +0000678 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000679 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
680
681 // Create Decl objects for each parameter, adding them to the
682 // FunctionDecl.
683 llvm::SmallVector<ParmVarDecl*, 16> Params;
684
685 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
686 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000687 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +0000688 // We let through "const void" here because Sema::GetTypeForDeclarator
689 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000690 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
691 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +0000692 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
693 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000694 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
695
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000696 // In C++, the empty parameter-type-list must be spelled "void"; a
697 // typedef of void is not permitted.
698 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +0000699 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +0000700 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
701 }
702
Eli Friedman769e7302008-08-25 21:31:01 +0000703 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000704 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
705 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
706 }
707
708 NewFD->setParams(&Params[0], Params.size());
709 }
710
Steve Narofff8a09432008-01-09 23:34:55 +0000711 // Merge the decl with the existing one if appropriate. Since C functions
712 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000713 if (PrevDecl &&
714 (!getLangOptions().CPlusPlus ||
715 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000716 bool Redeclaration = false;
717 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Chris Lattner4b009652007-07-25 00:24:17 +0000718 if (NewFD == 0) return 0;
Douglas Gregor42214c52008-04-21 02:02:58 +0000719 if (Redeclaration) {
Eli Friedmand2701812008-05-27 05:07:37 +0000720 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregor42214c52008-04-21 02:02:58 +0000721 }
Chris Lattner4b009652007-07-25 00:24:17 +0000722 }
723 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000724
725 // In C++, check default arguments now that we have merged decls.
726 if (getLangOptions().CPlusPlus)
727 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +0000728 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000729 // Check that there are no default arguments (C++ only).
730 if (getLangOptions().CPlusPlus)
731 CheckExtraCXXDefaultArguments(D);
732
Ted Kremenek42730c52008-01-07 19:49:32 +0000733 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000734 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
735 D.getIdentifier()->getName());
736 InvalidDecl = true;
737 }
Chris Lattner4b009652007-07-25 00:24:17 +0000738
739 VarDecl *NewVD;
740 VarDecl::StorageClass SC;
741 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +0000742 default: assert(0 && "Unknown storage class!");
743 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
744 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
745 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
746 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
747 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
748 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000749 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000750 if (D.getContext() == Declarator::MemberContext) {
751 assert(SC == VarDecl::Static && "Invalid storage class for member!");
752 // This is a static data member for a C++ class.
753 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
754 D.getIdentifierLoc(), II,
755 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000756 } else {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000757 if (S->getFnParent() == 0) {
758 // C99 6.9p2: The storage-class specifiers auto and register shall not
759 // appear in the declaration specifiers in an external declaration.
760 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
761 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
762 R.getAsString());
763 InvalidDecl = true;
764 }
765 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
766 II, R, SC, LastDeclarator);
767 } else {
768 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
769 II, R, SC, LastDeclarator);
770 }
Steve Naroffcae537d2007-08-28 18:45:29 +0000771 }
Chris Lattner4b009652007-07-25 00:24:17 +0000772 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000773 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +0000774
Daniel Dunbarced89142008-08-06 00:03:29 +0000775 // Handle GNU asm-label extension (encoded as an attribute).
776 if (Expr *E = (Expr*) D.getAsmLabel()) {
777 // The parser guarantees this is a string.
778 StringLiteral *SE = cast<StringLiteral>(E);
779 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
780 SE->getByteLength())));
781 }
782
Nate Begemanea583262008-03-14 18:07:10 +0000783 // Emit an error if an address space was applied to decl with local storage.
784 // This includes arrays of objects with address space qualifiers, but not
785 // automatic variables that point to other address spaces.
786 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +0000787 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
788 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
789 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +0000790 }
Steve Narofff8a09432008-01-09 23:34:55 +0000791 // Merge the decl with the existing one if appropriate. If the decl is
792 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000793 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000794 NewVD = MergeVarDecl(NewVD, PrevDecl);
795 if (NewVD == 0) return 0;
796 }
Chris Lattner4b009652007-07-25 00:24:17 +0000797 New = NewVD;
798 }
799
800 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000801 if (II)
802 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000803 // If any semantic error occurred, mark the decl as invalid.
804 if (D.getInvalidType() || InvalidDecl)
805 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000806
807 return New;
808}
809
Eli Friedman02c22ce2008-05-20 13:48:25 +0000810bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
811 switch (Init->getStmtClass()) {
812 default:
813 Diag(Init->getExprLoc(),
814 diag::err_init_element_not_constant, Init->getSourceRange());
815 return true;
816 case Expr::ParenExprClass: {
817 const ParenExpr* PE = cast<ParenExpr>(Init);
818 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
819 }
820 case Expr::CompoundLiteralExprClass:
821 return cast<CompoundLiteralExpr>(Init)->isFileScope();
822 case Expr::DeclRefExprClass: {
823 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +0000824 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
825 if (VD->hasGlobalStorage())
826 return false;
827 Diag(Init->getExprLoc(),
828 diag::err_init_element_not_constant, Init->getSourceRange());
829 return true;
830 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000831 if (isa<FunctionDecl>(D))
832 return false;
833 Diag(Init->getExprLoc(),
834 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Narofff0b23542008-01-10 22:15:12 +0000835 return true;
836 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000837 case Expr::MemberExprClass: {
838 const MemberExpr *M = cast<MemberExpr>(Init);
839 if (M->isArrow())
840 return CheckAddressConstantExpression(M->getBase());
841 return CheckAddressConstantExpressionLValue(M->getBase());
842 }
843 case Expr::ArraySubscriptExprClass: {
844 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
845 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
846 return CheckAddressConstantExpression(ASE->getBase()) ||
847 CheckArithmeticConstantExpression(ASE->getIdx());
848 }
849 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +0000850 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +0000851 return false;
852 case Expr::UnaryOperatorClass: {
853 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
854
855 // C99 6.6p9
856 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +0000857 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +0000858
859 Diag(Init->getExprLoc(),
860 diag::err_init_element_not_constant, Init->getSourceRange());
861 return true;
862 }
863 }
864}
865
866bool Sema::CheckAddressConstantExpression(const Expr* Init) {
867 switch (Init->getStmtClass()) {
868 default:
869 Diag(Init->getExprLoc(),
870 diag::err_init_element_not_constant, Init->getSourceRange());
871 return true;
872 case Expr::ParenExprClass: {
873 const ParenExpr* PE = cast<ParenExpr>(Init);
874 return CheckAddressConstantExpression(PE->getSubExpr());
875 }
876 case Expr::StringLiteralClass:
877 case Expr::ObjCStringLiteralClass:
878 return false;
879 case Expr::CallExprClass: {
880 const CallExpr *CE = cast<CallExpr>(Init);
881 if (CE->isBuiltinConstantExpr())
882 return false;
883 Diag(Init->getExprLoc(),
884 diag::err_init_element_not_constant, Init->getSourceRange());
885 return true;
886 }
887 case Expr::UnaryOperatorClass: {
888 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
889
890 // C99 6.6p9
891 if (Exp->getOpcode() == UnaryOperator::AddrOf)
892 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
893
894 if (Exp->getOpcode() == UnaryOperator::Extension)
895 return CheckAddressConstantExpression(Exp->getSubExpr());
896
897 Diag(Init->getExprLoc(),
898 diag::err_init_element_not_constant, Init->getSourceRange());
899 return true;
900 }
901 case Expr::BinaryOperatorClass: {
902 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
903 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
904
905 Expr *PExp = Exp->getLHS();
906 Expr *IExp = Exp->getRHS();
907 if (IExp->getType()->isPointerType())
908 std::swap(PExp, IExp);
909
910 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
911 return CheckAddressConstantExpression(PExp) ||
912 CheckArithmeticConstantExpression(IExp);
913 }
Eli Friedman1fad3c62008-08-25 20:46:57 +0000914 case Expr::ImplicitCastExprClass:
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +0000915 case Expr::ExplicitCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +0000916 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +0000917 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
918 // Check for implicit promotion
919 if (SubExpr->getType()->isFunctionType() ||
920 SubExpr->getType()->isArrayType())
921 return CheckAddressConstantExpressionLValue(SubExpr);
922 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000923
924 // Check for pointer->pointer cast
925 if (SubExpr->getType()->isPointerType())
926 return CheckAddressConstantExpression(SubExpr);
927
Eli Friedman1fad3c62008-08-25 20:46:57 +0000928 if (SubExpr->getType()->isIntegralType()) {
929 // Check for the special-case of a pointer->int->pointer cast;
930 // this isn't standard, but some code requires it. See
931 // PR2720 for an example.
932 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
933 if (SubCast->getSubExpr()->getType()->isPointerType()) {
934 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
935 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
936 if (IntWidth >= PointerWidth) {
937 return CheckAddressConstantExpression(SubCast->getSubExpr());
938 }
939 }
940 }
941 }
942 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +0000943 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +0000944 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000945
946 Diag(Init->getExprLoc(),
947 diag::err_init_element_not_constant, Init->getSourceRange());
948 return true;
949 }
950 case Expr::ConditionalOperatorClass: {
951 // FIXME: Should we pedwarn here?
952 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
953 if (!Exp->getCond()->getType()->isArithmeticType()) {
954 Diag(Init->getExprLoc(),
955 diag::err_init_element_not_constant, Init->getSourceRange());
956 return true;
957 }
958 if (CheckArithmeticConstantExpression(Exp->getCond()))
959 return true;
960 if (Exp->getLHS() &&
961 CheckAddressConstantExpression(Exp->getLHS()))
962 return true;
963 return CheckAddressConstantExpression(Exp->getRHS());
964 }
965 case Expr::AddrLabelExprClass:
966 return false;
967 }
968}
969
Eli Friedman998dffb2008-06-09 05:05:07 +0000970static const Expr* FindExpressionBaseAddress(const Expr* E);
971
972static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
973 switch (E->getStmtClass()) {
974 default:
975 return E;
976 case Expr::ParenExprClass: {
977 const ParenExpr* PE = cast<ParenExpr>(E);
978 return FindExpressionBaseAddressLValue(PE->getSubExpr());
979 }
980 case Expr::MemberExprClass: {
981 const MemberExpr *M = cast<MemberExpr>(E);
982 if (M->isArrow())
983 return FindExpressionBaseAddress(M->getBase());
984 return FindExpressionBaseAddressLValue(M->getBase());
985 }
986 case Expr::ArraySubscriptExprClass: {
987 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
988 return FindExpressionBaseAddress(ASE->getBase());
989 }
990 case Expr::UnaryOperatorClass: {
991 const UnaryOperator *Exp = cast<UnaryOperator>(E);
992
993 if (Exp->getOpcode() == UnaryOperator::Deref)
994 return FindExpressionBaseAddress(Exp->getSubExpr());
995
996 return E;
997 }
998 }
999}
1000
1001static const Expr* FindExpressionBaseAddress(const Expr* E) {
1002 switch (E->getStmtClass()) {
1003 default:
1004 return E;
1005 case Expr::ParenExprClass: {
1006 const ParenExpr* PE = cast<ParenExpr>(E);
1007 return FindExpressionBaseAddress(PE->getSubExpr());
1008 }
1009 case Expr::UnaryOperatorClass: {
1010 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1011
1012 // C99 6.6p9
1013 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1014 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1015
1016 if (Exp->getOpcode() == UnaryOperator::Extension)
1017 return FindExpressionBaseAddress(Exp->getSubExpr());
1018
1019 return E;
1020 }
1021 case Expr::BinaryOperatorClass: {
1022 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1023
1024 Expr *PExp = Exp->getLHS();
1025 Expr *IExp = Exp->getRHS();
1026 if (IExp->getType()->isPointerType())
1027 std::swap(PExp, IExp);
1028
1029 return FindExpressionBaseAddress(PExp);
1030 }
1031 case Expr::ImplicitCastExprClass: {
1032 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1033
1034 // Check for implicit promotion
1035 if (SubExpr->getType()->isFunctionType() ||
1036 SubExpr->getType()->isArrayType())
1037 return FindExpressionBaseAddressLValue(SubExpr);
1038
1039 // Check for pointer->pointer cast
1040 if (SubExpr->getType()->isPointerType())
1041 return FindExpressionBaseAddress(SubExpr);
1042
1043 // We assume that we have an arithmetic expression here;
1044 // if we don't, we'll figure it out later
1045 return 0;
1046 }
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001047 case Expr::ExplicitCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001048 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1049
1050 // Check for pointer->pointer cast
1051 if (SubExpr->getType()->isPointerType())
1052 return FindExpressionBaseAddress(SubExpr);
1053
1054 // We assume that we have an arithmetic expression here;
1055 // if we don't, we'll figure it out later
1056 return 0;
1057 }
1058 }
1059}
1060
Eli Friedman02c22ce2008-05-20 13:48:25 +00001061bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1062 switch (Init->getStmtClass()) {
1063 default:
1064 Diag(Init->getExprLoc(),
1065 diag::err_init_element_not_constant, Init->getSourceRange());
1066 return true;
1067 case Expr::ParenExprClass: {
1068 const ParenExpr* PE = cast<ParenExpr>(Init);
1069 return CheckArithmeticConstantExpression(PE->getSubExpr());
1070 }
1071 case Expr::FloatingLiteralClass:
1072 case Expr::IntegerLiteralClass:
1073 case Expr::CharacterLiteralClass:
1074 case Expr::ImaginaryLiteralClass:
1075 case Expr::TypesCompatibleExprClass:
1076 case Expr::CXXBoolLiteralExprClass:
1077 return false;
1078 case Expr::CallExprClass: {
1079 const CallExpr *CE = cast<CallExpr>(Init);
1080 if (CE->isBuiltinConstantExpr())
1081 return false;
1082 Diag(Init->getExprLoc(),
1083 diag::err_init_element_not_constant, Init->getSourceRange());
1084 return true;
1085 }
1086 case Expr::DeclRefExprClass: {
1087 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1088 if (isa<EnumConstantDecl>(D))
1089 return false;
1090 Diag(Init->getExprLoc(),
1091 diag::err_init_element_not_constant, Init->getSourceRange());
1092 return true;
1093 }
1094 case Expr::CompoundLiteralExprClass:
1095 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1096 // but vectors are allowed to be magic.
1097 if (Init->getType()->isVectorType())
1098 return false;
1099 Diag(Init->getExprLoc(),
1100 diag::err_init_element_not_constant, Init->getSourceRange());
1101 return true;
1102 case Expr::UnaryOperatorClass: {
1103 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1104
1105 switch (Exp->getOpcode()) {
1106 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1107 // See C99 6.6p3.
1108 default:
1109 Diag(Init->getExprLoc(),
1110 diag::err_init_element_not_constant, Init->getSourceRange());
1111 return true;
1112 case UnaryOperator::SizeOf:
1113 case UnaryOperator::AlignOf:
1114 case UnaryOperator::OffsetOf:
1115 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1116 // See C99 6.5.3.4p2 and 6.6p3.
1117 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1118 return false;
1119 Diag(Init->getExprLoc(),
1120 diag::err_init_element_not_constant, Init->getSourceRange());
1121 return true;
1122 case UnaryOperator::Extension:
1123 case UnaryOperator::LNot:
1124 case UnaryOperator::Plus:
1125 case UnaryOperator::Minus:
1126 case UnaryOperator::Not:
1127 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1128 }
1129 }
1130 case Expr::SizeOfAlignOfTypeExprClass: {
1131 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1132 // Special check for void types, which are allowed as an extension
1133 if (Exp->getArgumentType()->isVoidType())
1134 return false;
1135 // alignof always evaluates to a constant.
1136 // FIXME: is sizeof(int[3.0]) a constant expression?
1137 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1138 Diag(Init->getExprLoc(),
1139 diag::err_init_element_not_constant, Init->getSourceRange());
1140 return true;
1141 }
1142 return false;
1143 }
1144 case Expr::BinaryOperatorClass: {
1145 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1146
1147 if (Exp->getLHS()->getType()->isArithmeticType() &&
1148 Exp->getRHS()->getType()->isArithmeticType()) {
1149 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1150 CheckArithmeticConstantExpression(Exp->getRHS());
1151 }
1152
Eli Friedman998dffb2008-06-09 05:05:07 +00001153 if (Exp->getLHS()->getType()->isPointerType() &&
1154 Exp->getRHS()->getType()->isPointerType()) {
1155 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1156 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1157
1158 // Only allow a null (constant integer) base; we could
1159 // allow some additional cases if necessary, but this
1160 // is sufficient to cover offsetof-like constructs.
1161 if (!LHSBase && !RHSBase) {
1162 return CheckAddressConstantExpression(Exp->getLHS()) ||
1163 CheckAddressConstantExpression(Exp->getRHS());
1164 }
1165 }
1166
Eli Friedman02c22ce2008-05-20 13:48:25 +00001167 Diag(Init->getExprLoc(),
1168 diag::err_init_element_not_constant, Init->getSourceRange());
1169 return true;
1170 }
1171 case Expr::ImplicitCastExprClass:
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001172 case Expr::ExplicitCastExprClass: {
1173 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman02c22ce2008-05-20 13:48:25 +00001174 if (SubExpr->getType()->isArithmeticType())
1175 return CheckArithmeticConstantExpression(SubExpr);
1176
1177 Diag(Init->getExprLoc(),
1178 diag::err_init_element_not_constant, Init->getSourceRange());
1179 return true;
1180 }
1181 case Expr::ConditionalOperatorClass: {
1182 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1183 if (CheckArithmeticConstantExpression(Exp->getCond()))
1184 return true;
1185 if (Exp->getLHS() &&
1186 CheckArithmeticConstantExpression(Exp->getLHS()))
1187 return true;
1188 return CheckArithmeticConstantExpression(Exp->getRHS());
1189 }
1190 }
1191}
1192
1193bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopese7280452008-07-07 16:46:50 +00001194 Init = Init->IgnoreParens();
1195
Eli Friedman02c22ce2008-05-20 13:48:25 +00001196 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1197 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1198 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1199
Nuno Lopese7280452008-07-07 16:46:50 +00001200 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1201 return CheckForConstantInitializer(e->getInitializer(), DclT);
1202
Eli Friedman02c22ce2008-05-20 13:48:25 +00001203 if (Init->getType()->isReferenceType()) {
1204 // FIXME: Work out how the heck reference types work
1205 return false;
1206#if 0
1207 // A reference is constant if the address of the expression
1208 // is constant
1209 // We look through initlists here to simplify
1210 // CheckAddressConstantExpressionLValue.
1211 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1212 assert(Exp->getNumInits() > 0 &&
1213 "Refernce initializer cannot be empty");
1214 Init = Exp->getInit(0);
1215 }
1216 return CheckAddressConstantExpressionLValue(Init);
1217#endif
1218 }
1219
1220 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1221 unsigned numInits = Exp->getNumInits();
1222 for (unsigned i = 0; i < numInits; i++) {
1223 // FIXME: Need to get the type of the declaration for C++,
1224 // because it could be a reference?
1225 if (CheckForConstantInitializer(Exp->getInit(i),
1226 Exp->getInit(i)->getType()))
1227 return true;
1228 }
1229 return false;
1230 }
1231
1232 if (Init->isNullPointerConstant(Context))
1233 return false;
1234 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001235 QualType InitTy = Context.getCanonicalType(Init->getType())
1236 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00001237 if (InitTy == Context.BoolTy) {
1238 // Special handling for pointers implicitly cast to bool;
1239 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1240 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1241 Expr* SubE = ICE->getSubExpr();
1242 if (SubE->getType()->isPointerType() ||
1243 SubE->getType()->isArrayType() ||
1244 SubE->getType()->isFunctionType()) {
1245 return CheckAddressConstantExpression(Init);
1246 }
1247 }
1248 } else if (InitTy->isIntegralType()) {
1249 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001250 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00001251 SubE = CE->getSubExpr();
1252 // Special check for pointer cast to int; we allow as an extension
1253 // an address constant cast to an integer if the integer
1254 // is of an appropriate width (this sort of code is apparently used
1255 // in some places).
1256 // FIXME: Add pedwarn?
1257 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1258 if (SubE && (SubE->getType()->isPointerType() ||
1259 SubE->getType()->isArrayType() ||
1260 SubE->getType()->isFunctionType())) {
1261 unsigned IntWidth = Context.getTypeSize(Init->getType());
1262 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1263 if (IntWidth >= PointerWidth)
1264 return CheckAddressConstantExpression(Init);
1265 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001266 }
1267
1268 return CheckArithmeticConstantExpression(Init);
1269 }
1270
1271 if (Init->getType()->isPointerType())
1272 return CheckAddressConstantExpression(Init);
1273
Eli Friedman25086f02008-05-30 18:14:48 +00001274 // An array type at the top level that isn't an init-list must
1275 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001276 if (Init->getType()->isArrayType())
1277 return false;
1278
1279 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1280 Init->getSourceRange());
1281 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001282}
1283
Steve Naroff6a0e2092007-09-12 14:07:44 +00001284void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001285 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001286 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001287 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001288
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001289 // If there is no declaration, there was an error parsing it. Just ignore
1290 // the initializer.
1291 if (RealDecl == 0) {
1292 delete Init;
1293 return;
1294 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001295
Steve Naroff420d0f52007-09-12 20:13:48 +00001296 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1297 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001298 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1299 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001300 RealDecl->setInvalidDecl();
1301 return;
1302 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001303 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001304 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001305 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001306 if (VDecl->isBlockVarDecl()) {
1307 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001308 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001309 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001310 VDecl->setInvalidDecl();
1311 } else if (!VDecl->isInvalidDecl()) {
Steve Narofff3cb5142008-01-25 00:51:06 +00001312 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001313 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00001314
1315 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1316 if (!getLangOptions().CPlusPlus) {
1317 if (SC == VarDecl::Static) // C99 6.7.8p4.
1318 CheckForConstantInitializer(Init, DclT);
1319 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001320 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001321 } else if (VDecl->isFileVarDecl()) {
1322 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001323 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001324 if (!VDecl->isInvalidDecl())
Steve Narofff3cb5142008-01-25 00:51:06 +00001325 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001326 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001327
Anders Carlssonea7140a2008-08-22 05:00:02 +00001328 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1329 if (!getLangOptions().CPlusPlus) {
1330 // C99 6.7.8p4. All file scoped initializers need to be constant.
1331 CheckForConstantInitializer(Init, DclT);
1332 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001333 }
1334 // If the type changed, it means we had an incomplete type that was
1335 // completed by the initializer. For example:
1336 // int ary[] = { 1, 3, 5 };
1337 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001338 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001339 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001340 Init->setType(DclT);
1341 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001342
1343 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001344 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001345 return;
1346}
1347
Chris Lattner4b009652007-07-25 00:24:17 +00001348/// The declarators are chained together backwards, reverse the list.
1349Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1350 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001351 Decl *GroupDecl = static_cast<Decl*>(group);
1352 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00001353 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00001354
1355 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1356 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001357 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00001358 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001359 else { // reverse the list.
1360 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001361 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001362 Group->setNextDeclarator(NewGroup);
1363 NewGroup = Group;
1364 Group = Next;
1365 }
1366 }
1367 // Perform semantic analysis that depends on having fully processed both
1368 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001369 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001370 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1371 if (!IDecl)
1372 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001373 QualType T = IDecl->getType();
1374
1375 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1376 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001377 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1378 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001379 if (T->isVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001380 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1381 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001382 }
1383 }
1384 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1385 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001386 if (IDecl->isBlockVarDecl() &&
1387 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001388 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001389 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1390 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001391 IDecl->setInvalidDecl();
1392 }
1393 }
1394 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1395 // object that has file scope without an initializer, and without a
1396 // storage-class specifier or with the storage-class specifier "static",
1397 // constitutes a tentative definition. Note: A tentative definition with
1398 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00001399 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001400 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001401 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1402 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001403 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001404 // C99 6.9.2p3: If the declaration of an identifier for an object is
1405 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1406 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001407 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1408 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001409 IDecl->setInvalidDecl();
1410 }
1411 }
Steve Naroffb5e78152008-08-08 17:50:35 +00001412 if (IDecl->isFileVarDecl())
1413 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001414 }
1415 return NewGroup;
1416}
Steve Naroff91b03f72007-08-28 03:03:08 +00001417
Chris Lattner3e254fb2008-04-08 04:40:51 +00001418/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1419/// to introduce parameters into function prototype scope.
1420Sema::DeclTy *
1421Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00001422 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001423
1424 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1425 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1426 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1427 Diag(DS.getStorageClassSpecLoc(),
1428 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001429 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001430 }
1431 if (DS.isThreadSpecified()) {
1432 Diag(DS.getThreadSpecLoc(),
1433 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001434 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001435 }
1436
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001437 // Check that there are no default arguments inside the type of this
1438 // parameter (C++ only).
1439 if (getLangOptions().CPlusPlus)
1440 CheckExtraCXXDefaultArguments(D);
1441
Chris Lattner3e254fb2008-04-08 04:40:51 +00001442 // In this context, we *do not* check D.getInvalidType(). If the declarator
1443 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1444 // though it will not reflect the user specified type.
1445 QualType parmDeclType = GetTypeForDeclarator(D, S);
1446
1447 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1448
Chris Lattner4b009652007-07-25 00:24:17 +00001449 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1450 // Can this happen for params? We already checked that they don't conflict
1451 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001452 IdentifierInfo *II = D.getIdentifier();
1453 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1454 if (S->isDeclScope(PrevDecl)) {
1455 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1456 dyn_cast<NamedDecl>(PrevDecl)->getName());
1457
1458 // Recover by removing the name
1459 II = 0;
1460 D.SetIdentifier(0, D.getIdentifierLoc());
1461 }
Chris Lattner4b009652007-07-25 00:24:17 +00001462 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001463
1464 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1465 // Doing the promotion here has a win and a loss. The win is the type for
1466 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1467 // code generator). The loss is the orginal type isn't preserved. For example:
1468 //
1469 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1470 // int blockvardecl[5];
1471 // sizeof(parmvardecl); // size == 4
1472 // sizeof(blockvardecl); // size == 20
1473 // }
1474 //
1475 // For expressions, all implicit conversions are captured using the
1476 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1477 //
1478 // FIXME: If a source translation tool needs to see the original type, then
1479 // we need to consider storing both types (in ParmVarDecl)...
1480 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001481 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001482 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001483 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001484 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001485 parmDeclType = Context.getPointerType(parmDeclType);
1486
Chris Lattner3e254fb2008-04-08 04:40:51 +00001487 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1488 D.getIdentifierLoc(), II,
1489 parmDeclType, VarDecl::None,
1490 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001491
Chris Lattner3e254fb2008-04-08 04:40:51 +00001492 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001493 New->setInvalidDecl();
1494
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001495 if (II)
1496 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001497
Chris Lattner9b384ca2008-06-29 00:02:00 +00001498 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00001499 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001500
Chris Lattner4b009652007-07-25 00:24:17 +00001501}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001502
Chris Lattnerea148702007-10-09 17:14:05 +00001503Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001504 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00001505 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1506 "Not a function declarator!");
1507 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001508
Chris Lattner4b009652007-07-25 00:24:17 +00001509 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1510 // for a K&R function.
1511 if (!FTI.hasPrototype) {
1512 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001513 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001514 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1515 FTI.ArgInfo[i].Ident->getName());
1516 // Implicitly declare the argument as type 'int' for lack of a better
1517 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001518 DeclSpec DS;
1519 const char* PrevSpec; // unused
1520 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1521 PrevSpec);
1522 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1523 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1524 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00001525 }
1526 }
Chris Lattner4b009652007-07-25 00:24:17 +00001527 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001528 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00001529 }
1530
1531 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001532
1533 // See if this is a redefinition.
Steve Naroffe57c21a2008-04-01 23:04:06 +00001534 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroff6384a012008-04-02 14:35:35 +00001535 GlobalScope);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001536 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1537 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1538 const FunctionDecl *Definition;
1539 if (FD->getBody(Definition)) {
1540 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1541 D.getIdentifier()->getName());
1542 Diag(Definition->getLocation(), diag::err_previous_definition);
1543 }
Steve Naroff1d5bd642008-01-14 20:51:29 +00001544 }
1545 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001546
1547 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001548 ActOnDeclarator(GlobalScope, D, 0));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001549}
1550
1551Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1552 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00001553 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001554 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001555
1556 // Check the validity of our function parameters
1557 CheckParmsForFunctionDef(FD);
1558
1559 // Introduce our parameters into the function scope
1560 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1561 ParmVarDecl *Param = FD->getParamDecl(p);
1562 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001563 if (Param->getIdentifier())
1564 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001565 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001566
Chris Lattner4b009652007-07-25 00:24:17 +00001567 return FD;
1568}
1569
Steve Naroff99ee4302007-11-11 23:20:51 +00001570Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1571 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001572 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001573 FD->setBody((Stmt*)Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001574 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00001575 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001576 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001577 } else
1578 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001579 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00001580 // Verify and clean out per-function state.
1581
1582 // Check goto/label use.
1583 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1584 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1585 // Verify that we have no forward references left. If so, there was a goto
1586 // or address of a label taken, but no definition of it. Label fwd
1587 // definitions are indicated with a null substmt.
1588 if (I->second->getSubStmt() == 0) {
1589 LabelStmt *L = I->second;
1590 // Emit error.
1591 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1592
1593 // At this point, we have gotos that use the bogus label. Stitch it into
1594 // the function body so that they aren't leaked and that the AST is well
1595 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001596 if (Body) {
1597 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1598 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1599 } else {
1600 // The whole function wasn't parsed correctly, just delete this.
1601 delete L;
1602 }
Chris Lattner4b009652007-07-25 00:24:17 +00001603 }
1604 }
1605 LabelMap.clear();
1606
Steve Naroff99ee4302007-11-11 23:20:51 +00001607 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001608}
1609
Chris Lattner4b009652007-07-25 00:24:17 +00001610/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1611/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001612ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1613 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001614 // Extension in C99. Legal in C90, but warn about it.
1615 if (getLangOptions().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00001616 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001617 else
Chris Lattner4b009652007-07-25 00:24:17 +00001618 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1619
1620 // FIXME: handle stuff like:
1621 // void foo() { extern float X(); }
1622 // void bar() { X(); } <-- implicit decl for X in another scope.
1623
1624 // Set a Declarator for the implicit definition: int foo();
1625 const char *Dummy;
1626 DeclSpec DS;
1627 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1628 Error = Error; // Silence warning.
1629 assert(!Error && "Error setting up implicit decl!");
1630 Declarator D(DS, Declarator::BlockContext);
1631 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1632 D.SetIdentifier(&II, Loc);
1633
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001634 // Insert this function into translation-unit scope.
1635
1636 DeclContext *PrevDC = CurContext;
1637 CurContext = Context.getTranslationUnitDecl();
1638
Steve Naroff9104f3c2008-04-04 14:32:09 +00001639 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001640 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00001641 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001642
1643 CurContext = PrevDC;
1644
Steve Naroff9104f3c2008-04-04 14:32:09 +00001645 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00001646}
1647
1648
Chris Lattner82bb4792007-11-14 06:34:38 +00001649TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001650 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001651 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001652 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001653
1654 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00001655 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1656 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00001657 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00001658 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001659 if (D.getInvalidType())
1660 NewTD->setInvalidDecl();
1661 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001662}
1663
Steve Naroff0acc9c92007-09-15 18:49:24 +00001664/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001665/// former case, Name will be non-null. In the later case, Name will be null.
1666/// TagType indicates what kind of tag this is. TK indicates whether this is a
1667/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001668Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001669 SourceLocation KWLoc, IdentifierInfo *Name,
1670 SourceLocation NameLoc, AttributeList *Attr) {
1671 // If this is a use of an existing tag, it must have a name.
1672 assert((Name != 0 || TK == TK_Definition) &&
1673 "Nameless record must be a definition!");
1674
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001675 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00001676 switch (TagType) {
1677 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001678 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1679 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1680 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1681 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001682 }
1683
1684 // If this is a named struct, check to see if there was a previous forward
1685 // declaration or definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001686 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1687 if (ScopedDecl *PrevDecl =
1688 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Chris Lattner4b009652007-07-25 00:24:17 +00001689
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001690 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1691 "unexpected Decl type");
1692 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001693 // If this is a use of a previous tag, or if the tag is already declared
1694 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001695 // rementions the tag), reuse the decl.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001696 if (TK == TK_Reference ||
1697 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001698 // Make sure that this wasn't declared as an enum and now used as a
1699 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001700 if (PrevTagDecl->getTagKind() != Kind) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001701 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1702 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001703 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001704 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001705 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001706 } else {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001707 // If this is a use or a forward declaration, we're good.
1708 if (TK != TK_Definition)
1709 return PrevDecl;
1710
1711 // Diagnose attempts to redefine a tag.
1712 if (PrevTagDecl->isDefinition()) {
1713 Diag(NameLoc, diag::err_redefinition, Name->getName());
1714 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1715 // If this is a redefinition, recover by making this struct be
1716 // anonymous, which will make any later references get the previous
1717 // definition.
1718 Name = 0;
1719 } else {
1720 // Okay, this is definition of a previously declared or referenced
1721 // tag. Move the location of the decl to be the definition site.
1722 PrevDecl->setLocation(NameLoc);
1723 return PrevDecl;
1724 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001725 }
Chris Lattner4b009652007-07-25 00:24:17 +00001726 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001727 // If we get here, this is a definition of a new struct type in a nested
1728 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1729 // type.
1730 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00001731 // PrevDecl is a namespace.
1732 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1733 // The tag name clashes with a namespace name, issue an error and recover
1734 // by making this tag be anonymous.
1735 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1736 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1737 Name = 0;
1738 }
Chris Lattner4b009652007-07-25 00:24:17 +00001739 }
Chris Lattner4b009652007-07-25 00:24:17 +00001740 }
1741
1742 // If there is an identifier, use the location of the identifier as the
1743 // location of the decl, otherwise use the location of the struct/union
1744 // keyword.
1745 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1746
1747 // Otherwise, if this is the first time we've seen this tag, create the decl.
1748 TagDecl *New;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001749 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00001750 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1751 // enum X { A, B, C } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001752 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001753 // If this is an undefined enum, warn.
1754 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001755 } else {
1756 // struct/union/class
1757
Chris Lattner4b009652007-07-25 00:24:17 +00001758 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1759 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001760 if (getLangOptions().CPlusPlus)
1761 // FIXME: Look for a way to use RecordDecl for simple structs.
1762 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1763 else
1764 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1765 }
Chris Lattner4b009652007-07-25 00:24:17 +00001766
1767 // If this has an identifier, add it to the scope stack.
1768 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001769 // The scope passed in may not be a decl scope. Zip up the scope tree until
1770 // we find one that is.
1771 while ((S->getFlags() & Scope::DeclScope) == 0)
1772 S = S->getParent();
1773
1774 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001775 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00001776 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00001777
Chris Lattnerd7e83d82008-06-28 23:58:55 +00001778 if (Attr)
1779 ProcessDeclAttributeList(New, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00001780 return New;
1781}
1782
Chris Lattner1bf58f62008-06-21 19:39:06 +00001783/// Collect the instance variables declared in an Objective-C object. Used in
1784/// the creation of structures from objects using the @defs directive.
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001785static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattnere705e5e2008-07-21 22:17:28 +00001786 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00001787 if (Class->getSuperClass())
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001788 CollectIvars(Class->getSuperClass(), Ctx, ivars);
1789
1790 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1791 for (ObjCInterfaceDecl::ivar_iterator I=Class->ivar_begin(), E=Class->ivar_end();
1792 I!=E; ++I) {
1793
1794 ObjCIvarDecl* ID = *I;
1795 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
1796 ID->getIdentifier(),
1797 ID->getType(),
1798 ID->getBitWidth()));
1799 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00001800}
1801
1802/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1803/// instance variables of ClassName into Decls.
1804void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1805 IdentifierInfo *ClassName,
Chris Lattnere705e5e2008-07-21 22:17:28 +00001806 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00001807 // Check that ClassName is a valid class
1808 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1809 if (!Class) {
1810 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1811 return;
1812 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00001813 // Collect the instance variables
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001814 CollectIvars(Class, Context, Decls);
Chris Lattner1bf58f62008-06-21 19:39:06 +00001815}
1816
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001817QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1818 // This method tries to turn a variable array into a constant
1819 // array even when the size isn't an ICE. This is necessary
1820 // for compatibility with code that depends on gcc's buggy
1821 // constant expression folding, like struct {char x[(int)(char*)2];}
1822 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc7436af2008-07-03 04:20:39 +00001823 APValue Result;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001824 if (VLATy->getSizeExpr() &&
Chris Lattner334b1942008-07-11 19:19:21 +00001825 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
1826 llvm::APSInt &Res = Result.getInt();
1827 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1828 return Context.getConstantArrayType(VLATy->getElementType(),
1829 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001830 }
1831 }
1832 return QualType();
1833}
1834
Steve Naroff0acc9c92007-09-15 18:49:24 +00001835/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001836/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001837Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00001838 SourceLocation DeclStart,
1839 Declarator &D, ExprTy *BitfieldWidth) {
1840 IdentifierInfo *II = D.getIdentifier();
1841 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001842 SourceLocation Loc = DeclStart;
1843 if (II) Loc = D.getIdentifierLoc();
1844
1845 // FIXME: Unnamed fields can be handled in various different ways, for
1846 // example, unnamed unions inject all members into the struct namespace!
1847
1848
1849 if (BitWidth) {
1850 // TODO: Validate.
1851 //printf("WARNING: BITFIELDS IGNORED!\n");
1852
1853 // 6.7.2.1p3
1854 // 6.7.2.1p4
1855
1856 } else {
1857 // Not a bitfield.
1858
1859 // validate II.
1860
1861 }
1862
1863 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001864 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1865 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001866
Chris Lattner4b009652007-07-25 00:24:17 +00001867 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1868 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00001869 if (T->isVariablyModifiedType()) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001870 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1871 if (!FixedTy.isNull()) {
1872 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1873 T = FixedTy;
1874 } else {
1875 // FIXME: This diagnostic needs work
1876 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1877 InvalidDecl = true;
1878 }
Chris Lattner4b009652007-07-25 00:24:17 +00001879 }
Chris Lattner4b009652007-07-25 00:24:17 +00001880 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001881 FieldDecl *NewFD;
1882
1883 if (getLangOptions().CPlusPlus) {
1884 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
1885 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
1886 Loc, II, T, BitWidth);
1887 if (II)
1888 PushOnScopeChains(NewFD, S);
1889 }
1890 else
1891 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00001892
Chris Lattner9b384ca2008-06-29 00:02:00 +00001893 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00001894
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001895 if (D.getInvalidType() || InvalidDecl)
1896 NewFD->setInvalidDecl();
1897 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001898}
1899
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001900/// TranslateIvarVisibility - Translate visibility from a token ID to an
1901/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00001902static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001903TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001904 switch (ivarVisibility) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001905 case tok::objc_private: return ObjCIvarDecl::Private;
1906 case tok::objc_public: return ObjCIvarDecl::Public;
1907 case tok::objc_protected: return ObjCIvarDecl::Protected;
1908 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001909 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001910 }
1911}
1912
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001913/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1914/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001915Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001916 SourceLocation DeclStart,
1917 Declarator &D, ExprTy *BitfieldWidth,
1918 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001919 IdentifierInfo *II = D.getIdentifier();
1920 Expr *BitWidth = (Expr*)BitfieldWidth;
1921 SourceLocation Loc = DeclStart;
1922 if (II) Loc = D.getIdentifierLoc();
1923
1924 // FIXME: Unnamed fields can be handled in various different ways, for
1925 // example, unnamed unions inject all members into the struct namespace!
1926
1927
1928 if (BitWidth) {
1929 // TODO: Validate.
1930 //printf("WARNING: BITFIELDS IGNORED!\n");
1931
1932 // 6.7.2.1p3
1933 // 6.7.2.1p4
1934
1935 } else {
1936 // Not a bitfield.
1937
1938 // validate II.
1939
1940 }
1941
1942 QualType T = GetTypeForDeclarator(D, S);
1943 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1944 bool InvalidDecl = false;
1945
1946 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1947 // than a variably modified type.
1948 if (T->isVariablyModifiedType()) {
1949 // FIXME: This diagnostic needs work
1950 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1951 InvalidDecl = true;
1952 }
1953
Ted Kremenek173dd312008-07-23 18:04:17 +00001954 // Get the visibility (access control) for this ivar.
1955 ObjCIvarDecl::AccessControl ac =
1956 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
1957 : ObjCIvarDecl::None;
1958
1959 // Construct the decl.
1960 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00001961 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001962
Ted Kremenek173dd312008-07-23 18:04:17 +00001963 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00001964 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001965
1966 if (D.getInvalidType() || InvalidDecl)
1967 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00001968
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001969 return NewID;
1970}
1971
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001972void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001973 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001974 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001975 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001976 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1977 assert(EnclosingDecl && "missing record or interface decl");
1978 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1979
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001980 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001981 // Diagnose code like:
1982 // struct S { struct S {} X; };
1983 // We discover this when we complete the outer S. Reject and ignore the
1984 // outer S.
1985 Diag(Record->getLocation(), diag::err_nested_redefinition,
1986 Record->getKindName());
1987 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001988 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001989 return;
1990 }
Chris Lattner4b009652007-07-25 00:24:17 +00001991 // Verify that all the fields are okay.
1992 unsigned NumNamedMembers = 0;
1993 llvm::SmallVector<FieldDecl*, 32> RecFields;
1994 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001995
Chris Lattner4b009652007-07-25 00:24:17 +00001996 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001997
Steve Naroff9bb759f2007-09-14 22:20:54 +00001998 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1999 assert(FD && "missing field decl");
2000
2001 // Remember all fields.
2002 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002003
2004 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002005 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002006
Chris Lattner4b009652007-07-25 00:24:17 +00002007 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002008 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002009 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00002010 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002011 FD->setInvalidDecl();
2012 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002013 continue;
2014 }
Chris Lattner4b009652007-07-25 00:24:17 +00002015 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2016 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002017 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002018 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002019 FD->setInvalidDecl();
2020 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002021 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002022 }
Chris Lattner4b009652007-07-25 00:24:17 +00002023 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002024 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002025 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00002026 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002027 FD->setInvalidDecl();
2028 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002029 continue;
2030 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002031 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00002032 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2033 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002034 FD->setInvalidDecl();
2035 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002036 continue;
2037 }
Chris Lattner4b009652007-07-25 00:24:17 +00002038 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002039 if (Record)
2040 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002041 }
Chris Lattner4b009652007-07-25 00:24:17 +00002042 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2043 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002044 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002045 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2046 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002047 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002048 Record->setHasFlexibleArrayMember(true);
2049 } else {
2050 // If this is a struct/class and this is not the last element, reject
2051 // it. Note that GCC supports variable sized arrays in the middle of
2052 // structures.
2053 if (i != NumFields-1) {
2054 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2055 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002056 FD->setInvalidDecl();
2057 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002058 continue;
2059 }
Chris Lattner4b009652007-07-25 00:24:17 +00002060 // We support flexible arrays at the end of structs in other structs
2061 // as an extension.
2062 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2063 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002064 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002065 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002066 }
2067 }
2068 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002069 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002070 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002071 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2072 FD->getName());
2073 FD->setInvalidDecl();
2074 EnclosingDecl->setInvalidDecl();
2075 continue;
2076 }
Chris Lattner4b009652007-07-25 00:24:17 +00002077 // Keep track of the number of named members.
2078 if (IdentifierInfo *II = FD->getIdentifier()) {
2079 // Detect duplicate member names.
2080 if (!FieldIDs.insert(II)) {
2081 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2082 // Find the previous decl.
2083 SourceLocation PrevLoc;
2084 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2085 assert(i != e && "Didn't find previous def!");
2086 if (RecFields[i]->getIdentifier() == II) {
2087 PrevLoc = RecFields[i]->getLocation();
2088 break;
2089 }
2090 }
2091 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002092 FD->setInvalidDecl();
2093 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002094 continue;
2095 }
2096 ++NumNamedMembers;
2097 }
Chris Lattner4b009652007-07-25 00:24:17 +00002098 }
2099
Chris Lattner4b009652007-07-25 00:24:17 +00002100 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00002101 if (Record) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002102 Record->defineBody(&RecFields[0], RecFields.size());
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00002103 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2104 // Sema::ActOnFinishCXXClassDef.
2105 if (!isa<CXXRecordDecl>(Record))
2106 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002107 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002108 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2109 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2110 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2111 else if (ObjCImplementationDecl *IMPDecl =
2112 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002113 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2114 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00002115 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00002116 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00002117 }
Chris Lattner4b009652007-07-25 00:24:17 +00002118}
2119
Steve Naroff0acc9c92007-09-15 18:49:24 +00002120Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00002121 DeclTy *lastEnumConst,
2122 SourceLocation IdLoc, IdentifierInfo *Id,
2123 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00002124 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002125 EnumConstantDecl *LastEnumConst =
2126 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2127 Expr *Val = static_cast<Expr*>(val);
2128
Chris Lattnera7549902007-08-26 06:24:45 +00002129 // The scope passed in may not be a decl scope. Zip up the scope tree until
2130 // we find one that is.
2131 while ((S->getFlags() & Scope::DeclScope) == 0)
2132 S = S->getParent();
2133
Chris Lattner4b009652007-07-25 00:24:17 +00002134 // Verify that there isn't already something declared with this name in this
2135 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00002136 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00002137 // When in C++, we may get a TagDecl with the same name; in this case the
2138 // enum constant will 'hide' the tag.
2139 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2140 "Received TagDecl when not in C++!");
2141 if (!isa<TagDecl>(PrevDecl) &&
2142 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002143 if (isa<EnumConstantDecl>(PrevDecl))
2144 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2145 else
2146 Diag(IdLoc, diag::err_redefinition, Id->getName());
2147 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002148 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00002149 return 0;
2150 }
2151 }
2152
2153 llvm::APSInt EnumVal(32);
2154 QualType EltTy;
2155 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00002156 // Make sure to promote the operand type to int.
2157 UsualUnaryConversions(Val);
2158
Chris Lattner4b009652007-07-25 00:24:17 +00002159 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2160 SourceLocation ExpLoc;
2161 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2162 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2163 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002164 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00002165 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00002166 } else {
2167 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002168 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00002169 }
2170
2171 if (!Val) {
2172 if (LastEnumConst) {
2173 // Assign the last value + 1.
2174 EnumVal = LastEnumConst->getInitVal();
2175 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00002176
2177 // Check for overflow on increment.
2178 if (EnumVal < LastEnumConst->getInitVal())
2179 Diag(IdLoc, diag::warn_enum_value_overflow);
2180
Chris Lattnere7f53a42007-08-27 17:37:24 +00002181 EltTy = LastEnumConst->getType();
2182 } else {
2183 // First value, set to zero.
2184 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002185 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00002186 }
Chris Lattner4b009652007-07-25 00:24:17 +00002187 }
2188
Chris Lattnere4650482008-03-15 06:12:44 +00002189 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00002190 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2191 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00002192 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00002193
2194 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002195 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002196 return New;
2197}
2198
Steve Naroffb0726b82008-08-07 14:08:16 +00002199// FIXME: For consistency with ActOnFields(), we should have the parser
2200// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002201void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00002202 DeclTy **Elements, unsigned NumElements) {
2203 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattner4b009652007-07-25 00:24:17 +00002204
Steve Naroffb0726b82008-08-07 14:08:16 +00002205 if (Enum && Enum->isDefinition()) {
2206 // Diagnose code like:
2207 // enum e0 {
2208 // E0 = sizeof(enum e0 { E1 })
2209 // };
2210 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2211 Enum->getName());
2212 Diag(EnumLoc, diag::err_previous_definition);
2213 Enum->setInvalidDecl();
2214 return;
2215 }
Chris Lattner435c3fd2007-08-28 05:10:31 +00002216 // TODO: If the result value doesn't fit in an int, it must be a long or long
2217 // long value. ISO C does not support this, but GCC does as an extension,
2218 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002219 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00002220
Chris Lattner206754a2007-08-28 06:15:15 +00002221 // Verify that all the values are okay, compute the size of the values, and
2222 // reverse the list.
2223 unsigned NumNegativeBits = 0;
2224 unsigned NumPositiveBits = 0;
2225
2226 // Keep track of whether all elements have type int.
2227 bool AllElementsInt = true;
2228
Chris Lattner4b009652007-07-25 00:24:17 +00002229 EnumConstantDecl *EltList = 0;
2230 for (unsigned i = 0; i != NumElements; ++i) {
2231 EnumConstantDecl *ECD =
2232 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2233 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002234
2235 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002236 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002237 assert(InitVal.getBitWidth() >= IntWidth &&
2238 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00002239 if (InitVal.getBitWidth() > IntWidth) {
2240 llvm::APSInt V(InitVal);
2241 V.trunc(IntWidth);
2242 V.extend(InitVal.getBitWidth());
2243 if (V != InitVal)
2244 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattneread053a2008-08-17 07:19:51 +00002245 InitVal.toString(10));
Chris Lattnercb33ae12007-08-28 05:27:00 +00002246 }
Chris Lattner206754a2007-08-28 06:15:15 +00002247
2248 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002249 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00002250 NumPositiveBits = std::max(NumPositiveBits,
2251 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00002252 else
Chris Lattneraff63f02008-01-14 21:47:29 +00002253 NumNegativeBits = std::max(NumNegativeBits,
2254 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00002255
Chris Lattner206754a2007-08-28 06:15:15 +00002256 // Keep track of whether every enum element has type int (very commmon).
2257 if (AllElementsInt)
2258 AllElementsInt = ECD->getType() == Context.IntTy;
2259
Chris Lattner4b009652007-07-25 00:24:17 +00002260 ECD->setNextDeclarator(EltList);
2261 EltList = ECD;
2262 }
2263
Chris Lattner206754a2007-08-28 06:15:15 +00002264 // Figure out the type that should be used for this enum.
2265 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2266 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002267 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00002268
2269 if (NumNegativeBits) {
2270 // If there is a negative value, figure out the smallest integer type (of
2271 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002272 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002273 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002274 BestWidth = IntWidth;
2275 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002276 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002277
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002278 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002279 BestType = Context.LongTy;
2280 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002281 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002282
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002283 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002284 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2285 BestType = Context.LongLongTy;
2286 }
2287 }
2288 } else {
2289 // If there is no negative value, figure out which of uint, ulong, ulonglong
2290 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002291 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002292 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002293 BestWidth = IntWidth;
2294 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00002295 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00002296 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002297 } else {
2298 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002299 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00002300 "How could an initializer get larger than ULL?");
2301 BestType = Context.UnsignedLongLongTy;
2302 }
2303 }
2304
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002305 // Loop over all of the enumerator constants, changing their types to match
2306 // the type of the enum if needed.
2307 for (unsigned i = 0; i != NumElements; ++i) {
2308 EnumConstantDecl *ECD =
2309 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2310 if (!ECD) continue; // Already issued a diagnostic.
2311
2312 // Standard C says the enumerators have int type, but we allow, as an
2313 // extension, the enumerators to be larger than int size. If each
2314 // enumerator value fits in an int, type it as an int, otherwise type it the
2315 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2316 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002317 if (ECD->getType() == Context.IntTy) {
2318 // Make sure the init value is signed.
2319 llvm::APSInt IV = ECD->getInitVal();
2320 IV.setIsSigned(true);
2321 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002322 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002323 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002324
2325 // Determine whether the value fits into an int.
2326 llvm::APSInt InitVal = ECD->getInitVal();
2327 bool FitsInInt;
2328 if (InitVal.isUnsigned() || !InitVal.isNegative())
2329 FitsInInt = InitVal.getActiveBits() < IntWidth;
2330 else
2331 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2332
2333 // If it fits into an integer type, force it. Otherwise force it to match
2334 // the enum decl type.
2335 QualType NewTy;
2336 unsigned NewWidth;
2337 bool NewSign;
2338 if (FitsInInt) {
2339 NewTy = Context.IntTy;
2340 NewWidth = IntWidth;
2341 NewSign = true;
2342 } else if (ECD->getType() == BestType) {
2343 // Already the right type!
2344 continue;
2345 } else {
2346 NewTy = BestType;
2347 NewWidth = BestWidth;
2348 NewSign = BestType->isSignedIntegerType();
2349 }
2350
2351 // Adjust the APSInt value.
2352 InitVal.extOrTrunc(NewWidth);
2353 InitVal.setIsSigned(NewSign);
2354 ECD->setInitVal(InitVal);
2355
2356 // Adjust the Expr initializer and type.
2357 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2358 ECD->setType(NewTy);
2359 }
Chris Lattner206754a2007-08-28 06:15:15 +00002360
Chris Lattner90a018d2007-08-28 18:24:31 +00002361 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002362 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00002363}
2364
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002365Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2366 ExprTy *expr) {
2367 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2368
Chris Lattner81db64a2008-03-16 00:16:02 +00002369 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002370}
2371
Chris Lattner806a5f52008-01-12 07:05:38 +00002372Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00002373 SourceLocation LBrace,
2374 SourceLocation RBrace,
2375 const char *Lang,
2376 unsigned StrSize,
2377 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00002378 LinkageSpecDecl::LanguageIDs Language;
2379 Decl *dcl = static_cast<Decl *>(D);
2380 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2381 Language = LinkageSpecDecl::lang_c;
2382 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2383 Language = LinkageSpecDecl::lang_cxx;
2384 else {
2385 Diag(Loc, diag::err_bad_language);
2386 return 0;
2387 }
2388
2389 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00002390 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00002391}