blob: df75109e562c9082e4aeacf2099bb76d830ad42e [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Anders Carlssonf78915f2008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/Builtins.h"
19#include "clang/AST/Decl.h"
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +000020#include "clang/AST/DeclCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/AST/Expr.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000022#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/AST/Type.h"
24#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "clang/Basic/LangOptions.h"
27#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000028#include "clang/Basic/SourceManager.h"
29// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000030#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000031#include "clang/Lex/HeaderSearch.h"
Steve Naroff563477d2007-09-18 23:55:05 +000032#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000034#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
36
Steve Naroffb327ce02008-04-02 14:35:35 +000037Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
38 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
39
Douglas Gregor2ce52f32008-04-13 21:07:44 +000040 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
41 isa<ObjCInterfaceDecl>(IIDecl) ||
42 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000043 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000044 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000045}
46
Chris Lattner9fdf9c62008-04-22 18:39:57 +000047void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000048 assert( ( (isa<ObjCMethodDecl>(DC) && isa<TranslationUnitDecl>(CurContext))
Chris Lattner9fdf9c62008-04-22 18:39:57 +000049 || DC->getParent() == CurContext ) &&
Chris Lattnerb048c982008-04-06 04:47:34 +000050 "The next DeclContext should be directly contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000051 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000052}
53
Chris Lattnerb048c982008-04-06 04:47:34 +000054void Sema::PopDeclContext() {
55 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000056 // If CurContext is a ObjC method, getParent() will return NULL.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000057 CurContext = isa<ObjCMethodDecl>(CurContext)
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000058 ? Context.getTranslationUnitDecl()
59 : CurContext->getParent();
Chris Lattner0ed844b2008-04-04 06:12:32 +000060}
61
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000062/// Add this decl to the scope shadowed decl chains.
63void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000064 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000065
66 // C++ [basic.scope]p4:
67 // -- exactly one declaration shall declare a class name or
68 // enumeration name that is not a typedef name and the other
69 // declarations shall all refer to the same object or
70 // enumerator, or all refer to functions and function templates;
71 // in this case the class name or enumeration name is hidden.
72 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
73 // We are pushing the name of a tag (enum or class).
74 IdentifierResolver::ctx_iterator
75 CIT = IdResolver.ctx_begin(TD->getIdentifier(), TD->getDeclContext());
76 if (CIT != IdResolver.ctx_end(TD->getIdentifier()) &&
77 IdResolver.isDeclInScope(*CIT, TD->getDeclContext(), S)) {
78 // There is already a declaration with the same name in the same
79 // scope. It must be found before we find the new declaration,
80 // so swap the order on the shadowed declaration chain.
81
82 IdResolver.AddShadowedDecl(TD, *CIT);
83 return;
84 }
85 }
86
87 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000088}
89
Steve Naroffb216c882007-10-09 22:01:59 +000090void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000091 if (S->decl_empty()) return;
92 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000093
Reid Spencer5f016e22007-07-11 17:01:13 +000094 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
95 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000096 Decl *TmpD = static_cast<Decl*>(*I);
97 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +000098
99 if (isa<CXXFieldDecl>(TmpD)) continue;
100
101 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
102 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000103
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 IdentifierInfo *II = D->getIdentifier();
105 if (!II) continue;
106
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000107 // We only want to remove the decls from the identifier decl chains for local
108 // scopes, when inside a function/method.
109 if (S->getFnParent() != 0)
110 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000111
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000112 // Chain this decl to the containing DeclContext.
113 D->setNext(CurContext->getDeclChain());
114 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 }
116}
117
Steve Naroffe8043c32008-04-01 23:04:06 +0000118/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
119/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000120ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000121 // The third "scope" argument is 0 since we aren't enabling lazy built-in
122 // creation from this context.
123 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000124
Steve Naroffb327ce02008-04-02 14:35:35 +0000125 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000126}
127
Steve Naroffe8043c32008-04-01 23:04:06 +0000128/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000129/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000130Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
131 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000133 unsigned NS = NSI;
134 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
135 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000136
Reid Spencer5f016e22007-07-11 17:01:13 +0000137 // Scan up the scope chain looking for a decl that matches this identifier
138 // that is in the appropriate namespace. This search should not take long, as
139 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000140 for (IdentifierResolver::iterator
141 I = IdResolver.begin(II, CurContext), E = IdResolver.end(II); I != E; ++I)
142 if ((*I)->getIdentifierNamespace() & NS)
143 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000144
Reid Spencer5f016e22007-07-11 17:01:13 +0000145 // If we didn't find a use of this identifier, and if the identifier
146 // corresponds to a compiler builtin, create the decl object for the builtin
147 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000148 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000149 if (enableLazyBuiltinCreation) {
150 // If this is a builtin on this (or all) targets, create the decl.
151 if (unsigned BuiltinID = II->getBuiltinID())
152 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
153 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000154 if (getLangOptions().ObjC1) {
155 // @interface and @compatibility_alias introduce typedef-like names.
156 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000157 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000158 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000159 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
160 if (IDI != ObjCInterfaceDecls.end())
161 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000162 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
163 if (I != ObjCAliasDecls.end())
164 return I->second->getClassInterface();
165 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000166 }
167 return 0;
168}
169
Chris Lattner95e2c712008-05-05 22:18:14 +0000170void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000171 if (!Context.getBuiltinVaListType().isNull())
172 return;
173
174 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000175 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000176 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000177 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
178}
179
Reid Spencer5f016e22007-07-11 17:01:13 +0000180/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
181/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000182ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
183 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 Builtin::ID BID = (Builtin::ID)bid;
185
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000186 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattner95e2c712008-05-05 22:18:14 +0000187 BID == Builtin::BI__builtin_va_copy ||
188 BID == Builtin::BI__builtin_va_end)
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000189 InitBuiltinVaListType();
190
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000191 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000192 FunctionDecl *New = FunctionDecl::Create(Context,
193 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000194 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000195 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000196
Chris Lattner95e2c712008-05-05 22:18:14 +0000197 // Create Decl objects for each parameter, adding them to the
198 // FunctionDecl.
199 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
200 llvm::SmallVector<ParmVarDecl*, 16> Params;
201 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
202 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
203 FT->getArgType(i), VarDecl::None, 0,
204 0));
205 New->setParams(&Params[0], Params.size());
206 }
207
208
209
Chris Lattner7f925cc2008-04-11 07:00:53 +0000210 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000211 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000212 return New;
213}
214
215/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
216/// and scope as a previous declaration 'Old'. Figure out how to resolve this
217/// situation, merging decls or emitting diagnostics as appropriate.
218///
Steve Naroffe8043c32008-04-01 23:04:06 +0000219TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000220 // Verify the old decl was also a typedef.
221 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
222 if (!Old) {
223 Diag(New->getLocation(), diag::err_redefinition_different_kind,
224 New->getName());
225 Diag(OldD->getLocation(), diag::err_previous_definition);
226 return New;
227 }
228
Steve Naroff8ee529b2007-10-31 18:42:27 +0000229 // Allow multiple definitions for ObjC built-in typedefs.
230 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000231 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000232 return Old;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000233
234 if (getLangOptions().Microsoft) return New;
235
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000236 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
237 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
238 // *either* declaration is in a system header. The code below implements
239 // this adhoc compatibility rule. FIXME: The following code will not
240 // work properly when compiling ".i" files (containing preprocessed output).
241 SourceManager &SrcMgr = Context.getSourceManager();
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000242 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
Eli Friedman54ecfce2008-06-11 06:20:39 +0000243 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
244 if (OldDeclFile) {
245 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
246 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
247 if (OldDirType != DirectoryLookup::NormalHeaderDir)
248 return New;
249 }
250 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
251 if (NewDeclFile) {
252 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
253 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
254 if (NewDirType != DirectoryLookup::NormalHeaderDir)
255 return New;
256 }
257
Ted Kremenek2d05c082008-05-23 21:28:18 +0000258 Diag(New->getLocation(), diag::err_redefinition, New->getName());
259 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000260 return New;
261}
262
Chris Lattner6b6b5372008-06-26 18:38:35 +0000263/// DeclhasAttr - returns true if decl Declaration already has the target
264/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000265static bool DeclHasAttr(const Decl *decl, const Attr *target) {
266 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
267 if (attr->getKind() == target->getKind())
268 return true;
269
270 return false;
271}
272
273/// MergeAttributes - append attributes from the Old decl to the New one.
274static void MergeAttributes(Decl *New, Decl *Old) {
275 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
276
Chris Lattnerddee4232008-03-03 03:28:21 +0000277 while (attr) {
278 tmp = attr;
279 attr = attr->getNext();
280
281 if (!DeclHasAttr(New, tmp)) {
282 New->addAttr(tmp);
283 } else {
284 tmp->setNext(0);
285 delete(tmp);
286 }
287 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000288
289 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000290}
291
Chris Lattner04421082008-04-08 04:40:51 +0000292/// MergeFunctionDecl - We just parsed a function 'New' from
293/// declarator D which has the same name and scope as a previous
294/// declaration 'Old'. Figure out how to resolve this situation,
295/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000296/// Redeclaration will be set true if thisNew is a redeclaration OldD.
297FunctionDecl *
298Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
299 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 // Verify the old decl was also a function.
301 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
302 if (!Old) {
303 Diag(New->getLocation(), diag::err_redefinition_different_kind,
304 New->getName());
305 Diag(OldD->getLocation(), diag::err_previous_definition);
306 return New;
307 }
Chris Lattner04421082008-04-08 04:40:51 +0000308
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000309 QualType OldQType = Context.getCanonicalType(Old->getType());
310 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000311
Chris Lattner04421082008-04-08 04:40:51 +0000312 // C++ [dcl.fct]p3:
313 // All declarations for a function shall agree exactly in both the
314 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000315 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
316 MergeAttributes(New, Old);
317 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000318 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000319 }
Chris Lattner04421082008-04-08 04:40:51 +0000320
321 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000322 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000323 if (!getLangOptions().CPlusPlus &&
324 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000325 MergeAttributes(New, Old);
326 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000327 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000328 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000329
Steve Naroff837618c2008-01-16 15:01:34 +0000330 // A function that has already been declared has been redeclared or defined
331 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000332 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000333 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000334 PrevDiag = diag::err_previous_definition;
335 else if (Old->isImplicit())
336 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000337 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000338 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000339
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
341 // TODO: This is totally simplistic. It should handle merging functions
342 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000343 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
344 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 return New;
346}
347
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000348/// equivalentArrayTypes - Used to determine whether two array types are
349/// equivalent.
350/// We need to check this explicitly as an incomplete array definition is
351/// considered a VariableArrayType, so will not match a complete array
352/// definition that would be otherwise equivalent.
353static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
354 const ArrayType *NewAT = NewQType->getAsArrayType();
355 const ArrayType *OldAT = OldQType->getAsArrayType();
356
357 if (!NewAT || !OldAT)
358 return false;
359
360 // If either (or both) array types in incomplete we need to strip off the
361 // outer VariableArrayType. Once the outer VAT is removed the remaining
362 // types must be identical if the array types are to be considered
363 // equivalent.
364 // eg. int[][1] and int[1][1] become
365 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
366 // removing the outermost VAT gives
367 // CAT(1, int) and CAT(1, int)
368 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000369 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000370 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
371 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000372 NewQType = NewAT->getElementType().getCanonicalType();
373 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000374 }
375
376 return NewQType == OldQType;
377}
378
Reid Spencer5f016e22007-07-11 17:01:13 +0000379/// MergeVarDecl - We just parsed a variable 'New' which has the same name
380/// and scope as a previous declaration 'Old'. Figure out how to resolve this
381/// situation, merging decls or emitting diagnostics as appropriate.
382///
383/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
384/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
385///
Steve Naroffe8043c32008-04-01 23:04:06 +0000386VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 // Verify the old decl was also a variable.
388 VarDecl *Old = dyn_cast<VarDecl>(OldD);
389 if (!Old) {
390 Diag(New->getLocation(), diag::err_redefinition_different_kind,
391 New->getName());
392 Diag(OldD->getLocation(), diag::err_previous_definition);
393 return New;
394 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000395
396 MergeAttributes(New, Old);
397
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000399 QualType OldCType = Context.getCanonicalType(Old->getType());
400 QualType NewCType = Context.getCanonicalType(New->getType());
401 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 Diag(New->getLocation(), diag::err_redefinition, New->getName());
403 Diag(Old->getLocation(), diag::err_previous_definition);
404 return New;
405 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000406 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
407 if (New->getStorageClass() == VarDecl::Static &&
408 (Old->getStorageClass() == VarDecl::None ||
409 Old->getStorageClass() == VarDecl::Extern)) {
410 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
411 Diag(Old->getLocation(), diag::err_previous_definition);
412 return New;
413 }
414 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
415 if (New->getStorageClass() != VarDecl::Static &&
416 Old->getStorageClass() == VarDecl::Static) {
417 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
418 Diag(Old->getLocation(), diag::err_previous_definition);
419 return New;
420 }
421 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff248a7532008-04-15 22:42:06 +0000422 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb7b032e2008-01-30 00:44:01 +0000423 // Handle C "tentative" external object definitions (C99 6.9.2).
424 bool OldIsTentative = false;
425 bool NewIsTentative = false;
426
Steve Naroff248a7532008-04-15 22:42:06 +0000427 if (!Old->getInit() &&
428 (Old->getStorageClass() == VarDecl::None ||
429 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000430 OldIsTentative = true;
431
432 // FIXME: this check doesn't work (since the initializer hasn't been
433 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
434 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
435 // thrown out the old decl.
Steve Naroff248a7532008-04-15 22:42:06 +0000436 if (!New->getInit() &&
437 (New->getStorageClass() == VarDecl::None ||
438 New->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000439 ; // change to NewIsTentative = true; once the code is moved.
440
441 if (NewIsTentative || OldIsTentative)
442 return New;
443 }
Steve Naroff235549c2008-05-12 22:36:43 +0000444 // Handle __private_extern__ just like extern.
Steve Naroffb7b032e2008-01-30 00:44:01 +0000445 if (Old->getStorageClass() != VarDecl::Extern &&
Steve Naroff235549c2008-05-12 22:36:43 +0000446 Old->getStorageClass() != VarDecl::PrivateExtern &&
447 New->getStorageClass() != VarDecl::Extern &&
448 New->getStorageClass() != VarDecl::PrivateExtern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000449 Diag(New->getLocation(), diag::err_redefinition, New->getName());
450 Diag(Old->getLocation(), diag::err_previous_definition);
451 }
452 return New;
453}
454
Chris Lattner04421082008-04-08 04:40:51 +0000455/// CheckParmsForFunctionDef - Check that the parameters of the given
456/// function are appropriate for the definition of a function. This
457/// takes care of any checks that cannot be performed on the
458/// declaration itself, e.g., that the types of each of the function
459/// parameters are complete.
460bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
461 bool HasInvalidParm = false;
462 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
463 ParmVarDecl *Param = FD->getParamDecl(p);
464
465 // C99 6.7.5.3p4: the parameters in a parameter type list in a
466 // function declarator that is part of a function definition of
467 // that function shall not have incomplete type.
468 if (Param->getType()->isIncompleteType() &&
469 !Param->isInvalidDecl()) {
470 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
471 Param->getType().getAsString());
472 Param->setInvalidDecl();
473 HasInvalidParm = true;
474 }
475 }
476
477 return HasInvalidParm;
478}
479
480/// CreateImplicitParameter - Creates an implicit function parameter
481/// in the scope S and with the given type. This routine is used, for
482/// example, to create the implicit "self" parameter in an Objective-C
483/// method.
Chris Lattner41110242008-06-17 18:05:57 +0000484ImplicitParamDecl *
Chris Lattner04421082008-04-08 04:40:51 +0000485Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
486 SourceLocation IdLoc, QualType Type) {
Chris Lattner41110242008-06-17 18:05:57 +0000487 ImplicitParamDecl *New = ImplicitParamDecl::Create(Context, CurContext,
488 IdLoc, Id, Type, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000489 if (Id)
490 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000491
492 return New;
493}
494
Reid Spencer5f016e22007-07-11 17:01:13 +0000495/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
496/// no declarator (e.g. "struct foo;") is parsed.
497Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
498 // TODO: emit error on 'int;' or 'const enum foo;'.
499 // TODO: emit error on 'typedef int;'
500 // if (!DS.isMissingDeclaratorOk()) Diag(...);
501
Steve Naroff92199282007-11-17 21:37:36 +0000502 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000503}
504
Steve Naroffd0091aa2008-01-10 22:15:12 +0000505bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000506 // Get the type before calling CheckSingleAssignmentConstraints(), since
507 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000508 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000509
Chris Lattner5cf216b2008-01-04 18:04:52 +0000510 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
511 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
512 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000513}
514
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000515bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000516 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000517 // C99 6.7.8p14. We have an array of character type with unknown size
518 // being initialized to a string literal.
519 llvm::APSInt ConstVal(32);
520 ConstVal = strLiteral->getByteLength() + 1;
521 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000522 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000523 ArrayType::Normal, 0);
524 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
525 // C99 6.7.8p14. We have an array of character type with known size.
526 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
527 Diag(strLiteral->getSourceRange().getBegin(),
528 diag::warn_initializer_string_for_char_array_too_long,
529 strLiteral->getSourceRange());
530 } else {
531 assert(0 && "HandleStringLiteralInit(): Invalid array type");
532 }
533 // Set type from "char *" to "constant array of char".
534 strLiteral->setType(DeclT);
535 // For now, we always return false (meaning success).
536 return false;
537}
538
539StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000540 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000541 if (AT && AT->getElementType()->isCharType()) {
542 return dyn_cast<StringLiteral>(Init);
543 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000544 return 0;
545}
546
Steve Naroffa9960332008-01-25 00:51:06 +0000547bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000548 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
549 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000550 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000551 return Diag(VAT->getSizeExpr()->getLocStart(),
552 diag::err_variable_object_no_init,
553 VAT->getSizeExpr()->getSourceRange());
554
Steve Naroff2fdc3742007-12-10 22:44:33 +0000555 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
556 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000557 // FIXME: Handle wide strings
558 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
559 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000560
561 if (DeclType->isArrayType())
562 return Diag(Init->getLocStart(),
563 diag::err_array_init_list_required,
564 Init->getSourceRange());
565
Steve Naroffd0091aa2008-01-10 22:15:12 +0000566 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000567 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000568
Steve Naroff0cca7492008-05-01 22:18:59 +0000569 InitListChecker CheckInitList(this, InitList, DeclType);
570 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000571}
572
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000573Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000574Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000575 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 IdentifierInfo *II = D.getIdentifier();
577
Chris Lattnere80a59c2007-07-25 00:24:17 +0000578 // All of these full declarators require an identifier. If it doesn't have
579 // one, the ParsedFreeStandingDeclSpec action should be used.
580 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000581 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000582 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000583 D.getDeclSpec().getSourceRange(), D.getSourceRange());
584 return 0;
585 }
586
Chris Lattner31e05722007-08-26 06:24:45 +0000587 // The scope passed in may not be a decl scope. Zip up the scope tree until
588 // we find one that is.
589 while ((S->getFlags() & Scope::DeclScope) == 0)
590 S = S->getParent();
591
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000593 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000594 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000595 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000596
597 // In C++, the previous declaration we find might be a tag type
598 // (class or enum). In this case, the new declaration will hide the
599 // tag type.
600 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
601 PrevDecl = 0;
602
Chris Lattner41af0932007-11-14 06:34:38 +0000603 QualType R = GetTypeForDeclarator(D, S);
604 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
605
Reid Spencer5f016e22007-07-11 17:01:13 +0000606 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000607 // Check that there are no default arguments (C++ only).
608 if (getLangOptions().CPlusPlus)
609 CheckExtraCXXDefaultArguments(D);
610
Chris Lattner41af0932007-11-14 06:34:38 +0000611 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000612 if (!NewTD) return 0;
613
614 // Handle attributes prior to checking for duplicates in MergeVarDecl
615 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
616 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000617 // Merge the decl with the existing one if appropriate. If the decl is
618 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000619 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000620 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
621 if (NewTD == 0) return 0;
622 }
623 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000624 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000625 // C99 6.7.7p2: If a typedef name specifies a variably modified type
626 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000627 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
628 // FIXME: Diagnostic needs to be fixed.
629 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000630 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 }
632 }
Chris Lattner41af0932007-11-14 06:34:38 +0000633 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000634 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000635 switch (D.getDeclSpec().getStorageClassSpec()) {
636 default: assert(0 && "Unknown storage class!");
637 case DeclSpec::SCS_auto:
638 case DeclSpec::SCS_register:
639 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
640 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000641 InvalidDecl = true;
642 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
644 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
645 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000646 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 }
648
Chris Lattnera98e58d2008-03-15 21:24:04 +0000649 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000650 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
651 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000652 II, R, SC, isInline,
653 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000654 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000655 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
656 D.getAttributes());
Chris Lattner04421082008-04-08 04:40:51 +0000657
658 // Copy the parameter declarations from the declarator D to
659 // the function declaration NewFD, if they are available.
660 if (D.getNumTypeObjects() > 0 &&
661 D.getTypeObject(0).Fun.hasPrototype) {
662 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
663
664 // Create Decl objects for each parameter, adding them to the
665 // FunctionDecl.
666 llvm::SmallVector<ParmVarDecl*, 16> Params;
667
668 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
669 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000670 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000671 // We let through "const void" here because Sema::GetTypeForDeclarator
672 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000673 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
674 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000675 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
676 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000677 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
678
Chris Lattnerdef026a2008-04-10 02:26:16 +0000679 // In C++, the empty parameter-type-list must be spelled "void"; a
680 // typedef of void is not permitted.
681 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000682 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000683 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
684 }
685
Chris Lattner04421082008-04-08 04:40:51 +0000686 } else {
687 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
688 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
689 }
690
691 NewFD->setParams(&Params[0], Params.size());
692 }
693
Steve Naroffffce4d52008-01-09 23:34:55 +0000694 // Merge the decl with the existing one if appropriate. Since C functions
695 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000696 if (PrevDecl &&
697 (!getLangOptions().CPlusPlus ||
698 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000699 bool Redeclaration = false;
700 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000702 if (Redeclaration) {
Eli Friedman27424962008-05-27 05:07:37 +0000703 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregorf0097952008-04-21 02:02:58 +0000704 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000705 }
706 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000707
708 // In C++, check default arguments now that we have merged decls.
709 if (getLangOptions().CPlusPlus)
710 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000711 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000712 // Check that there are no default arguments (C++ only).
713 if (getLangOptions().CPlusPlus)
714 CheckExtraCXXDefaultArguments(D);
715
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000716 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000717 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
718 D.getIdentifier()->getName());
719 InvalidDecl = true;
720 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000721
722 VarDecl *NewVD;
723 VarDecl::StorageClass SC;
724 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000725 default: assert(0 && "Unknown storage class!");
726 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
727 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
728 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
729 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
730 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
731 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000733 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 // C99 6.9p2: The storage-class specifiers auto and register shall not
735 // appear in the declaration specifiers in an external declaration.
736 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
737 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
738 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000739 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000740 }
Steve Naroff248a7532008-04-15 22:42:06 +0000741 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
742 II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000743 } else {
Steve Naroff248a7532008-04-15 22:42:06 +0000744 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
745 II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000746 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 // Handle attributes prior to checking for duplicates in MergeVarDecl
748 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
749 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000750
751 // Emit an error if an address space was applied to decl with local storage.
752 // This includes arrays of objects with address space qualifiers, but not
753 // automatic variables that point to other address spaces.
754 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000755 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
756 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
757 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000758 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000759 // Merge the decl with the existing one if appropriate. If the decl is
760 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000761 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 NewVD = MergeVarDecl(NewVD, PrevDecl);
763 if (NewVD == 0) return 0;
764 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 New = NewVD;
766 }
767
768 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000769 if (II)
770 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000771 // If any semantic error occurred, mark the decl as invalid.
772 if (D.getInvalidType() || InvalidDecl)
773 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000774
775 return New;
776}
777
Eli Friedmanc594b322008-05-20 13:48:25 +0000778bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
779 switch (Init->getStmtClass()) {
780 default:
781 Diag(Init->getExprLoc(),
782 diag::err_init_element_not_constant, Init->getSourceRange());
783 return true;
784 case Expr::ParenExprClass: {
785 const ParenExpr* PE = cast<ParenExpr>(Init);
786 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
787 }
788 case Expr::CompoundLiteralExprClass:
789 return cast<CompoundLiteralExpr>(Init)->isFileScope();
790 case Expr::DeclRefExprClass: {
791 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +0000792 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
793 if (VD->hasGlobalStorage())
794 return false;
795 Diag(Init->getExprLoc(),
796 diag::err_init_element_not_constant, Init->getSourceRange());
797 return true;
798 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000799 if (isa<FunctionDecl>(D))
800 return false;
801 Diag(Init->getExprLoc(),
802 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroffd0091aa2008-01-10 22:15:12 +0000803 return true;
804 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000805 case Expr::MemberExprClass: {
806 const MemberExpr *M = cast<MemberExpr>(Init);
807 if (M->isArrow())
808 return CheckAddressConstantExpression(M->getBase());
809 return CheckAddressConstantExpressionLValue(M->getBase());
810 }
811 case Expr::ArraySubscriptExprClass: {
812 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
813 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
814 return CheckAddressConstantExpression(ASE->getBase()) ||
815 CheckArithmeticConstantExpression(ASE->getIdx());
816 }
817 case Expr::StringLiteralClass:
818 case Expr::PreDefinedExprClass:
819 return false;
820 case Expr::UnaryOperatorClass: {
821 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
822
823 // C99 6.6p9
824 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +0000825 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +0000826
827 Diag(Init->getExprLoc(),
828 diag::err_init_element_not_constant, Init->getSourceRange());
829 return true;
830 }
831 }
832}
833
834bool Sema::CheckAddressConstantExpression(const Expr* Init) {
835 switch (Init->getStmtClass()) {
836 default:
837 Diag(Init->getExprLoc(),
838 diag::err_init_element_not_constant, Init->getSourceRange());
839 return true;
840 case Expr::ParenExprClass: {
841 const ParenExpr* PE = cast<ParenExpr>(Init);
842 return CheckAddressConstantExpression(PE->getSubExpr());
843 }
844 case Expr::StringLiteralClass:
845 case Expr::ObjCStringLiteralClass:
846 return false;
847 case Expr::CallExprClass: {
848 const CallExpr *CE = cast<CallExpr>(Init);
849 if (CE->isBuiltinConstantExpr())
850 return false;
851 Diag(Init->getExprLoc(),
852 diag::err_init_element_not_constant, Init->getSourceRange());
853 return true;
854 }
855 case Expr::UnaryOperatorClass: {
856 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
857
858 // C99 6.6p9
859 if (Exp->getOpcode() == UnaryOperator::AddrOf)
860 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
861
862 if (Exp->getOpcode() == UnaryOperator::Extension)
863 return CheckAddressConstantExpression(Exp->getSubExpr());
864
865 Diag(Init->getExprLoc(),
866 diag::err_init_element_not_constant, Init->getSourceRange());
867 return true;
868 }
869 case Expr::BinaryOperatorClass: {
870 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
871 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
872
873 Expr *PExp = Exp->getLHS();
874 Expr *IExp = Exp->getRHS();
875 if (IExp->getType()->isPointerType())
876 std::swap(PExp, IExp);
877
878 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
879 return CheckAddressConstantExpression(PExp) ||
880 CheckArithmeticConstantExpression(IExp);
881 }
882 case Expr::ImplicitCastExprClass: {
883 const Expr* SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
884
885 // Check for implicit promotion
886 if (SubExpr->getType()->isFunctionType() ||
887 SubExpr->getType()->isArrayType())
888 return CheckAddressConstantExpressionLValue(SubExpr);
889
890 // Check for pointer->pointer cast
891 if (SubExpr->getType()->isPointerType())
892 return CheckAddressConstantExpression(SubExpr);
893
894 if (SubExpr->getType()->isArithmeticType())
895 return CheckArithmeticConstantExpression(SubExpr);
896
897 Diag(Init->getExprLoc(),
898 diag::err_init_element_not_constant, Init->getSourceRange());
899 return true;
900 }
901 case Expr::CastExprClass: {
902 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
903
904 // Check for pointer->pointer cast
905 if (SubExpr->getType()->isPointerType())
906 return CheckAddressConstantExpression(SubExpr);
907
908 // FIXME: Should we pedwarn for (int*)(0+0)?
909 if (SubExpr->getType()->isArithmeticType())
910 return CheckArithmeticConstantExpression(SubExpr);
911
912 Diag(Init->getExprLoc(),
913 diag::err_init_element_not_constant, Init->getSourceRange());
914 return true;
915 }
916 case Expr::ConditionalOperatorClass: {
917 // FIXME: Should we pedwarn here?
918 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
919 if (!Exp->getCond()->getType()->isArithmeticType()) {
920 Diag(Init->getExprLoc(),
921 diag::err_init_element_not_constant, Init->getSourceRange());
922 return true;
923 }
924 if (CheckArithmeticConstantExpression(Exp->getCond()))
925 return true;
926 if (Exp->getLHS() &&
927 CheckAddressConstantExpression(Exp->getLHS()))
928 return true;
929 return CheckAddressConstantExpression(Exp->getRHS());
930 }
931 case Expr::AddrLabelExprClass:
932 return false;
933 }
934}
935
Eli Friedman4caf0552008-06-09 05:05:07 +0000936static const Expr* FindExpressionBaseAddress(const Expr* E);
937
938static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
939 switch (E->getStmtClass()) {
940 default:
941 return E;
942 case Expr::ParenExprClass: {
943 const ParenExpr* PE = cast<ParenExpr>(E);
944 return FindExpressionBaseAddressLValue(PE->getSubExpr());
945 }
946 case Expr::MemberExprClass: {
947 const MemberExpr *M = cast<MemberExpr>(E);
948 if (M->isArrow())
949 return FindExpressionBaseAddress(M->getBase());
950 return FindExpressionBaseAddressLValue(M->getBase());
951 }
952 case Expr::ArraySubscriptExprClass: {
953 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
954 return FindExpressionBaseAddress(ASE->getBase());
955 }
956 case Expr::UnaryOperatorClass: {
957 const UnaryOperator *Exp = cast<UnaryOperator>(E);
958
959 if (Exp->getOpcode() == UnaryOperator::Deref)
960 return FindExpressionBaseAddress(Exp->getSubExpr());
961
962 return E;
963 }
964 }
965}
966
967static const Expr* FindExpressionBaseAddress(const Expr* E) {
968 switch (E->getStmtClass()) {
969 default:
970 return E;
971 case Expr::ParenExprClass: {
972 const ParenExpr* PE = cast<ParenExpr>(E);
973 return FindExpressionBaseAddress(PE->getSubExpr());
974 }
975 case Expr::UnaryOperatorClass: {
976 const UnaryOperator *Exp = cast<UnaryOperator>(E);
977
978 // C99 6.6p9
979 if (Exp->getOpcode() == UnaryOperator::AddrOf)
980 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
981
982 if (Exp->getOpcode() == UnaryOperator::Extension)
983 return FindExpressionBaseAddress(Exp->getSubExpr());
984
985 return E;
986 }
987 case Expr::BinaryOperatorClass: {
988 const BinaryOperator *Exp = cast<BinaryOperator>(E);
989
990 Expr *PExp = Exp->getLHS();
991 Expr *IExp = Exp->getRHS();
992 if (IExp->getType()->isPointerType())
993 std::swap(PExp, IExp);
994
995 return FindExpressionBaseAddress(PExp);
996 }
997 case Expr::ImplicitCastExprClass: {
998 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
999
1000 // Check for implicit promotion
1001 if (SubExpr->getType()->isFunctionType() ||
1002 SubExpr->getType()->isArrayType())
1003 return FindExpressionBaseAddressLValue(SubExpr);
1004
1005 // Check for pointer->pointer cast
1006 if (SubExpr->getType()->isPointerType())
1007 return FindExpressionBaseAddress(SubExpr);
1008
1009 // We assume that we have an arithmetic expression here;
1010 // if we don't, we'll figure it out later
1011 return 0;
1012 }
1013 case Expr::CastExprClass: {
1014 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1015
1016 // Check for pointer->pointer cast
1017 if (SubExpr->getType()->isPointerType())
1018 return FindExpressionBaseAddress(SubExpr);
1019
1020 // We assume that we have an arithmetic expression here;
1021 // if we don't, we'll figure it out later
1022 return 0;
1023 }
1024 }
1025}
1026
Eli Friedmanc594b322008-05-20 13:48:25 +00001027bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1028 switch (Init->getStmtClass()) {
1029 default:
1030 Diag(Init->getExprLoc(),
1031 diag::err_init_element_not_constant, Init->getSourceRange());
1032 return true;
1033 case Expr::ParenExprClass: {
1034 const ParenExpr* PE = cast<ParenExpr>(Init);
1035 return CheckArithmeticConstantExpression(PE->getSubExpr());
1036 }
1037 case Expr::FloatingLiteralClass:
1038 case Expr::IntegerLiteralClass:
1039 case Expr::CharacterLiteralClass:
1040 case Expr::ImaginaryLiteralClass:
1041 case Expr::TypesCompatibleExprClass:
1042 case Expr::CXXBoolLiteralExprClass:
1043 return false;
1044 case Expr::CallExprClass: {
1045 const CallExpr *CE = cast<CallExpr>(Init);
1046 if (CE->isBuiltinConstantExpr())
1047 return false;
1048 Diag(Init->getExprLoc(),
1049 diag::err_init_element_not_constant, Init->getSourceRange());
1050 return true;
1051 }
1052 case Expr::DeclRefExprClass: {
1053 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1054 if (isa<EnumConstantDecl>(D))
1055 return false;
1056 Diag(Init->getExprLoc(),
1057 diag::err_init_element_not_constant, Init->getSourceRange());
1058 return true;
1059 }
1060 case Expr::CompoundLiteralExprClass:
1061 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1062 // but vectors are allowed to be magic.
1063 if (Init->getType()->isVectorType())
1064 return false;
1065 Diag(Init->getExprLoc(),
1066 diag::err_init_element_not_constant, Init->getSourceRange());
1067 return true;
1068 case Expr::UnaryOperatorClass: {
1069 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1070
1071 switch (Exp->getOpcode()) {
1072 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1073 // See C99 6.6p3.
1074 default:
1075 Diag(Init->getExprLoc(),
1076 diag::err_init_element_not_constant, Init->getSourceRange());
1077 return true;
1078 case UnaryOperator::SizeOf:
1079 case UnaryOperator::AlignOf:
1080 case UnaryOperator::OffsetOf:
1081 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1082 // See C99 6.5.3.4p2 and 6.6p3.
1083 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1084 return false;
1085 Diag(Init->getExprLoc(),
1086 diag::err_init_element_not_constant, Init->getSourceRange());
1087 return true;
1088 case UnaryOperator::Extension:
1089 case UnaryOperator::LNot:
1090 case UnaryOperator::Plus:
1091 case UnaryOperator::Minus:
1092 case UnaryOperator::Not:
1093 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1094 }
1095 }
1096 case Expr::SizeOfAlignOfTypeExprClass: {
1097 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1098 // Special check for void types, which are allowed as an extension
1099 if (Exp->getArgumentType()->isVoidType())
1100 return false;
1101 // alignof always evaluates to a constant.
1102 // FIXME: is sizeof(int[3.0]) a constant expression?
1103 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1104 Diag(Init->getExprLoc(),
1105 diag::err_init_element_not_constant, Init->getSourceRange());
1106 return true;
1107 }
1108 return false;
1109 }
1110 case Expr::BinaryOperatorClass: {
1111 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1112
1113 if (Exp->getLHS()->getType()->isArithmeticType() &&
1114 Exp->getRHS()->getType()->isArithmeticType()) {
1115 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1116 CheckArithmeticConstantExpression(Exp->getRHS());
1117 }
1118
Eli Friedman4caf0552008-06-09 05:05:07 +00001119 if (Exp->getLHS()->getType()->isPointerType() &&
1120 Exp->getRHS()->getType()->isPointerType()) {
1121 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1122 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1123
1124 // Only allow a null (constant integer) base; we could
1125 // allow some additional cases if necessary, but this
1126 // is sufficient to cover offsetof-like constructs.
1127 if (!LHSBase && !RHSBase) {
1128 return CheckAddressConstantExpression(Exp->getLHS()) ||
1129 CheckAddressConstantExpression(Exp->getRHS());
1130 }
1131 }
1132
Eli Friedmanc594b322008-05-20 13:48:25 +00001133 Diag(Init->getExprLoc(),
1134 diag::err_init_element_not_constant, Init->getSourceRange());
1135 return true;
1136 }
1137 case Expr::ImplicitCastExprClass:
1138 case Expr::CastExprClass: {
1139 const Expr *SubExpr;
1140 if (const CastExpr *C = dyn_cast<CastExpr>(Init)) {
1141 SubExpr = C->getSubExpr();
1142 } else {
1143 SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1144 }
1145
1146 if (SubExpr->getType()->isArithmeticType())
1147 return CheckArithmeticConstantExpression(SubExpr);
1148
1149 Diag(Init->getExprLoc(),
1150 diag::err_init_element_not_constant, Init->getSourceRange());
1151 return true;
1152 }
1153 case Expr::ConditionalOperatorClass: {
1154 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1155 if (CheckArithmeticConstantExpression(Exp->getCond()))
1156 return true;
1157 if (Exp->getLHS() &&
1158 CheckArithmeticConstantExpression(Exp->getLHS()))
1159 return true;
1160 return CheckArithmeticConstantExpression(Exp->getRHS());
1161 }
1162 }
1163}
1164
1165bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
1166 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1167 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1168 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1169
1170 if (Init->getType()->isReferenceType()) {
1171 // FIXME: Work out how the heck reference types work
1172 return false;
1173#if 0
1174 // A reference is constant if the address of the expression
1175 // is constant
1176 // We look through initlists here to simplify
1177 // CheckAddressConstantExpressionLValue.
1178 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1179 assert(Exp->getNumInits() > 0 &&
1180 "Refernce initializer cannot be empty");
1181 Init = Exp->getInit(0);
1182 }
1183 return CheckAddressConstantExpressionLValue(Init);
1184#endif
1185 }
1186
1187 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1188 unsigned numInits = Exp->getNumInits();
1189 for (unsigned i = 0; i < numInits; i++) {
1190 // FIXME: Need to get the type of the declaration for C++,
1191 // because it could be a reference?
1192 if (CheckForConstantInitializer(Exp->getInit(i),
1193 Exp->getInit(i)->getType()))
1194 return true;
1195 }
1196 return false;
1197 }
1198
1199 if (Init->isNullPointerConstant(Context))
1200 return false;
1201 if (Init->getType()->isArithmeticType()) {
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001202 QualType InitTy = Init->getType().getCanonicalType().getUnqualifiedType();
1203 if (InitTy == Context.BoolTy) {
1204 // Special handling for pointers implicitly cast to bool;
1205 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1206 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1207 Expr* SubE = ICE->getSubExpr();
1208 if (SubE->getType()->isPointerType() ||
1209 SubE->getType()->isArrayType() ||
1210 SubE->getType()->isFunctionType()) {
1211 return CheckAddressConstantExpression(Init);
1212 }
1213 }
1214 } else if (InitTy->isIntegralType()) {
1215 Expr* SubE = 0;
1216 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init))
1217 SubE = ICE->getSubExpr();
1218 else if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1219 SubE = CE->getSubExpr();
1220 // Special check for pointer cast to int; we allow as an extension
1221 // an address constant cast to an integer if the integer
1222 // is of an appropriate width (this sort of code is apparently used
1223 // in some places).
1224 // FIXME: Add pedwarn?
1225 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1226 if (SubE && (SubE->getType()->isPointerType() ||
1227 SubE->getType()->isArrayType() ||
1228 SubE->getType()->isFunctionType())) {
1229 unsigned IntWidth = Context.getTypeSize(Init->getType());
1230 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1231 if (IntWidth >= PointerWidth)
1232 return CheckAddressConstantExpression(Init);
1233 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001234 }
1235
1236 return CheckArithmeticConstantExpression(Init);
1237 }
1238
1239 if (Init->getType()->isPointerType())
1240 return CheckAddressConstantExpression(Init);
1241
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001242 // An array type at the top level that isn't an init-list must
1243 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001244 if (Init->getType()->isArrayType())
1245 return false;
1246
1247 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1248 Init->getSourceRange());
1249 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001250}
1251
Steve Naroffbb204692007-09-12 14:07:44 +00001252void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001253 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001254 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001255 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001256
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001257 // If there is no declaration, there was an error parsing it. Just ignore
1258 // the initializer.
1259 if (RealDecl == 0) {
1260 delete Init;
1261 return;
1262 }
Steve Naroffbb204692007-09-12 14:07:44 +00001263
Steve Naroff410e3e22007-09-12 20:13:48 +00001264 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1265 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001266 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1267 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001268 RealDecl->setInvalidDecl();
1269 return;
1270 }
Steve Naroffbb204692007-09-12 14:07:44 +00001271 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001272 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001273 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001274 if (VDecl->isBlockVarDecl()) {
1275 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001276 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001277 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001278 VDecl->setInvalidDecl();
1279 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +00001280 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001281 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001282 if (SC == VarDecl::Static) // C99 6.7.8p4.
1283 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001284 }
Steve Naroff248a7532008-04-15 22:42:06 +00001285 } else if (VDecl->isFileVarDecl()) {
1286 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001287 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001288 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001289 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001290 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001291
1292 // C99 6.7.8p4. All file scoped initializers need to be constant.
1293 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001294 }
1295 // If the type changed, it means we had an incomplete type that was
1296 // completed by the initializer. For example:
1297 // int ary[] = { 1, 3, 5 };
1298 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001299 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001300 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001301 Init->setType(DclT);
1302 }
Steve Naroffbb204692007-09-12 14:07:44 +00001303
1304 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001305 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001306 return;
1307}
1308
Reid Spencer5f016e22007-07-11 17:01:13 +00001309/// The declarators are chained together backwards, reverse the list.
1310Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1311 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001312 Decl *GroupDecl = static_cast<Decl*>(group);
1313 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001314 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001315
1316 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1317 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001318 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001320 else { // reverse the list.
1321 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001322 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001323 Group->setNextDeclarator(NewGroup);
1324 NewGroup = Group;
1325 Group = Next;
1326 }
1327 }
1328 // Perform semantic analysis that depends on having fully processed both
1329 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001330 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001331 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1332 if (!IDecl)
1333 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001334 QualType T = IDecl->getType();
1335
1336 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1337 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001338 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1339 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +00001340 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001341 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1342 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001343 }
1344 }
1345 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1346 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001347 if (IDecl->isBlockVarDecl() &&
1348 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001349 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001350 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1351 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001352 IDecl->setInvalidDecl();
1353 }
1354 }
1355 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1356 // object that has file scope without an initializer, and without a
1357 // storage-class specifier or with the storage-class specifier "static",
1358 // constitutes a tentative definition. Note: A tentative definition with
1359 // external linkage is valid (C99 6.2.2p5).
Steve Naroff248a7532008-04-15 22:42:06 +00001360 if (IDecl && !IDecl->getInit() &&
1361 (IDecl->getStorageClass() == VarDecl::Static ||
1362 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001363 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001364 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1365 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001366 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001367 // C99 6.9.2p3: If the declaration of an identifier for an object is
1368 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1369 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001370 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1371 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001372 IDecl->setInvalidDecl();
1373 }
1374 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001375 }
1376 return NewGroup;
1377}
Steve Naroffe1223f72007-08-28 03:03:08 +00001378
Chris Lattner04421082008-04-08 04:40:51 +00001379/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1380/// to introduce parameters into function prototype scope.
1381Sema::DeclTy *
1382Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00001383 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001384
1385 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1386 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1387 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1388 Diag(DS.getStorageClassSpecLoc(),
1389 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001390 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001391 }
1392 if (DS.isThreadSpecified()) {
1393 Diag(DS.getThreadSpecLoc(),
1394 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001395 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001396 }
1397
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001398 // Check that there are no default arguments inside the type of this
1399 // parameter (C++ only).
1400 if (getLangOptions().CPlusPlus)
1401 CheckExtraCXXDefaultArguments(D);
1402
Chris Lattner04421082008-04-08 04:40:51 +00001403 // In this context, we *do not* check D.getInvalidType(). If the declarator
1404 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1405 // though it will not reflect the user specified type.
1406 QualType parmDeclType = GetTypeForDeclarator(D, S);
1407
1408 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1409
Reid Spencer5f016e22007-07-11 17:01:13 +00001410 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1411 // Can this happen for params? We already checked that they don't conflict
1412 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001413 IdentifierInfo *II = D.getIdentifier();
1414 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1415 if (S->isDeclScope(PrevDecl)) {
1416 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1417 dyn_cast<NamedDecl>(PrevDecl)->getName());
1418
1419 // Recover by removing the name
1420 II = 0;
1421 D.SetIdentifier(0, D.getIdentifierLoc());
1422 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001423 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001424
1425 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1426 // Doing the promotion here has a win and a loss. The win is the type for
1427 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1428 // code generator). The loss is the orginal type isn't preserved. For example:
1429 //
1430 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1431 // int blockvardecl[5];
1432 // sizeof(parmvardecl); // size == 4
1433 // sizeof(blockvardecl); // size == 20
1434 // }
1435 //
1436 // For expressions, all implicit conversions are captured using the
1437 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1438 //
1439 // FIXME: If a source translation tool needs to see the original type, then
1440 // we need to consider storing both types (in ParmVarDecl)...
1441 //
Chris Lattnere6327742008-04-02 05:18:44 +00001442 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001443 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001444 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001445 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001446 parmDeclType = Context.getPointerType(parmDeclType);
1447
Chris Lattner04421082008-04-08 04:40:51 +00001448 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1449 D.getIdentifierLoc(), II,
1450 parmDeclType, VarDecl::None,
1451 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001452
Chris Lattner04421082008-04-08 04:40:51 +00001453 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001454 New->setInvalidDecl();
1455
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001456 if (II)
1457 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001458
Nate Begemanfc584522008-05-09 16:56:01 +00001459 HandleDeclAttributes(New, D.getDeclSpec().getAttributes(),
1460 D.getAttributes());
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001462
Reid Spencer5f016e22007-07-11 17:01:13 +00001463}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001464
Chris Lattnerb652cea2007-10-09 17:14:05 +00001465Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001466 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1468 "Not a function declarator!");
1469 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001470
Reid Spencer5f016e22007-07-11 17:01:13 +00001471 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1472 // for a K&R function.
1473 if (!FTI.hasPrototype) {
1474 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001475 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1477 FTI.ArgInfo[i].Ident->getName());
1478 // Implicitly declare the argument as type 'int' for lack of a better
1479 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001480 DeclSpec DS;
1481 const char* PrevSpec; // unused
1482 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1483 PrevSpec);
1484 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1485 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1486 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 }
1488 }
Chris Lattner52804082008-02-17 19:31:09 +00001489
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 // Since this is a function definition, act as though we have information
1491 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001492 if (FTI.NumArgs)
1493 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001495 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001496 }
1497
1498 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001499
1500 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001501 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001502 GlobalScope);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001503 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1504 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1505 const FunctionDecl *Definition;
1506 if (FD->getBody(Definition)) {
1507 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1508 D.getIdentifier()->getName());
1509 Diag(Definition->getLocation(), diag::err_previous_definition);
1510 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001511 }
1512 }
Steve Narofffabbc342008-02-12 01:09:36 +00001513 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001514 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerb048c982008-04-06 04:47:34 +00001515 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001516
1517 // Check the validity of our function parameters
1518 CheckParmsForFunctionDef(FD);
1519
1520 // Introduce our parameters into the function scope
1521 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1522 ParmVarDecl *Param = FD->getParamDecl(p);
1523 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001524 if (Param->getIdentifier())
1525 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 }
Chris Lattner04421082008-04-08 04:40:51 +00001527
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 return FD;
1529}
1530
Steve Naroffd6d054d2007-11-11 23:20:51 +00001531Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1532 Decl *dcl = static_cast<Decl *>(D);
1533 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1534 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001535 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001536 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001537 MD->setBody((Stmt*)Body);
Steve Naroff4d832202007-12-13 18:18:56 +00001538 }
Chris Lattnerb048c982008-04-06 04:47:34 +00001539 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 // Verify and clean out per-function state.
1541
1542 // Check goto/label use.
1543 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1544 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1545 // Verify that we have no forward references left. If so, there was a goto
1546 // or address of a label taken, but no definition of it. Label fwd
1547 // definitions are indicated with a null substmt.
1548 if (I->second->getSubStmt() == 0) {
1549 LabelStmt *L = I->second;
1550 // Emit error.
1551 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1552
1553 // At this point, we have gotos that use the bogus label. Stitch it into
1554 // the function body so that they aren't leaked and that the AST is well
1555 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001556 if (Body) {
1557 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1558 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1559 } else {
1560 // The whole function wasn't parsed correctly, just delete this.
1561 delete L;
1562 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 }
1564 }
1565 LabelMap.clear();
1566
Steve Naroffd6d054d2007-11-11 23:20:51 +00001567 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001568}
1569
Reid Spencer5f016e22007-07-11 17:01:13 +00001570/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1571/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001572ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1573 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001574 // Extension in C99. Legal in C90, but warn about it.
1575 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001577 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1579
1580 // FIXME: handle stuff like:
1581 // void foo() { extern float X(); }
1582 // void bar() { X(); } <-- implicit decl for X in another scope.
1583
1584 // Set a Declarator for the implicit definition: int foo();
1585 const char *Dummy;
1586 DeclSpec DS;
1587 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1588 Error = Error; // Silence warning.
1589 assert(!Error && "Error setting up implicit decl!");
1590 Declarator D(DS, Declarator::BlockContext);
1591 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1592 D.SetIdentifier(&II, Loc);
1593
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001594 // Insert this function into translation-unit scope.
1595
1596 DeclContext *PrevDC = CurContext;
1597 CurContext = Context.getTranslationUnitDecl();
1598
Steve Naroffe2ef8152008-04-04 14:32:09 +00001599 FunctionDecl *FD =
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001600 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001601 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001602
1603 CurContext = PrevDC;
1604
Steve Naroffe2ef8152008-04-04 14:32:09 +00001605 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001606}
1607
1608
Chris Lattner41af0932007-11-14 06:34:38 +00001609TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001610 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001612 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001613
1614 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001615 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1616 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001617 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001618 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001619 if (D.getInvalidType())
1620 NewTD->setInvalidDecl();
1621 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001622}
1623
Steve Naroff08d92e42007-09-15 18:49:24 +00001624/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001625/// former case, Name will be non-null. In the later case, Name will be null.
1626/// TagType indicates what kind of tag this is. TK indicates whether this is a
1627/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001628Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001629 SourceLocation KWLoc, IdentifierInfo *Name,
1630 SourceLocation NameLoc, AttributeList *Attr) {
1631 // If this is a use of an existing tag, it must have a name.
1632 assert((Name != 0 || TK == TK_Definition) &&
1633 "Nameless record must be a definition!");
1634
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001635 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00001636 switch (TagType) {
1637 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001638 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1639 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1640 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1641 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 }
1643
1644 // If this is a named struct, check to see if there was a previous forward
1645 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001646 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1647 if (ScopedDecl *PrevDecl =
1648 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001649
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001650 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1651 "unexpected Decl type");
1652 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1653 // If this is a use of a previous tag, or if the tag is already declared in
1654 // the same scope (so that the definition/declaration completes or
1655 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001656 if (TK == TK_Reference ||
1657 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001658 // Make sure that this wasn't declared as an enum and now used as a struct
1659 // or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001660 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001661 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1662 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1663 }
1664
1665 // If this is a use or a forward declaration, we're good.
1666 if (TK != TK_Definition)
1667 return PrevDecl;
Reid Spencer5f016e22007-07-11 17:01:13 +00001668
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001669 // Diagnose attempts to redefine a tag.
1670 if (PrevTagDecl->isDefinition()) {
1671 Diag(NameLoc, diag::err_redefinition, Name->getName());
1672 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1673 // If this is a redefinition, recover by making this struct be
1674 // anonymous, which will make any later references get the previous
1675 // definition.
1676 Name = 0;
1677 } else {
1678 // Okay, this is definition of a previously declared or referenced tag.
1679 // Move the location of the decl to be the definition site.
1680 PrevDecl->setLocation(NameLoc);
1681 return PrevDecl;
1682 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001684 // If we get here, this is a definition of a new struct type in a nested
1685 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1686 // type.
1687 } else {
1688 // The tag name clashes with a namespace name, issue an error and recover
1689 // by making this tag be anonymous.
1690 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1691 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1692 Name = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001693 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 }
1695
1696 // If there is an identifier, use the location of the identifier as the
1697 // location of the decl, otherwise use the location of the struct/union
1698 // keyword.
1699 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1700
1701 // Otherwise, if this is the first time we've seen this tag, create the decl.
1702 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001703 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1705 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001706 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001707 // If this is an undefined enum, warn.
1708 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001709 } else {
1710 // struct/union/class
1711
Reid Spencer5f016e22007-07-11 17:01:13 +00001712 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1713 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001714 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001715 }
1716
1717 // If this has an identifier, add it to the scope stack.
1718 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001719 // The scope passed in may not be a decl scope. Zip up the scope tree until
1720 // we find one that is.
1721 while ((S->getFlags() & Scope::DeclScope) == 0)
1722 S = S->getParent();
1723
1724 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001725 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001727
Anders Carlssonad148062008-02-16 00:29:18 +00001728 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001729 return New;
1730}
1731
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001732/// Collect the instance variables declared in an Objective-C object. Used in
1733/// the creation of structures from objects using the @defs directive.
1734static void CollectIvars(ObjCInterfaceDecl *Class,
1735 llvm::SmallVector<Sema::DeclTy*, 16> &ivars) {
1736 if (Class->getSuperClass())
1737 CollectIvars(Class->getSuperClass(), ivars);
1738 ivars.append(Class->ivar_begin(), Class->ivar_end());
1739}
1740
1741/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1742/// instance variables of ClassName into Decls.
1743void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1744 IdentifierInfo *ClassName,
1745 llvm::SmallVector<DeclTy*, 16> &Decls) {
1746 // Check that ClassName is a valid class
1747 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1748 if (!Class) {
1749 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1750 return;
1751 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001752 // Collect the instance variables
1753 CollectIvars(Class, Decls);
1754}
1755
1756
Eli Friedman1b76ada2008-06-03 21:01:11 +00001757static bool CalcFakeICEVal(const Expr* Expr,
1758 llvm::APSInt& Result,
1759 ASTContext& Context) {
1760 // Calculate the value of an expression that has a calculatable
1761 // value, but isn't an ICE. Currently, this only supports
1762 // a very narrow set of extensions, but it can be expanded if needed.
1763 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Expr))
1764 return CalcFakeICEVal(PE->getSubExpr(), Result, Context);
1765
1766 if (const CastExpr *CE = dyn_cast<CastExpr>(Expr)) {
1767 QualType CETy = CE->getType();
1768 if ((CETy->isIntegralType() && !CETy->isBooleanType()) ||
1769 CETy->isPointerType()) {
1770 if (CalcFakeICEVal(CE->getSubExpr(), Result, Context)) {
1771 Result.extOrTrunc(Context.getTypeSize(CETy));
1772 // FIXME: This assumes pointers are signed.
1773 Result.setIsSigned(CETy->isSignedIntegerType() ||
1774 CETy->isPointerType());
1775 return true;
1776 }
1777 }
1778 }
1779
1780 if (Expr->getType()->isIntegralType())
1781 return Expr->isIntegerConstantExpr(Result, Context);
1782
1783 return false;
1784}
1785
1786QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1787 // This method tries to turn a variable array into a constant
1788 // array even when the size isn't an ICE. This is necessary
1789 // for compatibility with code that depends on gcc's buggy
1790 // constant expression folding, like struct {char x[(int)(char*)2];}
1791 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
1792 llvm::APSInt Result(32);
1793 if (VLATy->getSizeExpr() &&
1794 CalcFakeICEVal(VLATy->getSizeExpr(), Result, Context) &&
1795 Result > llvm::APSInt(Result.getBitWidth(), Result.isUnsigned())) {
1796 return Context.getConstantArrayType(VLATy->getElementType(),
1797 Result, ArrayType::Normal, 0);
1798 }
1799 }
1800 return QualType();
1801}
1802
Steve Naroff08d92e42007-09-15 18:49:24 +00001803/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001804/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001805Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001806 SourceLocation DeclStart,
1807 Declarator &D, ExprTy *BitfieldWidth) {
1808 IdentifierInfo *II = D.getIdentifier();
1809 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001810 SourceLocation Loc = DeclStart;
1811 if (II) Loc = D.getIdentifierLoc();
1812
1813 // FIXME: Unnamed fields can be handled in various different ways, for
1814 // example, unnamed unions inject all members into the struct namespace!
1815
1816
1817 if (BitWidth) {
1818 // TODO: Validate.
1819 //printf("WARNING: BITFIELDS IGNORED!\n");
1820
1821 // 6.7.2.1p3
1822 // 6.7.2.1p4
1823
1824 } else {
1825 // Not a bitfield.
1826
1827 // validate II.
1828
1829 }
1830
1831 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001832 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1833 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001834
Reid Spencer5f016e22007-07-11 17:01:13 +00001835 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1836 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001837 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00001838 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1839 if (!FixedTy.isNull()) {
1840 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1841 T = FixedTy;
1842 } else {
1843 // FIXME: This diagnostic needs work
1844 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1845 InvalidDecl = true;
1846 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001847 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001848 // FIXME: Chain fielddecls together.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001849 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001850
Anders Carlssonad148062008-02-16 00:29:18 +00001851 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1852 D.getAttributes());
1853
Steve Naroff5912a352007-08-28 20:14:24 +00001854 if (D.getInvalidType() || InvalidDecl)
1855 NewFD->setInvalidDecl();
1856 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001857}
1858
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001859/// TranslateIvarVisibility - Translate visibility from a token ID to an
1860/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001861static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001862TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001863 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001864 case tok::objc_private: return ObjCIvarDecl::Private;
1865 case tok::objc_public: return ObjCIvarDecl::Public;
1866 case tok::objc_protected: return ObjCIvarDecl::Protected;
1867 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001868 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001869 }
1870}
1871
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001872/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1873/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001874Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001875 SourceLocation DeclStart,
1876 Declarator &D, ExprTy *BitfieldWidth,
1877 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001878 IdentifierInfo *II = D.getIdentifier();
1879 Expr *BitWidth = (Expr*)BitfieldWidth;
1880 SourceLocation Loc = DeclStart;
1881 if (II) Loc = D.getIdentifierLoc();
1882
1883 // FIXME: Unnamed fields can be handled in various different ways, for
1884 // example, unnamed unions inject all members into the struct namespace!
1885
1886
1887 if (BitWidth) {
1888 // TODO: Validate.
1889 //printf("WARNING: BITFIELDS IGNORED!\n");
1890
1891 // 6.7.2.1p3
1892 // 6.7.2.1p4
1893
1894 } else {
1895 // Not a bitfield.
1896
1897 // validate II.
1898
1899 }
1900
1901 QualType T = GetTypeForDeclarator(D, S);
1902 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1903 bool InvalidDecl = false;
1904
1905 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1906 // than a variably modified type.
1907 if (T->isVariablyModifiedType()) {
1908 // FIXME: This diagnostic needs work
1909 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1910 InvalidDecl = true;
1911 }
1912
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001913 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001914
1915 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1916 D.getAttributes());
1917
1918 if (D.getInvalidType() || InvalidDecl)
1919 NewID->setInvalidDecl();
1920 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001921 if (Visibility != tok::objc_not_keyword)
1922 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001923 return NewID;
1924}
1925
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001926void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001927 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001928 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001929 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001930 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1931 assert(EnclosingDecl && "missing record or interface decl");
1932 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1933
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001934 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001935 // Diagnose code like:
1936 // struct S { struct S {} X; };
1937 // We discover this when we complete the outer S. Reject and ignore the
1938 // outer S.
1939 Diag(Record->getLocation(), diag::err_nested_redefinition,
1940 Record->getKindName());
1941 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001942 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 return;
1944 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001945 // Verify that all the fields are okay.
1946 unsigned NumNamedMembers = 0;
1947 llvm::SmallVector<FieldDecl*, 32> RecFields;
1948 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001949
Reid Spencer5f016e22007-07-11 17:01:13 +00001950 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001951
Steve Naroff74216642007-09-14 22:20:54 +00001952 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1953 assert(FD && "missing field decl");
1954
1955 // Remember all fields.
1956 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001957
1958 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001959 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00001960
Reid Spencer5f016e22007-07-11 17:01:13 +00001961 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001962 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001963 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001965 FD->setInvalidDecl();
1966 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001967 continue;
1968 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001969 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1970 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001971 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001972 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001973 FD->setInvalidDecl();
1974 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001975 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001976 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001977 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001978 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001979 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001980 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001981 FD->setInvalidDecl();
1982 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 continue;
1984 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001985 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001986 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1987 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001988 FD->setInvalidDecl();
1989 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001990 continue;
1991 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001993 if (Record)
1994 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001996 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1997 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001998 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001999 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2000 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002001 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002002 Record->setHasFlexibleArrayMember(true);
2003 } else {
2004 // If this is a struct/class and this is not the last element, reject
2005 // it. Note that GCC supports variable sized arrays in the middle of
2006 // structures.
2007 if (i != NumFields-1) {
2008 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2009 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002010 FD->setInvalidDecl();
2011 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 continue;
2013 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002014 // We support flexible arrays at the end of structs in other structs
2015 // as an extension.
2016 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2017 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002018 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002019 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002020 }
2021 }
2022 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002023 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002024 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002025 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2026 FD->getName());
2027 FD->setInvalidDecl();
2028 EnclosingDecl->setInvalidDecl();
2029 continue;
2030 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002031 // Keep track of the number of named members.
2032 if (IdentifierInfo *II = FD->getIdentifier()) {
2033 // Detect duplicate member names.
2034 if (!FieldIDs.insert(II)) {
2035 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2036 // Find the previous decl.
2037 SourceLocation PrevLoc;
2038 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2039 assert(i != e && "Didn't find previous def!");
2040 if (RecFields[i]->getIdentifier() == II) {
2041 PrevLoc = RecFields[i]->getLocation();
2042 break;
2043 }
2044 }
2045 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002046 FD->setInvalidDecl();
2047 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002048 continue;
2049 }
2050 ++NumNamedMembers;
2051 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002052 }
2053
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002055 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002056 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00002057 Consumer.HandleTagDeclDefinition(Record);
2058 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002059 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2060 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2061 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2062 else if (ObjCImplementationDecl *IMPDecl =
2063 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002064 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2065 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002066 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002067 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002068 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002069}
2070
Steve Naroff08d92e42007-09-15 18:49:24 +00002071Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002072 DeclTy *lastEnumConst,
2073 SourceLocation IdLoc, IdentifierInfo *Id,
2074 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002075 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002076 EnumConstantDecl *LastEnumConst =
2077 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2078 Expr *Val = static_cast<Expr*>(val);
2079
Chris Lattner31e05722007-08-26 06:24:45 +00002080 // The scope passed in may not be a decl scope. Zip up the scope tree until
2081 // we find one that is.
2082 while ((S->getFlags() & Scope::DeclScope) == 0)
2083 S = S->getParent();
2084
Reid Spencer5f016e22007-07-11 17:01:13 +00002085 // Verify that there isn't already something declared with this name in this
2086 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002087 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00002088 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002089 if (isa<EnumConstantDecl>(PrevDecl))
2090 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2091 else
2092 Diag(IdLoc, diag::err_redefinition, Id->getName());
2093 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002094 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002095 return 0;
2096 }
2097 }
2098
2099 llvm::APSInt EnumVal(32);
2100 QualType EltTy;
2101 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002102 // Make sure to promote the operand type to int.
2103 UsualUnaryConversions(Val);
2104
Reid Spencer5f016e22007-07-11 17:01:13 +00002105 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2106 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002107 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002108 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2109 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002110 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002111 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002112 } else {
2113 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002114 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002115 }
2116
2117 if (!Val) {
2118 if (LastEnumConst) {
2119 // Assign the last value + 1.
2120 EnumVal = LastEnumConst->getInitVal();
2121 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002122
2123 // Check for overflow on increment.
2124 if (EnumVal < LastEnumConst->getInitVal())
2125 Diag(IdLoc, diag::warn_enum_value_overflow);
2126
Chris Lattnerb7416f92007-08-27 17:37:24 +00002127 EltTy = LastEnumConst->getType();
2128 } else {
2129 // First value, set to zero.
2130 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002131 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002132 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 }
2134
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002135 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002136 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2137 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002138 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002139
2140 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002141 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002142 return New;
2143}
2144
Steve Naroff08d92e42007-09-15 18:49:24 +00002145void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 DeclTy **Elements, unsigned NumElements) {
2147 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
2148 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
2149
Chris Lattnere37f0be2007-08-28 05:10:31 +00002150 // TODO: If the result value doesn't fit in an int, it must be a long or long
2151 // long value. ISO C does not support this, but GCC does as an extension,
2152 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002153 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002154
Chris Lattnerac609682007-08-28 06:15:15 +00002155 // Verify that all the values are okay, compute the size of the values, and
2156 // reverse the list.
2157 unsigned NumNegativeBits = 0;
2158 unsigned NumPositiveBits = 0;
2159
2160 // Keep track of whether all elements have type int.
2161 bool AllElementsInt = true;
2162
Reid Spencer5f016e22007-07-11 17:01:13 +00002163 EnumConstantDecl *EltList = 0;
2164 for (unsigned i = 0; i != NumElements; ++i) {
2165 EnumConstantDecl *ECD =
2166 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2167 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002168
2169 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002170 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002171 assert(InitVal.getBitWidth() >= IntWidth &&
2172 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002173 if (InitVal.getBitWidth() > IntWidth) {
2174 llvm::APSInt V(InitVal);
2175 V.trunc(IntWidth);
2176 V.extend(InitVal.getBitWidth());
2177 if (V != InitVal)
2178 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2179 InitVal.toString());
2180 }
Chris Lattnerac609682007-08-28 06:15:15 +00002181
2182 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002183 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002184 NumPositiveBits = std::max(NumPositiveBits,
2185 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002186 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002187 NumNegativeBits = std::max(NumNegativeBits,
2188 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002189
Chris Lattnerac609682007-08-28 06:15:15 +00002190 // Keep track of whether every enum element has type int (very commmon).
2191 if (AllElementsInt)
2192 AllElementsInt = ECD->getType() == Context.IntTy;
2193
Reid Spencer5f016e22007-07-11 17:01:13 +00002194 ECD->setNextDeclarator(EltList);
2195 EltList = ECD;
2196 }
2197
Chris Lattnerac609682007-08-28 06:15:15 +00002198 // Figure out the type that should be used for this enum.
2199 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2200 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002201 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002202
2203 if (NumNegativeBits) {
2204 // If there is a negative value, figure out the smallest integer type (of
2205 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002206 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002207 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002208 BestWidth = IntWidth;
2209 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002210 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002211
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002212 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002213 BestType = Context.LongTy;
2214 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002215 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002216
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002217 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002218 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2219 BestType = Context.LongLongTy;
2220 }
2221 }
2222 } else {
2223 // If there is no negative value, figure out which of uint, ulong, ulonglong
2224 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002225 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002226 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002227 BestWidth = IntWidth;
2228 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002229 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002230 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002231 } else {
2232 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002233 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002234 "How could an initializer get larger than ULL?");
2235 BestType = Context.UnsignedLongLongTy;
2236 }
2237 }
2238
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002239 // Loop over all of the enumerator constants, changing their types to match
2240 // the type of the enum if needed.
2241 for (unsigned i = 0; i != NumElements; ++i) {
2242 EnumConstantDecl *ECD =
2243 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2244 if (!ECD) continue; // Already issued a diagnostic.
2245
2246 // Standard C says the enumerators have int type, but we allow, as an
2247 // extension, the enumerators to be larger than int size. If each
2248 // enumerator value fits in an int, type it as an int, otherwise type it the
2249 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2250 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002251 if (ECD->getType() == Context.IntTy) {
2252 // Make sure the init value is signed.
2253 llvm::APSInt IV = ECD->getInitVal();
2254 IV.setIsSigned(true);
2255 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002256 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002257 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002258
2259 // Determine whether the value fits into an int.
2260 llvm::APSInt InitVal = ECD->getInitVal();
2261 bool FitsInInt;
2262 if (InitVal.isUnsigned() || !InitVal.isNegative())
2263 FitsInInt = InitVal.getActiveBits() < IntWidth;
2264 else
2265 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2266
2267 // If it fits into an integer type, force it. Otherwise force it to match
2268 // the enum decl type.
2269 QualType NewTy;
2270 unsigned NewWidth;
2271 bool NewSign;
2272 if (FitsInInt) {
2273 NewTy = Context.IntTy;
2274 NewWidth = IntWidth;
2275 NewSign = true;
2276 } else if (ECD->getType() == BestType) {
2277 // Already the right type!
2278 continue;
2279 } else {
2280 NewTy = BestType;
2281 NewWidth = BestWidth;
2282 NewSign = BestType->isSignedIntegerType();
2283 }
2284
2285 // Adjust the APSInt value.
2286 InitVal.extOrTrunc(NewWidth);
2287 InitVal.setIsSigned(NewSign);
2288 ECD->setInitVal(InitVal);
2289
2290 // Adjust the Expr initializer and type.
2291 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2292 ECD->setType(NewTy);
2293 }
Chris Lattnerac609682007-08-28 06:15:15 +00002294
Chris Lattnere00b18c2007-08-28 18:24:31 +00002295 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002296 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002297}
2298
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002299Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2300 ExprTy *expr) {
2301 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2302
Chris Lattner8e25d862008-03-16 00:16:02 +00002303 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002304}
2305
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002306Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002307 SourceLocation LBrace,
2308 SourceLocation RBrace,
2309 const char *Lang,
2310 unsigned StrSize,
2311 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002312 LinkageSpecDecl::LanguageIDs Language;
2313 Decl *dcl = static_cast<Decl *>(D);
2314 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2315 Language = LinkageSpecDecl::lang_c;
2316 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2317 Language = LinkageSpecDecl::lang_cxx;
2318 else {
2319 Diag(Loc, diag::err_bad_language);
2320 return 0;
2321 }
2322
2323 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002324 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002325}