blob: b954c8b2e1146b37c3c8e299c1a31909a05c2f4c [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"
22#include "clang/AST/Type.h"
23#include "clang/Parse/DeclSpec.h"
24#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000027#include "clang/Basic/SourceManager.h"
Eli Friedmanc594b322008-05-20 13:48:25 +000028#include "clang/AST/ExprCXX.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000029// 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 Lattnerddee4232008-03-03 03:28:21 +0000263/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
264static bool DeclHasAttr(const Decl *decl, const Attr *target) {
265 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
266 if (attr->getKind() == target->getKind())
267 return true;
268
269 return false;
270}
271
272/// MergeAttributes - append attributes from the Old decl to the New one.
273static void MergeAttributes(Decl *New, Decl *Old) {
274 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
275
Chris Lattnerddee4232008-03-03 03:28:21 +0000276 while (attr) {
277 tmp = attr;
278 attr = attr->getNext();
279
280 if (!DeclHasAttr(New, tmp)) {
281 New->addAttr(tmp);
282 } else {
283 tmp->setNext(0);
284 delete(tmp);
285 }
286 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000287
288 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000289}
290
Chris Lattner04421082008-04-08 04:40:51 +0000291/// MergeFunctionDecl - We just parsed a function 'New' from
292/// declarator D which has the same name and scope as a previous
293/// declaration 'Old'. Figure out how to resolve this situation,
294/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000295/// Redeclaration will be set true if thisNew is a redeclaration OldD.
296FunctionDecl *
297Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
298 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000299 // Verify the old decl was also a function.
300 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
301 if (!Old) {
302 Diag(New->getLocation(), diag::err_redefinition_different_kind,
303 New->getName());
304 Diag(OldD->getLocation(), diag::err_previous_definition);
305 return New;
306 }
Chris Lattner04421082008-04-08 04:40:51 +0000307
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000308 QualType OldQType = Context.getCanonicalType(Old->getType());
309 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000310
Chris Lattner04421082008-04-08 04:40:51 +0000311 // C++ [dcl.fct]p3:
312 // All declarations for a function shall agree exactly in both the
313 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000314 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
315 MergeAttributes(New, Old);
316 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000317 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000318 }
Chris Lattner04421082008-04-08 04:40:51 +0000319
320 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000321 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000322 if (!getLangOptions().CPlusPlus &&
323 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000324 MergeAttributes(New, Old);
325 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000326 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000327 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000328
Steve Naroff837618c2008-01-16 15:01:34 +0000329 // A function that has already been declared has been redeclared or defined
330 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000331 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000332 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000333 PrevDiag = diag::err_previous_definition;
334 else if (Old->isImplicit())
335 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000336 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000337 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000338
Reid Spencer5f016e22007-07-11 17:01:13 +0000339 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
340 // TODO: This is totally simplistic. It should handle merging functions
341 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000342 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
343 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000344 return New;
345}
346
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000347/// equivalentArrayTypes - Used to determine whether two array types are
348/// equivalent.
349/// We need to check this explicitly as an incomplete array definition is
350/// considered a VariableArrayType, so will not match a complete array
351/// definition that would be otherwise equivalent.
352static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
353 const ArrayType *NewAT = NewQType->getAsArrayType();
354 const ArrayType *OldAT = OldQType->getAsArrayType();
355
356 if (!NewAT || !OldAT)
357 return false;
358
359 // If either (or both) array types in incomplete we need to strip off the
360 // outer VariableArrayType. Once the outer VAT is removed the remaining
361 // types must be identical if the array types are to be considered
362 // equivalent.
363 // eg. int[][1] and int[1][1] become
364 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
365 // removing the outermost VAT gives
366 // CAT(1, int) and CAT(1, int)
367 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000368 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000369 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
370 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000371 NewQType = NewAT->getElementType().getCanonicalType();
372 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000373 }
374
375 return NewQType == OldQType;
376}
377
Reid Spencer5f016e22007-07-11 17:01:13 +0000378/// MergeVarDecl - We just parsed a variable 'New' which has the same name
379/// and scope as a previous declaration 'Old'. Figure out how to resolve this
380/// situation, merging decls or emitting diagnostics as appropriate.
381///
382/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
383/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
384///
Steve Naroffe8043c32008-04-01 23:04:06 +0000385VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 // Verify the old decl was also a variable.
387 VarDecl *Old = dyn_cast<VarDecl>(OldD);
388 if (!Old) {
389 Diag(New->getLocation(), diag::err_redefinition_different_kind,
390 New->getName());
391 Diag(OldD->getLocation(), diag::err_previous_definition);
392 return New;
393 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000394
395 MergeAttributes(New, Old);
396
Reid Spencer5f016e22007-07-11 17:01:13 +0000397 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000398 QualType OldCType = Context.getCanonicalType(Old->getType());
399 QualType NewCType = Context.getCanonicalType(New->getType());
400 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 Diag(New->getLocation(), diag::err_redefinition, New->getName());
402 Diag(Old->getLocation(), diag::err_previous_definition);
403 return New;
404 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000405 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
406 if (New->getStorageClass() == VarDecl::Static &&
407 (Old->getStorageClass() == VarDecl::None ||
408 Old->getStorageClass() == VarDecl::Extern)) {
409 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
410 Diag(Old->getLocation(), diag::err_previous_definition);
411 return New;
412 }
413 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
414 if (New->getStorageClass() != VarDecl::Static &&
415 Old->getStorageClass() == VarDecl::Static) {
416 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
417 Diag(Old->getLocation(), diag::err_previous_definition);
418 return New;
419 }
420 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff248a7532008-04-15 22:42:06 +0000421 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb7b032e2008-01-30 00:44:01 +0000422 // Handle C "tentative" external object definitions (C99 6.9.2).
423 bool OldIsTentative = false;
424 bool NewIsTentative = false;
425
Steve Naroff248a7532008-04-15 22:42:06 +0000426 if (!Old->getInit() &&
427 (Old->getStorageClass() == VarDecl::None ||
428 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000429 OldIsTentative = true;
430
431 // FIXME: this check doesn't work (since the initializer hasn't been
432 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
433 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
434 // thrown out the old decl.
Steve Naroff248a7532008-04-15 22:42:06 +0000435 if (!New->getInit() &&
436 (New->getStorageClass() == VarDecl::None ||
437 New->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000438 ; // change to NewIsTentative = true; once the code is moved.
439
440 if (NewIsTentative || OldIsTentative)
441 return New;
442 }
Steve Naroff235549c2008-05-12 22:36:43 +0000443 // Handle __private_extern__ just like extern.
Steve Naroffb7b032e2008-01-30 00:44:01 +0000444 if (Old->getStorageClass() != VarDecl::Extern &&
Steve Naroff235549c2008-05-12 22:36:43 +0000445 Old->getStorageClass() != VarDecl::PrivateExtern &&
446 New->getStorageClass() != VarDecl::Extern &&
447 New->getStorageClass() != VarDecl::PrivateExtern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000448 Diag(New->getLocation(), diag::err_redefinition, New->getName());
449 Diag(Old->getLocation(), diag::err_previous_definition);
450 }
451 return New;
452}
453
Chris Lattner04421082008-04-08 04:40:51 +0000454/// CheckParmsForFunctionDef - Check that the parameters of the given
455/// function are appropriate for the definition of a function. This
456/// takes care of any checks that cannot be performed on the
457/// declaration itself, e.g., that the types of each of the function
458/// parameters are complete.
459bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
460 bool HasInvalidParm = false;
461 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
462 ParmVarDecl *Param = FD->getParamDecl(p);
463
464 // C99 6.7.5.3p4: the parameters in a parameter type list in a
465 // function declarator that is part of a function definition of
466 // that function shall not have incomplete type.
467 if (Param->getType()->isIncompleteType() &&
468 !Param->isInvalidDecl()) {
469 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
470 Param->getType().getAsString());
471 Param->setInvalidDecl();
472 HasInvalidParm = true;
473 }
474 }
475
476 return HasInvalidParm;
477}
478
479/// CreateImplicitParameter - Creates an implicit function parameter
480/// in the scope S and with the given type. This routine is used, for
481/// example, to create the implicit "self" parameter in an Objective-C
482/// method.
Chris Lattner41110242008-06-17 18:05:57 +0000483ImplicitParamDecl *
Chris Lattner04421082008-04-08 04:40:51 +0000484Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
485 SourceLocation IdLoc, QualType Type) {
Chris Lattner41110242008-06-17 18:05:57 +0000486 ImplicitParamDecl *New = ImplicitParamDecl::Create(Context, CurContext,
487 IdLoc, Id, Type, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000488 if (Id)
489 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000490
491 return New;
492}
493
Reid Spencer5f016e22007-07-11 17:01:13 +0000494/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
495/// no declarator (e.g. "struct foo;") is parsed.
496Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
497 // TODO: emit error on 'int;' or 'const enum foo;'.
498 // TODO: emit error on 'typedef int;'
499 // if (!DS.isMissingDeclaratorOk()) Diag(...);
500
Steve Naroff92199282007-11-17 21:37:36 +0000501 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000502}
503
Steve Naroffd0091aa2008-01-10 22:15:12 +0000504bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000505 // Get the type before calling CheckSingleAssignmentConstraints(), since
506 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000507 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000508
Chris Lattner5cf216b2008-01-04 18:04:52 +0000509 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
510 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
511 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000512}
513
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000514bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000515 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000516 // C99 6.7.8p14. We have an array of character type with unknown size
517 // being initialized to a string literal.
518 llvm::APSInt ConstVal(32);
519 ConstVal = strLiteral->getByteLength() + 1;
520 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000521 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000522 ArrayType::Normal, 0);
523 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
524 // C99 6.7.8p14. We have an array of character type with known size.
525 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
526 Diag(strLiteral->getSourceRange().getBegin(),
527 diag::warn_initializer_string_for_char_array_too_long,
528 strLiteral->getSourceRange());
529 } else {
530 assert(0 && "HandleStringLiteralInit(): Invalid array type");
531 }
532 // Set type from "char *" to "constant array of char".
533 strLiteral->setType(DeclT);
534 // For now, we always return false (meaning success).
535 return false;
536}
537
538StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000539 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000540 if (AT && AT->getElementType()->isCharType()) {
541 return dyn_cast<StringLiteral>(Init);
542 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000543 return 0;
544}
545
Steve Naroffa9960332008-01-25 00:51:06 +0000546bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000547 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
548 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000549 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000550 return Diag(VAT->getSizeExpr()->getLocStart(),
551 diag::err_variable_object_no_init,
552 VAT->getSizeExpr()->getSourceRange());
553
Steve Naroff2fdc3742007-12-10 22:44:33 +0000554 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
555 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000556 // FIXME: Handle wide strings
557 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
558 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000559
560 if (DeclType->isArrayType())
561 return Diag(Init->getLocStart(),
562 diag::err_array_init_list_required,
563 Init->getSourceRange());
564
Steve Naroffd0091aa2008-01-10 22:15:12 +0000565 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000566 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000567
Steve Naroff0cca7492008-05-01 22:18:59 +0000568 InitListChecker CheckInitList(this, InitList, DeclType);
569 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000570}
571
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000572Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000573Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000574 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 IdentifierInfo *II = D.getIdentifier();
576
Chris Lattnere80a59c2007-07-25 00:24:17 +0000577 // All of these full declarators require an identifier. If it doesn't have
578 // one, the ParsedFreeStandingDeclSpec action should be used.
579 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000580 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000581 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000582 D.getDeclSpec().getSourceRange(), D.getSourceRange());
583 return 0;
584 }
585
Chris Lattner31e05722007-08-26 06:24:45 +0000586 // The scope passed in may not be a decl scope. Zip up the scope tree until
587 // we find one that is.
588 while ((S->getFlags() & Scope::DeclScope) == 0)
589 S = S->getParent();
590
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000592 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000593 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000594 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000595
596 // In C++, the previous declaration we find might be a tag type
597 // (class or enum). In this case, the new declaration will hide the
598 // tag type.
599 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
600 PrevDecl = 0;
601
Chris Lattner41af0932007-11-14 06:34:38 +0000602 QualType R = GetTypeForDeclarator(D, S);
603 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
604
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000606 // Check that there are no default arguments (C++ only).
607 if (getLangOptions().CPlusPlus)
608 CheckExtraCXXDefaultArguments(D);
609
Chris Lattner41af0932007-11-14 06:34:38 +0000610 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 if (!NewTD) return 0;
612
613 // Handle attributes prior to checking for duplicates in MergeVarDecl
614 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
615 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000616 // Merge the decl with the existing one if appropriate. If the decl is
617 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000618 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000619 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
620 if (NewTD == 0) return 0;
621 }
622 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000623 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 // C99 6.7.7p2: If a typedef name specifies a variably modified type
625 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000626 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
627 // FIXME: Diagnostic needs to be fixed.
628 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000629 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000630 }
631 }
Chris Lattner41af0932007-11-14 06:34:38 +0000632 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000633 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000634 switch (D.getDeclSpec().getStorageClassSpec()) {
635 default: assert(0 && "Unknown storage class!");
636 case DeclSpec::SCS_auto:
637 case DeclSpec::SCS_register:
638 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
639 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000640 InvalidDecl = true;
641 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
643 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
644 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000645 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000646 }
647
Chris Lattnera98e58d2008-03-15 21:24:04 +0000648 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000649 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
650 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000651 II, R, SC, isInline,
652 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000653 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000654 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
655 D.getAttributes());
Chris Lattner04421082008-04-08 04:40:51 +0000656
657 // Copy the parameter declarations from the declarator D to
658 // the function declaration NewFD, if they are available.
659 if (D.getNumTypeObjects() > 0 &&
660 D.getTypeObject(0).Fun.hasPrototype) {
661 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
662
663 // Create Decl objects for each parameter, adding them to the
664 // FunctionDecl.
665 llvm::SmallVector<ParmVarDecl*, 16> Params;
666
667 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
668 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000669 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000670 // We let through "const void" here because Sema::GetTypeForDeclarator
671 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000672 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
673 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000674 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
675 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000676 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
677
Chris Lattnerdef026a2008-04-10 02:26:16 +0000678 // In C++, the empty parameter-type-list must be spelled "void"; a
679 // typedef of void is not permitted.
680 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000681 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000682 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
683 }
684
Chris Lattner04421082008-04-08 04:40:51 +0000685 } else {
686 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
687 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
688 }
689
690 NewFD->setParams(&Params[0], Params.size());
691 }
692
Steve Naroffffce4d52008-01-09 23:34:55 +0000693 // Merge the decl with the existing one if appropriate. Since C functions
694 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000695 if (PrevDecl &&
696 (!getLangOptions().CPlusPlus ||
697 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000698 bool Redeclaration = false;
699 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000701 if (Redeclaration) {
Eli Friedman27424962008-05-27 05:07:37 +0000702 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregorf0097952008-04-21 02:02:58 +0000703 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000704 }
705 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000706
707 // In C++, check default arguments now that we have merged decls.
708 if (getLangOptions().CPlusPlus)
709 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000710 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000711 // Check that there are no default arguments (C++ only).
712 if (getLangOptions().CPlusPlus)
713 CheckExtraCXXDefaultArguments(D);
714
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000715 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000716 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
717 D.getIdentifier()->getName());
718 InvalidDecl = true;
719 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000720
721 VarDecl *NewVD;
722 VarDecl::StorageClass SC;
723 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000724 default: assert(0 && "Unknown storage class!");
725 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
726 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
727 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
728 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
729 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
730 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000732 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000733 // C99 6.9p2: The storage-class specifiers auto and register shall not
734 // appear in the declaration specifiers in an external declaration.
735 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
736 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
737 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000738 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000739 }
Steve Naroff248a7532008-04-15 22:42:06 +0000740 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
741 II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000742 } else {
Steve Naroff248a7532008-04-15 22:42:06 +0000743 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
744 II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000745 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 // Handle attributes prior to checking for duplicates in MergeVarDecl
747 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
748 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000749
750 // Emit an error if an address space was applied to decl with local storage.
751 // This includes arrays of objects with address space qualifiers, but not
752 // automatic variables that point to other address spaces.
753 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000754 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
755 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
756 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000757 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000758 // Merge the decl with the existing one if appropriate. If the decl is
759 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000760 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 NewVD = MergeVarDecl(NewVD, PrevDecl);
762 if (NewVD == 0) return 0;
763 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 New = NewVD;
765 }
766
767 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000768 if (II)
769 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000770 // If any semantic error occurred, mark the decl as invalid.
771 if (D.getInvalidType() || InvalidDecl)
772 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000773
774 return New;
775}
776
Eli Friedmanc594b322008-05-20 13:48:25 +0000777bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
778 switch (Init->getStmtClass()) {
779 default:
780 Diag(Init->getExprLoc(),
781 diag::err_init_element_not_constant, Init->getSourceRange());
782 return true;
783 case Expr::ParenExprClass: {
784 const ParenExpr* PE = cast<ParenExpr>(Init);
785 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
786 }
787 case Expr::CompoundLiteralExprClass:
788 return cast<CompoundLiteralExpr>(Init)->isFileScope();
789 case Expr::DeclRefExprClass: {
790 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +0000791 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
792 if (VD->hasGlobalStorage())
793 return false;
794 Diag(Init->getExprLoc(),
795 diag::err_init_element_not_constant, Init->getSourceRange());
796 return true;
797 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000798 if (isa<FunctionDecl>(D))
799 return false;
800 Diag(Init->getExprLoc(),
801 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroffd0091aa2008-01-10 22:15:12 +0000802 return true;
803 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000804 case Expr::MemberExprClass: {
805 const MemberExpr *M = cast<MemberExpr>(Init);
806 if (M->isArrow())
807 return CheckAddressConstantExpression(M->getBase());
808 return CheckAddressConstantExpressionLValue(M->getBase());
809 }
810 case Expr::ArraySubscriptExprClass: {
811 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
812 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
813 return CheckAddressConstantExpression(ASE->getBase()) ||
814 CheckArithmeticConstantExpression(ASE->getIdx());
815 }
816 case Expr::StringLiteralClass:
817 case Expr::PreDefinedExprClass:
818 return false;
819 case Expr::UnaryOperatorClass: {
820 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
821
822 // C99 6.6p9
823 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +0000824 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +0000825
826 Diag(Init->getExprLoc(),
827 diag::err_init_element_not_constant, Init->getSourceRange());
828 return true;
829 }
830 }
831}
832
833bool Sema::CheckAddressConstantExpression(const Expr* Init) {
834 switch (Init->getStmtClass()) {
835 default:
836 Diag(Init->getExprLoc(),
837 diag::err_init_element_not_constant, Init->getSourceRange());
838 return true;
839 case Expr::ParenExprClass: {
840 const ParenExpr* PE = cast<ParenExpr>(Init);
841 return CheckAddressConstantExpression(PE->getSubExpr());
842 }
843 case Expr::StringLiteralClass:
844 case Expr::ObjCStringLiteralClass:
845 return false;
846 case Expr::CallExprClass: {
847 const CallExpr *CE = cast<CallExpr>(Init);
848 if (CE->isBuiltinConstantExpr())
849 return false;
850 Diag(Init->getExprLoc(),
851 diag::err_init_element_not_constant, Init->getSourceRange());
852 return true;
853 }
854 case Expr::UnaryOperatorClass: {
855 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
856
857 // C99 6.6p9
858 if (Exp->getOpcode() == UnaryOperator::AddrOf)
859 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
860
861 if (Exp->getOpcode() == UnaryOperator::Extension)
862 return CheckAddressConstantExpression(Exp->getSubExpr());
863
864 Diag(Init->getExprLoc(),
865 diag::err_init_element_not_constant, Init->getSourceRange());
866 return true;
867 }
868 case Expr::BinaryOperatorClass: {
869 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
870 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
871
872 Expr *PExp = Exp->getLHS();
873 Expr *IExp = Exp->getRHS();
874 if (IExp->getType()->isPointerType())
875 std::swap(PExp, IExp);
876
877 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
878 return CheckAddressConstantExpression(PExp) ||
879 CheckArithmeticConstantExpression(IExp);
880 }
881 case Expr::ImplicitCastExprClass: {
882 const Expr* SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
883
884 // Check for implicit promotion
885 if (SubExpr->getType()->isFunctionType() ||
886 SubExpr->getType()->isArrayType())
887 return CheckAddressConstantExpressionLValue(SubExpr);
888
889 // Check for pointer->pointer cast
890 if (SubExpr->getType()->isPointerType())
891 return CheckAddressConstantExpression(SubExpr);
892
893 if (SubExpr->getType()->isArithmeticType())
894 return CheckArithmeticConstantExpression(SubExpr);
895
896 Diag(Init->getExprLoc(),
897 diag::err_init_element_not_constant, Init->getSourceRange());
898 return true;
899 }
900 case Expr::CastExprClass: {
901 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
902
903 // Check for pointer->pointer cast
904 if (SubExpr->getType()->isPointerType())
905 return CheckAddressConstantExpression(SubExpr);
906
907 // FIXME: Should we pedwarn for (int*)(0+0)?
908 if (SubExpr->getType()->isArithmeticType())
909 return CheckArithmeticConstantExpression(SubExpr);
910
911 Diag(Init->getExprLoc(),
912 diag::err_init_element_not_constant, Init->getSourceRange());
913 return true;
914 }
915 case Expr::ConditionalOperatorClass: {
916 // FIXME: Should we pedwarn here?
917 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
918 if (!Exp->getCond()->getType()->isArithmeticType()) {
919 Diag(Init->getExprLoc(),
920 diag::err_init_element_not_constant, Init->getSourceRange());
921 return true;
922 }
923 if (CheckArithmeticConstantExpression(Exp->getCond()))
924 return true;
925 if (Exp->getLHS() &&
926 CheckAddressConstantExpression(Exp->getLHS()))
927 return true;
928 return CheckAddressConstantExpression(Exp->getRHS());
929 }
930 case Expr::AddrLabelExprClass:
931 return false;
932 }
933}
934
Eli Friedman4caf0552008-06-09 05:05:07 +0000935static const Expr* FindExpressionBaseAddress(const Expr* E);
936
937static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
938 switch (E->getStmtClass()) {
939 default:
940 return E;
941 case Expr::ParenExprClass: {
942 const ParenExpr* PE = cast<ParenExpr>(E);
943 return FindExpressionBaseAddressLValue(PE->getSubExpr());
944 }
945 case Expr::MemberExprClass: {
946 const MemberExpr *M = cast<MemberExpr>(E);
947 if (M->isArrow())
948 return FindExpressionBaseAddress(M->getBase());
949 return FindExpressionBaseAddressLValue(M->getBase());
950 }
951 case Expr::ArraySubscriptExprClass: {
952 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
953 return FindExpressionBaseAddress(ASE->getBase());
954 }
955 case Expr::UnaryOperatorClass: {
956 const UnaryOperator *Exp = cast<UnaryOperator>(E);
957
958 if (Exp->getOpcode() == UnaryOperator::Deref)
959 return FindExpressionBaseAddress(Exp->getSubExpr());
960
961 return E;
962 }
963 }
964}
965
966static const Expr* FindExpressionBaseAddress(const Expr* E) {
967 switch (E->getStmtClass()) {
968 default:
969 return E;
970 case Expr::ParenExprClass: {
971 const ParenExpr* PE = cast<ParenExpr>(E);
972 return FindExpressionBaseAddress(PE->getSubExpr());
973 }
974 case Expr::UnaryOperatorClass: {
975 const UnaryOperator *Exp = cast<UnaryOperator>(E);
976
977 // C99 6.6p9
978 if (Exp->getOpcode() == UnaryOperator::AddrOf)
979 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
980
981 if (Exp->getOpcode() == UnaryOperator::Extension)
982 return FindExpressionBaseAddress(Exp->getSubExpr());
983
984 return E;
985 }
986 case Expr::BinaryOperatorClass: {
987 const BinaryOperator *Exp = cast<BinaryOperator>(E);
988
989 Expr *PExp = Exp->getLHS();
990 Expr *IExp = Exp->getRHS();
991 if (IExp->getType()->isPointerType())
992 std::swap(PExp, IExp);
993
994 return FindExpressionBaseAddress(PExp);
995 }
996 case Expr::ImplicitCastExprClass: {
997 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
998
999 // Check for implicit promotion
1000 if (SubExpr->getType()->isFunctionType() ||
1001 SubExpr->getType()->isArrayType())
1002 return FindExpressionBaseAddressLValue(SubExpr);
1003
1004 // Check for pointer->pointer cast
1005 if (SubExpr->getType()->isPointerType())
1006 return FindExpressionBaseAddress(SubExpr);
1007
1008 // We assume that we have an arithmetic expression here;
1009 // if we don't, we'll figure it out later
1010 return 0;
1011 }
1012 case Expr::CastExprClass: {
1013 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1014
1015 // Check for pointer->pointer cast
1016 if (SubExpr->getType()->isPointerType())
1017 return FindExpressionBaseAddress(SubExpr);
1018
1019 // We assume that we have an arithmetic expression here;
1020 // if we don't, we'll figure it out later
1021 return 0;
1022 }
1023 }
1024}
1025
Eli Friedmanc594b322008-05-20 13:48:25 +00001026bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1027 switch (Init->getStmtClass()) {
1028 default:
1029 Diag(Init->getExprLoc(),
1030 diag::err_init_element_not_constant, Init->getSourceRange());
1031 return true;
1032 case Expr::ParenExprClass: {
1033 const ParenExpr* PE = cast<ParenExpr>(Init);
1034 return CheckArithmeticConstantExpression(PE->getSubExpr());
1035 }
1036 case Expr::FloatingLiteralClass:
1037 case Expr::IntegerLiteralClass:
1038 case Expr::CharacterLiteralClass:
1039 case Expr::ImaginaryLiteralClass:
1040 case Expr::TypesCompatibleExprClass:
1041 case Expr::CXXBoolLiteralExprClass:
1042 return false;
1043 case Expr::CallExprClass: {
1044 const CallExpr *CE = cast<CallExpr>(Init);
1045 if (CE->isBuiltinConstantExpr())
1046 return false;
1047 Diag(Init->getExprLoc(),
1048 diag::err_init_element_not_constant, Init->getSourceRange());
1049 return true;
1050 }
1051 case Expr::DeclRefExprClass: {
1052 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1053 if (isa<EnumConstantDecl>(D))
1054 return false;
1055 Diag(Init->getExprLoc(),
1056 diag::err_init_element_not_constant, Init->getSourceRange());
1057 return true;
1058 }
1059 case Expr::CompoundLiteralExprClass:
1060 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1061 // but vectors are allowed to be magic.
1062 if (Init->getType()->isVectorType())
1063 return false;
1064 Diag(Init->getExprLoc(),
1065 diag::err_init_element_not_constant, Init->getSourceRange());
1066 return true;
1067 case Expr::UnaryOperatorClass: {
1068 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1069
1070 switch (Exp->getOpcode()) {
1071 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1072 // See C99 6.6p3.
1073 default:
1074 Diag(Init->getExprLoc(),
1075 diag::err_init_element_not_constant, Init->getSourceRange());
1076 return true;
1077 case UnaryOperator::SizeOf:
1078 case UnaryOperator::AlignOf:
1079 case UnaryOperator::OffsetOf:
1080 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1081 // See C99 6.5.3.4p2 and 6.6p3.
1082 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1083 return false;
1084 Diag(Init->getExprLoc(),
1085 diag::err_init_element_not_constant, Init->getSourceRange());
1086 return true;
1087 case UnaryOperator::Extension:
1088 case UnaryOperator::LNot:
1089 case UnaryOperator::Plus:
1090 case UnaryOperator::Minus:
1091 case UnaryOperator::Not:
1092 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1093 }
1094 }
1095 case Expr::SizeOfAlignOfTypeExprClass: {
1096 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1097 // Special check for void types, which are allowed as an extension
1098 if (Exp->getArgumentType()->isVoidType())
1099 return false;
1100 // alignof always evaluates to a constant.
1101 // FIXME: is sizeof(int[3.0]) a constant expression?
1102 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1103 Diag(Init->getExprLoc(),
1104 diag::err_init_element_not_constant, Init->getSourceRange());
1105 return true;
1106 }
1107 return false;
1108 }
1109 case Expr::BinaryOperatorClass: {
1110 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1111
1112 if (Exp->getLHS()->getType()->isArithmeticType() &&
1113 Exp->getRHS()->getType()->isArithmeticType()) {
1114 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1115 CheckArithmeticConstantExpression(Exp->getRHS());
1116 }
1117
Eli Friedman4caf0552008-06-09 05:05:07 +00001118 if (Exp->getLHS()->getType()->isPointerType() &&
1119 Exp->getRHS()->getType()->isPointerType()) {
1120 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1121 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1122
1123 // Only allow a null (constant integer) base; we could
1124 // allow some additional cases if necessary, but this
1125 // is sufficient to cover offsetof-like constructs.
1126 if (!LHSBase && !RHSBase) {
1127 return CheckAddressConstantExpression(Exp->getLHS()) ||
1128 CheckAddressConstantExpression(Exp->getRHS());
1129 }
1130 }
1131
Eli Friedmanc594b322008-05-20 13:48:25 +00001132 Diag(Init->getExprLoc(),
1133 diag::err_init_element_not_constant, Init->getSourceRange());
1134 return true;
1135 }
1136 case Expr::ImplicitCastExprClass:
1137 case Expr::CastExprClass: {
1138 const Expr *SubExpr;
1139 if (const CastExpr *C = dyn_cast<CastExpr>(Init)) {
1140 SubExpr = C->getSubExpr();
1141 } else {
1142 SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1143 }
1144
1145 if (SubExpr->getType()->isArithmeticType())
1146 return CheckArithmeticConstantExpression(SubExpr);
1147
1148 Diag(Init->getExprLoc(),
1149 diag::err_init_element_not_constant, Init->getSourceRange());
1150 return true;
1151 }
1152 case Expr::ConditionalOperatorClass: {
1153 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1154 if (CheckArithmeticConstantExpression(Exp->getCond()))
1155 return true;
1156 if (Exp->getLHS() &&
1157 CheckArithmeticConstantExpression(Exp->getLHS()))
1158 return true;
1159 return CheckArithmeticConstantExpression(Exp->getRHS());
1160 }
1161 }
1162}
1163
1164bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
1165 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1166 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1167 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1168
1169 if (Init->getType()->isReferenceType()) {
1170 // FIXME: Work out how the heck reference types work
1171 return false;
1172#if 0
1173 // A reference is constant if the address of the expression
1174 // is constant
1175 // We look through initlists here to simplify
1176 // CheckAddressConstantExpressionLValue.
1177 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1178 assert(Exp->getNumInits() > 0 &&
1179 "Refernce initializer cannot be empty");
1180 Init = Exp->getInit(0);
1181 }
1182 return CheckAddressConstantExpressionLValue(Init);
1183#endif
1184 }
1185
1186 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1187 unsigned numInits = Exp->getNumInits();
1188 for (unsigned i = 0; i < numInits; i++) {
1189 // FIXME: Need to get the type of the declaration for C++,
1190 // because it could be a reference?
1191 if (CheckForConstantInitializer(Exp->getInit(i),
1192 Exp->getInit(i)->getType()))
1193 return true;
1194 }
1195 return false;
1196 }
1197
1198 if (Init->isNullPointerConstant(Context))
1199 return false;
1200 if (Init->getType()->isArithmeticType()) {
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001201 QualType InitTy = Init->getType().getCanonicalType().getUnqualifiedType();
1202 if (InitTy == Context.BoolTy) {
1203 // Special handling for pointers implicitly cast to bool;
1204 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1205 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1206 Expr* SubE = ICE->getSubExpr();
1207 if (SubE->getType()->isPointerType() ||
1208 SubE->getType()->isArrayType() ||
1209 SubE->getType()->isFunctionType()) {
1210 return CheckAddressConstantExpression(Init);
1211 }
1212 }
1213 } else if (InitTy->isIntegralType()) {
1214 Expr* SubE = 0;
1215 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init))
1216 SubE = ICE->getSubExpr();
1217 else if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1218 SubE = CE->getSubExpr();
1219 // Special check for pointer cast to int; we allow as an extension
1220 // an address constant cast to an integer if the integer
1221 // is of an appropriate width (this sort of code is apparently used
1222 // in some places).
1223 // FIXME: Add pedwarn?
1224 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1225 if (SubE && (SubE->getType()->isPointerType() ||
1226 SubE->getType()->isArrayType() ||
1227 SubE->getType()->isFunctionType())) {
1228 unsigned IntWidth = Context.getTypeSize(Init->getType());
1229 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1230 if (IntWidth >= PointerWidth)
1231 return CheckAddressConstantExpression(Init);
1232 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001233 }
1234
1235 return CheckArithmeticConstantExpression(Init);
1236 }
1237
1238 if (Init->getType()->isPointerType())
1239 return CheckAddressConstantExpression(Init);
1240
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001241 // An array type at the top level that isn't an init-list must
1242 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001243 if (Init->getType()->isArrayType())
1244 return false;
1245
1246 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1247 Init->getSourceRange());
1248 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001249}
1250
Steve Naroffbb204692007-09-12 14:07:44 +00001251void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001252 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001253 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001254 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001255
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001256 // If there is no declaration, there was an error parsing it. Just ignore
1257 // the initializer.
1258 if (RealDecl == 0) {
1259 delete Init;
1260 return;
1261 }
Steve Naroffbb204692007-09-12 14:07:44 +00001262
Steve Naroff410e3e22007-09-12 20:13:48 +00001263 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1264 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001265 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1266 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001267 RealDecl->setInvalidDecl();
1268 return;
1269 }
Steve Naroffbb204692007-09-12 14:07:44 +00001270 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001271 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001272 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001273 if (VDecl->isBlockVarDecl()) {
1274 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001275 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001276 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001277 VDecl->setInvalidDecl();
1278 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +00001279 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001280 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001281 if (SC == VarDecl::Static) // C99 6.7.8p4.
1282 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001283 }
Steve Naroff248a7532008-04-15 22:42:06 +00001284 } else if (VDecl->isFileVarDecl()) {
1285 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001286 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001287 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001288 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001289 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001290
1291 // C99 6.7.8p4. All file scoped initializers need to be constant.
1292 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001293 }
1294 // If the type changed, it means we had an incomplete type that was
1295 // completed by the initializer. For example:
1296 // int ary[] = { 1, 3, 5 };
1297 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001298 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001299 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001300 Init->setType(DclT);
1301 }
Steve Naroffbb204692007-09-12 14:07:44 +00001302
1303 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001304 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001305 return;
1306}
1307
Reid Spencer5f016e22007-07-11 17:01:13 +00001308/// The declarators are chained together backwards, reverse the list.
1309Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1310 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001311 Decl *GroupDecl = static_cast<Decl*>(group);
1312 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001313 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001314
1315 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1316 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001317 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001319 else { // reverse the list.
1320 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001321 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001322 Group->setNextDeclarator(NewGroup);
1323 NewGroup = Group;
1324 Group = Next;
1325 }
1326 }
1327 // Perform semantic analysis that depends on having fully processed both
1328 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001329 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001330 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1331 if (!IDecl)
1332 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001333 QualType T = IDecl->getType();
1334
1335 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1336 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001337 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1338 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +00001339 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001340 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1341 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001342 }
1343 }
1344 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1345 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001346 if (IDecl->isBlockVarDecl() &&
1347 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001348 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001349 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1350 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001351 IDecl->setInvalidDecl();
1352 }
1353 }
1354 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1355 // object that has file scope without an initializer, and without a
1356 // storage-class specifier or with the storage-class specifier "static",
1357 // constitutes a tentative definition. Note: A tentative definition with
1358 // external linkage is valid (C99 6.2.2p5).
Steve Naroff248a7532008-04-15 22:42:06 +00001359 if (IDecl && !IDecl->getInit() &&
1360 (IDecl->getStorageClass() == VarDecl::Static ||
1361 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001362 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001363 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1364 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001365 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001366 // C99 6.9.2p3: If the declaration of an identifier for an object is
1367 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1368 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001369 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1370 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001371 IDecl->setInvalidDecl();
1372 }
1373 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 }
1375 return NewGroup;
1376}
Steve Naroffe1223f72007-08-28 03:03:08 +00001377
Chris Lattner04421082008-04-08 04:40:51 +00001378/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1379/// to introduce parameters into function prototype scope.
1380Sema::DeclTy *
1381Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00001382 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001383
1384 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1385 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1386 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1387 Diag(DS.getStorageClassSpecLoc(),
1388 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001389 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001390 }
1391 if (DS.isThreadSpecified()) {
1392 Diag(DS.getThreadSpecLoc(),
1393 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001394 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001395 }
1396
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001397 // Check that there are no default arguments inside the type of this
1398 // parameter (C++ only).
1399 if (getLangOptions().CPlusPlus)
1400 CheckExtraCXXDefaultArguments(D);
1401
Chris Lattner04421082008-04-08 04:40:51 +00001402 // In this context, we *do not* check D.getInvalidType(). If the declarator
1403 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1404 // though it will not reflect the user specified type.
1405 QualType parmDeclType = GetTypeForDeclarator(D, S);
1406
1407 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1408
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1410 // Can this happen for params? We already checked that they don't conflict
1411 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001412 IdentifierInfo *II = D.getIdentifier();
1413 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1414 if (S->isDeclScope(PrevDecl)) {
1415 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1416 dyn_cast<NamedDecl>(PrevDecl)->getName());
1417
1418 // Recover by removing the name
1419 II = 0;
1420 D.SetIdentifier(0, D.getIdentifierLoc());
1421 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001422 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001423
1424 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1425 // Doing the promotion here has a win and a loss. The win is the type for
1426 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1427 // code generator). The loss is the orginal type isn't preserved. For example:
1428 //
1429 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1430 // int blockvardecl[5];
1431 // sizeof(parmvardecl); // size == 4
1432 // sizeof(blockvardecl); // size == 20
1433 // }
1434 //
1435 // For expressions, all implicit conversions are captured using the
1436 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1437 //
1438 // FIXME: If a source translation tool needs to see the original type, then
1439 // we need to consider storing both types (in ParmVarDecl)...
1440 //
Chris Lattnere6327742008-04-02 05:18:44 +00001441 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001442 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001443 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001444 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001445 parmDeclType = Context.getPointerType(parmDeclType);
1446
Chris Lattner04421082008-04-08 04:40:51 +00001447 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1448 D.getIdentifierLoc(), II,
1449 parmDeclType, VarDecl::None,
1450 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001451
Chris Lattner04421082008-04-08 04:40:51 +00001452 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001453 New->setInvalidDecl();
1454
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001455 if (II)
1456 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001457
Nate Begemanfc584522008-05-09 16:56:01 +00001458 HandleDeclAttributes(New, D.getDeclSpec().getAttributes(),
1459 D.getAttributes());
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001461
Reid Spencer5f016e22007-07-11 17:01:13 +00001462}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001463
Chris Lattnerb652cea2007-10-09 17:14:05 +00001464Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001465 assert(CurFunctionDecl == 0 && "Function parsing confused");
1466 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1467 "Not a function declarator!");
1468 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001469
Reid Spencer5f016e22007-07-11 17:01:13 +00001470 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1471 // for a K&R function.
1472 if (!FTI.hasPrototype) {
1473 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001474 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1476 FTI.ArgInfo[i].Ident->getName());
1477 // Implicitly declare the argument as type 'int' for lack of a better
1478 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001479 DeclSpec DS;
1480 const char* PrevSpec; // unused
1481 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1482 PrevSpec);
1483 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1484 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1485 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 }
1487 }
Chris Lattner52804082008-02-17 19:31:09 +00001488
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 // Since this is a function definition, act as though we have information
1490 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001491 if (FTI.NumArgs)
1492 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001493 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001494 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 }
1496
1497 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001498
1499 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001500 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001501 GlobalScope);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001502 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1503 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1504 const FunctionDecl *Definition;
1505 if (FD->getBody(Definition)) {
1506 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1507 D.getIdentifier()->getName());
1508 Diag(Definition->getLocation(), diag::err_previous_definition);
1509 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001510 }
1511 }
Steve Narofffabbc342008-02-12 01:09:36 +00001512 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001513 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001514 CurFunctionDecl = FD;
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);
1535 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001536 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001537 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001538 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001539 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001540 }
Chris Lattnerb048c982008-04-06 04:47:34 +00001541 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 // Verify and clean out per-function state.
1543
1544 // Check goto/label use.
1545 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1546 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1547 // Verify that we have no forward references left. If so, there was a goto
1548 // or address of a label taken, but no definition of it. Label fwd
1549 // definitions are indicated with a null substmt.
1550 if (I->second->getSubStmt() == 0) {
1551 LabelStmt *L = I->second;
1552 // Emit error.
1553 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1554
1555 // At this point, we have gotos that use the bogus label. Stitch it into
1556 // the function body so that they aren't leaked and that the AST is well
1557 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001558 if (Body) {
1559 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1560 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1561 } else {
1562 // The whole function wasn't parsed correctly, just delete this.
1563 delete L;
1564 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 }
1566 }
1567 LabelMap.clear();
1568
Steve Naroffd6d054d2007-11-11 23:20:51 +00001569 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001570}
1571
Reid Spencer5f016e22007-07-11 17:01:13 +00001572/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1573/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001574ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1575 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001576 // Extension in C99. Legal in C90, but warn about it.
1577 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001579 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1581
1582 // FIXME: handle stuff like:
1583 // void foo() { extern float X(); }
1584 // void bar() { X(); } <-- implicit decl for X in another scope.
1585
1586 // Set a Declarator for the implicit definition: int foo();
1587 const char *Dummy;
1588 DeclSpec DS;
1589 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1590 Error = Error; // Silence warning.
1591 assert(!Error && "Error setting up implicit decl!");
1592 Declarator D(DS, Declarator::BlockContext);
1593 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1594 D.SetIdentifier(&II, Loc);
1595
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001596 // Insert this function into translation-unit scope.
1597
1598 DeclContext *PrevDC = CurContext;
1599 CurContext = Context.getTranslationUnitDecl();
1600
Steve Naroffe2ef8152008-04-04 14:32:09 +00001601 FunctionDecl *FD =
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001602 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001603 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001604
1605 CurContext = PrevDC;
1606
Steve Naroffe2ef8152008-04-04 14:32:09 +00001607 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001608}
1609
1610
Chris Lattner41af0932007-11-14 06:34:38 +00001611TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001612 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001613 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001614 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001615
1616 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001617 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1618 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001619 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001620 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001621 if (D.getInvalidType())
1622 NewTD->setInvalidDecl();
1623 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001624}
1625
Steve Naroff08d92e42007-09-15 18:49:24 +00001626/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001627/// former case, Name will be non-null. In the later case, Name will be null.
1628/// TagType indicates what kind of tag this is. TK indicates whether this is a
1629/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001630Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 SourceLocation KWLoc, IdentifierInfo *Name,
1632 SourceLocation NameLoc, AttributeList *Attr) {
1633 // If this is a use of an existing tag, it must have a name.
1634 assert((Name != 0 || TK == TK_Definition) &&
1635 "Nameless record must be a definition!");
1636
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001637 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 switch (TagType) {
1639 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001640 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1641 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1642 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1643 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001644 }
1645
1646 // If this is a named struct, check to see if there was a previous forward
1647 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001648 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1649 if (ScopedDecl *PrevDecl =
1650 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001651
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001652 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1653 "unexpected Decl type");
1654 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1655 // If this is a use of a previous tag, or if the tag is already declared in
1656 // the same scope (so that the definition/declaration completes or
1657 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001658 if (TK == TK_Reference ||
1659 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001660 // Make sure that this wasn't declared as an enum and now used as a struct
1661 // or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001662 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001663 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1664 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1665 }
1666
1667 // If this is a use or a forward declaration, we're good.
1668 if (TK != TK_Definition)
1669 return PrevDecl;
Reid Spencer5f016e22007-07-11 17:01:13 +00001670
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001671 // Diagnose attempts to redefine a tag.
1672 if (PrevTagDecl->isDefinition()) {
1673 Diag(NameLoc, diag::err_redefinition, Name->getName());
1674 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1675 // If this is a redefinition, recover by making this struct be
1676 // anonymous, which will make any later references get the previous
1677 // definition.
1678 Name = 0;
1679 } else {
1680 // Okay, this is definition of a previously declared or referenced tag.
1681 // Move the location of the decl to be the definition site.
1682 PrevDecl->setLocation(NameLoc);
1683 return PrevDecl;
1684 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001686 // If we get here, this is a definition of a new struct type in a nested
1687 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1688 // type.
1689 } else {
1690 // The tag name clashes with a namespace name, issue an error and recover
1691 // by making this tag be anonymous.
1692 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1693 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1694 Name = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001695 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 }
1697
1698 // If there is an identifier, use the location of the identifier as the
1699 // location of the decl, otherwise use the location of the struct/union
1700 // keyword.
1701 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1702
1703 // Otherwise, if this is the first time we've seen this tag, create the decl.
1704 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001705 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1707 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001708 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001709 // If this is an undefined enum, warn.
1710 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001711 } else {
1712 // struct/union/class
1713
Reid Spencer5f016e22007-07-11 17:01:13 +00001714 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1715 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001716 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 }
1718
1719 // If this has an identifier, add it to the scope stack.
1720 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001721 // The scope passed in may not be a decl scope. Zip up the scope tree until
1722 // we find one that is.
1723 while ((S->getFlags() & Scope::DeclScope) == 0)
1724 S = S->getParent();
1725
1726 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001727 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001729
Anders Carlssonad148062008-02-16 00:29:18 +00001730 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 return New;
1732}
1733
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001734/// Collect the instance variables declared in an Objective-C object. Used in
1735/// the creation of structures from objects using the @defs directive.
1736static void CollectIvars(ObjCInterfaceDecl *Class,
1737 llvm::SmallVector<Sema::DeclTy*, 16> &ivars) {
1738 if (Class->getSuperClass())
1739 CollectIvars(Class->getSuperClass(), ivars);
1740 ivars.append(Class->ivar_begin(), Class->ivar_end());
1741}
1742
1743/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1744/// instance variables of ClassName into Decls.
1745void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1746 IdentifierInfo *ClassName,
1747 llvm::SmallVector<DeclTy*, 16> &Decls) {
1748 // Check that ClassName is a valid class
1749 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1750 if (!Class) {
1751 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1752 return;
1753 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001754 // Collect the instance variables
1755 CollectIvars(Class, Decls);
1756}
1757
1758
Eli Friedman1b76ada2008-06-03 21:01:11 +00001759static bool CalcFakeICEVal(const Expr* Expr,
1760 llvm::APSInt& Result,
1761 ASTContext& Context) {
1762 // Calculate the value of an expression that has a calculatable
1763 // value, but isn't an ICE. Currently, this only supports
1764 // a very narrow set of extensions, but it can be expanded if needed.
1765 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Expr))
1766 return CalcFakeICEVal(PE->getSubExpr(), Result, Context);
1767
1768 if (const CastExpr *CE = dyn_cast<CastExpr>(Expr)) {
1769 QualType CETy = CE->getType();
1770 if ((CETy->isIntegralType() && !CETy->isBooleanType()) ||
1771 CETy->isPointerType()) {
1772 if (CalcFakeICEVal(CE->getSubExpr(), Result, Context)) {
1773 Result.extOrTrunc(Context.getTypeSize(CETy));
1774 // FIXME: This assumes pointers are signed.
1775 Result.setIsSigned(CETy->isSignedIntegerType() ||
1776 CETy->isPointerType());
1777 return true;
1778 }
1779 }
1780 }
1781
1782 if (Expr->getType()->isIntegralType())
1783 return Expr->isIntegerConstantExpr(Result, Context);
1784
1785 return false;
1786}
1787
1788QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1789 // This method tries to turn a variable array into a constant
1790 // array even when the size isn't an ICE. This is necessary
1791 // for compatibility with code that depends on gcc's buggy
1792 // constant expression folding, like struct {char x[(int)(char*)2];}
1793 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
1794 llvm::APSInt Result(32);
1795 if (VLATy->getSizeExpr() &&
1796 CalcFakeICEVal(VLATy->getSizeExpr(), Result, Context) &&
1797 Result > llvm::APSInt(Result.getBitWidth(), Result.isUnsigned())) {
1798 return Context.getConstantArrayType(VLATy->getElementType(),
1799 Result, ArrayType::Normal, 0);
1800 }
1801 }
1802 return QualType();
1803}
1804
Steve Naroff08d92e42007-09-15 18:49:24 +00001805/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001806/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001807Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001808 SourceLocation DeclStart,
1809 Declarator &D, ExprTy *BitfieldWidth) {
1810 IdentifierInfo *II = D.getIdentifier();
1811 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001812 SourceLocation Loc = DeclStart;
1813 if (II) Loc = D.getIdentifierLoc();
1814
1815 // FIXME: Unnamed fields can be handled in various different ways, for
1816 // example, unnamed unions inject all members into the struct namespace!
1817
1818
1819 if (BitWidth) {
1820 // TODO: Validate.
1821 //printf("WARNING: BITFIELDS IGNORED!\n");
1822
1823 // 6.7.2.1p3
1824 // 6.7.2.1p4
1825
1826 } else {
1827 // Not a bitfield.
1828
1829 // validate II.
1830
1831 }
1832
1833 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001834 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1835 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001836
Reid Spencer5f016e22007-07-11 17:01:13 +00001837 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1838 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001839 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00001840 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1841 if (!FixedTy.isNull()) {
1842 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1843 T = FixedTy;
1844 } else {
1845 // FIXME: This diagnostic needs work
1846 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1847 InvalidDecl = true;
1848 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001849 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001850 // FIXME: Chain fielddecls together.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001851 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001852
Anders Carlssonad148062008-02-16 00:29:18 +00001853 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1854 D.getAttributes());
1855
Steve Naroff5912a352007-08-28 20:14:24 +00001856 if (D.getInvalidType() || InvalidDecl)
1857 NewFD->setInvalidDecl();
1858 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001859}
1860
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001861/// TranslateIvarVisibility - Translate visibility from a token ID to an
1862/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001863static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001864TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001865 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001866 case tok::objc_private: return ObjCIvarDecl::Private;
1867 case tok::objc_public: return ObjCIvarDecl::Public;
1868 case tok::objc_protected: return ObjCIvarDecl::Protected;
1869 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001870 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001871 }
1872}
1873
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001874/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1875/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001876Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001877 SourceLocation DeclStart,
1878 Declarator &D, ExprTy *BitfieldWidth,
1879 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001880 IdentifierInfo *II = D.getIdentifier();
1881 Expr *BitWidth = (Expr*)BitfieldWidth;
1882 SourceLocation Loc = DeclStart;
1883 if (II) Loc = D.getIdentifierLoc();
1884
1885 // FIXME: Unnamed fields can be handled in various different ways, for
1886 // example, unnamed unions inject all members into the struct namespace!
1887
1888
1889 if (BitWidth) {
1890 // TODO: Validate.
1891 //printf("WARNING: BITFIELDS IGNORED!\n");
1892
1893 // 6.7.2.1p3
1894 // 6.7.2.1p4
1895
1896 } else {
1897 // Not a bitfield.
1898
1899 // validate II.
1900
1901 }
1902
1903 QualType T = GetTypeForDeclarator(D, S);
1904 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1905 bool InvalidDecl = false;
1906
1907 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1908 // than a variably modified type.
1909 if (T->isVariablyModifiedType()) {
1910 // FIXME: This diagnostic needs work
1911 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1912 InvalidDecl = true;
1913 }
1914
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001915 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001916
1917 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1918 D.getAttributes());
1919
1920 if (D.getInvalidType() || InvalidDecl)
1921 NewID->setInvalidDecl();
1922 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001923 if (Visibility != tok::objc_not_keyword)
1924 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001925 return NewID;
1926}
1927
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001928void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001929 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001930 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001931 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001932 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1933 assert(EnclosingDecl && "missing record or interface decl");
1934 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1935
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001936 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001937 // Diagnose code like:
1938 // struct S { struct S {} X; };
1939 // We discover this when we complete the outer S. Reject and ignore the
1940 // outer S.
1941 Diag(Record->getLocation(), diag::err_nested_redefinition,
1942 Record->getKindName());
1943 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001944 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001945 return;
1946 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001947 // Verify that all the fields are okay.
1948 unsigned NumNamedMembers = 0;
1949 llvm::SmallVector<FieldDecl*, 32> RecFields;
1950 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001951
Reid Spencer5f016e22007-07-11 17:01:13 +00001952 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001953
Steve Naroff74216642007-09-14 22:20:54 +00001954 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1955 assert(FD && "missing field decl");
1956
1957 // Remember all fields.
1958 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001959
1960 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001961 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00001962
Reid Spencer5f016e22007-07-11 17:01:13 +00001963 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001964 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001965 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001966 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001967 FD->setInvalidDecl();
1968 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001969 continue;
1970 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001971 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1972 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001973 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001974 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001975 FD->setInvalidDecl();
1976 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001977 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001978 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001979 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001980 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001981 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001983 FD->setInvalidDecl();
1984 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001985 continue;
1986 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001987 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1989 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001990 FD->setInvalidDecl();
1991 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 continue;
1993 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001994 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001995 if (Record)
1996 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001997 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001998 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1999 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002000 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002001 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2002 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002003 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 Record->setHasFlexibleArrayMember(true);
2005 } else {
2006 // If this is a struct/class and this is not the last element, reject
2007 // it. Note that GCC supports variable sized arrays in the middle of
2008 // structures.
2009 if (i != NumFields-1) {
2010 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2011 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002012 FD->setInvalidDecl();
2013 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002014 continue;
2015 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002016 // We support flexible arrays at the end of structs in other structs
2017 // as an extension.
2018 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2019 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002020 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002021 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002022 }
2023 }
2024 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002025 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002026 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002027 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2028 FD->getName());
2029 FD->setInvalidDecl();
2030 EnclosingDecl->setInvalidDecl();
2031 continue;
2032 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002033 // Keep track of the number of named members.
2034 if (IdentifierInfo *II = FD->getIdentifier()) {
2035 // Detect duplicate member names.
2036 if (!FieldIDs.insert(II)) {
2037 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2038 // Find the previous decl.
2039 SourceLocation PrevLoc;
2040 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2041 assert(i != e && "Didn't find previous def!");
2042 if (RecFields[i]->getIdentifier() == II) {
2043 PrevLoc = RecFields[i]->getLocation();
2044 break;
2045 }
2046 }
2047 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002048 FD->setInvalidDecl();
2049 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002050 continue;
2051 }
2052 ++NumNamedMembers;
2053 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 }
2055
Reid Spencer5f016e22007-07-11 17:01:13 +00002056 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002057 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002058 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00002059 Consumer.HandleTagDeclDefinition(Record);
2060 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002061 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2062 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2063 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2064 else if (ObjCImplementationDecl *IMPDecl =
2065 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002066 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2067 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002068 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002069 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002070 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002071}
2072
Steve Naroff08d92e42007-09-15 18:49:24 +00002073Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002074 DeclTy *lastEnumConst,
2075 SourceLocation IdLoc, IdentifierInfo *Id,
2076 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002077 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002078 EnumConstantDecl *LastEnumConst =
2079 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2080 Expr *Val = static_cast<Expr*>(val);
2081
Chris Lattner31e05722007-08-26 06:24:45 +00002082 // The scope passed in may not be a decl scope. Zip up the scope tree until
2083 // we find one that is.
2084 while ((S->getFlags() & Scope::DeclScope) == 0)
2085 S = S->getParent();
2086
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 // Verify that there isn't already something declared with this name in this
2088 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002089 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00002090 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002091 if (isa<EnumConstantDecl>(PrevDecl))
2092 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2093 else
2094 Diag(IdLoc, diag::err_redefinition, Id->getName());
2095 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002096 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002097 return 0;
2098 }
2099 }
2100
2101 llvm::APSInt EnumVal(32);
2102 QualType EltTy;
2103 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002104 // Make sure to promote the operand type to int.
2105 UsualUnaryConversions(Val);
2106
Reid Spencer5f016e22007-07-11 17:01:13 +00002107 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2108 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002109 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002110 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2111 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002112 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002113 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002114 } else {
2115 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002116 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002117 }
2118
2119 if (!Val) {
2120 if (LastEnumConst) {
2121 // Assign the last value + 1.
2122 EnumVal = LastEnumConst->getInitVal();
2123 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002124
2125 // Check for overflow on increment.
2126 if (EnumVal < LastEnumConst->getInitVal())
2127 Diag(IdLoc, diag::warn_enum_value_overflow);
2128
Chris Lattnerb7416f92007-08-27 17:37:24 +00002129 EltTy = LastEnumConst->getType();
2130 } else {
2131 // First value, set to zero.
2132 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002133 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002134 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 }
2136
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002137 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002138 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2139 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002140 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002141
2142 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002143 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002144 return New;
2145}
2146
Steve Naroff08d92e42007-09-15 18:49:24 +00002147void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002148 DeclTy **Elements, unsigned NumElements) {
2149 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
2150 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
2151
Chris Lattnere37f0be2007-08-28 05:10:31 +00002152 // TODO: If the result value doesn't fit in an int, it must be a long or long
2153 // long value. ISO C does not support this, but GCC does as an extension,
2154 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002155 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002156
Chris Lattnerac609682007-08-28 06:15:15 +00002157 // Verify that all the values are okay, compute the size of the values, and
2158 // reverse the list.
2159 unsigned NumNegativeBits = 0;
2160 unsigned NumPositiveBits = 0;
2161
2162 // Keep track of whether all elements have type int.
2163 bool AllElementsInt = true;
2164
Reid Spencer5f016e22007-07-11 17:01:13 +00002165 EnumConstantDecl *EltList = 0;
2166 for (unsigned i = 0; i != NumElements; ++i) {
2167 EnumConstantDecl *ECD =
2168 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2169 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002170
2171 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002172 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002173 assert(InitVal.getBitWidth() >= IntWidth &&
2174 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002175 if (InitVal.getBitWidth() > IntWidth) {
2176 llvm::APSInt V(InitVal);
2177 V.trunc(IntWidth);
2178 V.extend(InitVal.getBitWidth());
2179 if (V != InitVal)
2180 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2181 InitVal.toString());
2182 }
Chris Lattnerac609682007-08-28 06:15:15 +00002183
2184 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002185 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002186 NumPositiveBits = std::max(NumPositiveBits,
2187 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002188 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002189 NumNegativeBits = std::max(NumNegativeBits,
2190 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002191
Chris Lattnerac609682007-08-28 06:15:15 +00002192 // Keep track of whether every enum element has type int (very commmon).
2193 if (AllElementsInt)
2194 AllElementsInt = ECD->getType() == Context.IntTy;
2195
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 ECD->setNextDeclarator(EltList);
2197 EltList = ECD;
2198 }
2199
Chris Lattnerac609682007-08-28 06:15:15 +00002200 // Figure out the type that should be used for this enum.
2201 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2202 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002203 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002204
2205 if (NumNegativeBits) {
2206 // If there is a negative value, figure out the smallest integer type (of
2207 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002208 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002209 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002210 BestWidth = IntWidth;
2211 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002212 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002213
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002214 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002215 BestType = Context.LongTy;
2216 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002217 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002218
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002219 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002220 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2221 BestType = Context.LongLongTy;
2222 }
2223 }
2224 } else {
2225 // If there is no negative value, figure out which of uint, ulong, ulonglong
2226 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002227 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002228 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002229 BestWidth = IntWidth;
2230 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002231 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002232 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002233 } else {
2234 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002235 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002236 "How could an initializer get larger than ULL?");
2237 BestType = Context.UnsignedLongLongTy;
2238 }
2239 }
2240
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002241 // Loop over all of the enumerator constants, changing their types to match
2242 // the type of the enum if needed.
2243 for (unsigned i = 0; i != NumElements; ++i) {
2244 EnumConstantDecl *ECD =
2245 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2246 if (!ECD) continue; // Already issued a diagnostic.
2247
2248 // Standard C says the enumerators have int type, but we allow, as an
2249 // extension, the enumerators to be larger than int size. If each
2250 // enumerator value fits in an int, type it as an int, otherwise type it the
2251 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2252 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002253 if (ECD->getType() == Context.IntTy) {
2254 // Make sure the init value is signed.
2255 llvm::APSInt IV = ECD->getInitVal();
2256 IV.setIsSigned(true);
2257 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002258 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002259 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002260
2261 // Determine whether the value fits into an int.
2262 llvm::APSInt InitVal = ECD->getInitVal();
2263 bool FitsInInt;
2264 if (InitVal.isUnsigned() || !InitVal.isNegative())
2265 FitsInInt = InitVal.getActiveBits() < IntWidth;
2266 else
2267 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2268
2269 // If it fits into an integer type, force it. Otherwise force it to match
2270 // the enum decl type.
2271 QualType NewTy;
2272 unsigned NewWidth;
2273 bool NewSign;
2274 if (FitsInInt) {
2275 NewTy = Context.IntTy;
2276 NewWidth = IntWidth;
2277 NewSign = true;
2278 } else if (ECD->getType() == BestType) {
2279 // Already the right type!
2280 continue;
2281 } else {
2282 NewTy = BestType;
2283 NewWidth = BestWidth;
2284 NewSign = BestType->isSignedIntegerType();
2285 }
2286
2287 // Adjust the APSInt value.
2288 InitVal.extOrTrunc(NewWidth);
2289 InitVal.setIsSigned(NewSign);
2290 ECD->setInitVal(InitVal);
2291
2292 // Adjust the Expr initializer and type.
2293 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2294 ECD->setType(NewTy);
2295 }
Chris Lattnerac609682007-08-28 06:15:15 +00002296
Chris Lattnere00b18c2007-08-28 18:24:31 +00002297 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002298 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002299}
2300
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002301Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2302 ExprTy *expr) {
2303 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2304
Chris Lattner8e25d862008-03-16 00:16:02 +00002305 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002306}
2307
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002308Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002309 SourceLocation LBrace,
2310 SourceLocation RBrace,
2311 const char *Lang,
2312 unsigned StrSize,
2313 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002314 LinkageSpecDecl::LanguageIDs Language;
2315 Decl *dcl = static_cast<Decl *>(D);
2316 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2317 Language = LinkageSpecDecl::lang_c;
2318 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2319 Language = LinkageSpecDecl::lang_cxx;
2320 else {
2321 Diag(Loc, diag::err_bad_language);
2322 return 0;
2323 }
2324
2325 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002326 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002327}
2328
Chris Lattner985abd92008-06-26 06:49:43 +00002329void Sema::HandleDeclAttribute(Decl *New, const AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00002330
Chris Lattner74788ba2008-02-21 00:48:22 +00002331 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00002332 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00002333 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00002334 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002335 if (!newType.isNull()) // install the new vector type into the decl
2336 vDecl->setType(newType);
2337 }
2338 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2339 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00002340 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002341 if (!newType.isNull()) // install the new vector type into the decl
2342 tDecl->setUnderlyingType(newType);
2343 }
Chris Lattner212839c2008-02-20 23:17:35 +00002344 break;
Nate Begeman213541a2008-04-18 23:10:10 +00002345 case AttributeList::AT_ext_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00002346 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Nate Begeman213541a2008-04-18 23:10:10 +00002347 HandleExtVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00002348 else
Chris Lattner74788ba2008-02-21 00:48:22 +00002349 Diag(Attr->getLoc(),
Nate Begeman213541a2008-04-18 23:10:10 +00002350 diag::err_typecheck_ext_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00002351 break;
2352 case AttributeList::AT_address_space:
Chris Lattnerfca0ddd2008-06-26 06:27:57 +00002353 // Ignore this, this is a type attribute, handled by ProcessTypeAttributes.
Chris Lattner212839c2008-02-20 23:17:35 +00002354 break;
Eli Friedman3c0eb162008-05-27 03:33:27 +00002355 case AttributeList::AT_mode:
Chris Lattnerd546fc52008-06-26 06:39:41 +00002356 // Despite what would be logical, the mode attribute is a decl attribute,
2357 // not a type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make
2358 // 'G' be HImode, not an intermediate pointer.
Eli Friedman3c0eb162008-05-27 03:33:27 +00002359 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2360 QualType newType = HandleModeTypeAttribute(tDecl->getUnderlyingType(),
2361 Attr);
2362 tDecl->setUnderlyingType(newType);
2363 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2364 QualType newType = HandleModeTypeAttribute(vDecl->getType(), Attr);
2365 vDecl->setType(newType);
2366 }
2367 // FIXME: Diagnostic?
2368 break;
Nuno Lopesd4cbda62008-06-08 15:45:52 +00002369 case AttributeList::AT_alias:
2370 HandleAliasAttribute(New, Attr);
2371 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00002372 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00002373 HandleDeprecatedAttribute(New, Attr);
2374 break;
2375 case AttributeList::AT_visibility:
2376 HandleVisibilityAttribute(New, Attr);
2377 break;
2378 case AttributeList::AT_weak:
2379 HandleWeakAttribute(New, Attr);
2380 break;
2381 case AttributeList::AT_dllimport:
2382 HandleDLLImportAttribute(New, Attr);
2383 break;
2384 case AttributeList::AT_dllexport:
2385 HandleDLLExportAttribute(New, Attr);
2386 break;
2387 case AttributeList::AT_nothrow:
2388 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00002389 break;
Nate Begeman440b4562008-03-07 20:04:22 +00002390 case AttributeList::AT_stdcall:
2391 HandleStdCallAttribute(New, Attr);
2392 break;
2393 case AttributeList::AT_fastcall:
2394 HandleFastCallAttribute(New, Attr);
2395 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002396 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00002397 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002398 break;
2399 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00002400 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002401 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00002402 case AttributeList::AT_annotate:
2403 HandleAnnotateAttribute(New, Attr);
2404 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00002405 case AttributeList::AT_noreturn:
2406 HandleNoReturnAttribute(New, Attr);
2407 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00002408 case AttributeList::AT_format:
2409 HandleFormatAttribute(New, Attr);
2410 break;
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002411 case AttributeList::AT_transparent_union:
2412 HandleTransparentUnionAttribute(New, Attr);
2413 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002414 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00002415#if 0
2416 // TODO: when we have the full set of attributes, warn about unknown ones.
2417 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
2418 Attr->getName()->getName());
2419#endif
Chris Lattner212839c2008-02-20 23:17:35 +00002420 break;
2421 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002422}
2423
Chris Lattner985abd92008-06-26 06:49:43 +00002424void Sema::HandleDeclAttributes(Decl *New, const AttributeList *DeclSpecAttrs,
2425 const AttributeList *DeclaratorAttrs) {
2426 if (DeclSpecAttrs == 0 && DeclaratorAttrs == 0) return;
Chris Lattnerfca0ddd2008-06-26 06:27:57 +00002427
Chris Lattner985abd92008-06-26 06:49:43 +00002428 while (DeclSpecAttrs) {
2429 HandleDeclAttribute(New, DeclSpecAttrs);
2430 DeclSpecAttrs = DeclSpecAttrs->getNext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002431 }
Chris Lattnerfca0ddd2008-06-26 06:27:57 +00002432
2433 // If there are any type attributes that were in the declarator, apply them to
2434 // its top level type.
2435 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) {
2436 QualType DT = VD->getType();
Chris Lattner985abd92008-06-26 06:49:43 +00002437 ProcessTypeAttributes(DT, DeclaratorAttrs);
Chris Lattnerfca0ddd2008-06-26 06:27:57 +00002438 VD->setType(DT);
2439 } else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(New)) {
2440 QualType DT = TD->getUnderlyingType();
Chris Lattner985abd92008-06-26 06:49:43 +00002441 ProcessTypeAttributes(DT, DeclaratorAttrs);
Chris Lattnerfca0ddd2008-06-26 06:27:57 +00002442 TD->setUnderlyingType(DT);
2443 }
2444
Chris Lattner985abd92008-06-26 06:49:43 +00002445 while (DeclaratorAttrs) {
2446 HandleDeclAttribute(New, DeclaratorAttrs);
2447 DeclaratorAttrs = DeclaratorAttrs->getNext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002448 }
2449}
2450
Nate Begeman213541a2008-04-18 23:10:10 +00002451void Sema::HandleExtVectorTypeAttribute(TypedefDecl *tDecl,
Chris Lattner985abd92008-06-26 06:49:43 +00002452 const AttributeList *rawAttr) {
Steve Naroffbea0b342007-07-29 16:33:31 +00002453 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00002454 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00002455 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002456 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00002457 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002458 return;
Steve Naroff73322922007-07-18 18:00:27 +00002459 }
2460 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2461 llvm::APSInt vecSize(32);
2462 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002463 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Nate Begeman213541a2008-04-18 23:10:10 +00002464 "ext_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002465 return;
Steve Naroff73322922007-07-18 18:00:27 +00002466 }
2467 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2468 // in conjunction with complex types (pointers, arrays, functions, etc.).
2469 Type *canonType = curType.getCanonicalType().getTypePtr();
2470 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002471 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00002472 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002473 return;
Steve Naroff73322922007-07-18 18:00:27 +00002474 }
2475 // unlike gcc's vector_size attribute, the size is specified as the
2476 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002477 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002478
2479 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002480 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00002481 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002482 return;
Steve Naroff73322922007-07-18 18:00:27 +00002483 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002484 // Instantiate/Install the vector type, the number of elements is > 0.
Nate Begeman213541a2008-04-18 23:10:10 +00002485 tDecl->setUnderlyingType(Context.getExtVectorType(curType, vectorSize));
Steve Naroffbea0b342007-07-29 16:33:31 +00002486 // Remember this typedef decl, we will need it later for diagnostics.
Nate Begeman213541a2008-04-18 23:10:10 +00002487 ExtVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002488}
2489
Reid Spencer5f016e22007-07-11 17:01:13 +00002490QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattner985abd92008-06-26 06:49:43 +00002491 const AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002492 // check the attribute arugments.
2493 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002494 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00002495 std::string("1"));
2496 return QualType();
2497 }
2498 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2499 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002500 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002501 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002502 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002503 return QualType();
2504 }
2505 // navigate to the base type - we need to provide for vector pointers,
2506 // vector arrays, and functions returning vectors.
2507 Type *canonType = curType.getCanonicalType().getTypePtr();
2508
Steve Naroff73322922007-07-18 18:00:27 +00002509 if (canonType->isPointerType() || canonType->isArrayType() ||
2510 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00002511 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00002512 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2513 do {
2514 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2515 canonType = PT->getPointeeType().getTypePtr();
2516 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2517 canonType = AT->getElementType().getTypePtr();
2518 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2519 canonType = FT->getResultType().getTypePtr();
2520 } while (canonType->isPointerType() || canonType->isArrayType() ||
2521 canonType->isFunctionType());
2522 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002523 }
2524 // the base type must be integer or float.
2525 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002526 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00002527 curType.getCanonicalType().getAsString());
2528 return QualType();
2529 }
Chris Lattner98be4942008-03-05 18:54:05 +00002530 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00002531 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002532 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002533
2534 // the vector size needs to be an integral multiple of the type size.
2535 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00002536 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002537 sizeExpr->getSourceRange());
2538 return QualType();
2539 }
2540 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002541 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002542 sizeExpr->getSourceRange());
2543 return QualType();
2544 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00002545 // Instantiate the vector type, the number of elements is > 0, and not
2546 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00002547 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002548}
2549
Chris Lattner985abd92008-06-26 06:49:43 +00002550void Sema::HandlePackedAttribute(Decl *d, const AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00002551 // check the attribute arguments.
2552 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002553 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00002554 std::string("0"));
2555 return;
2556 }
2557
2558 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2559 TD->addAttr(new PackedAttr);
2560 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2561 // If the alignment is less than or equal to 8 bits, the packed attribute
2562 // has no effect.
Chris Lattnerabb57582008-05-09 05:34:49 +00002563 if (!FD->getType()->isIncompleteType() &&
2564 Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002565 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002566 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002567 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002568 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002569 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002570 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002571 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2572 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002573}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002574
Chris Lattner985abd92008-06-26 06:49:43 +00002575void Sema::HandleAliasAttribute(Decl *d, const AttributeList *rawAttr) {
Nuno Lopesd4cbda62008-06-08 15:45:52 +00002576 // check the attribute arguments.
2577 if (rawAttr->getNumArgs() != 1) {
2578 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2579 std::string("1"));
2580 return;
2581 }
2582
2583 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2584 Arg = Arg->IgnoreParenCasts();
2585 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2586
2587 if (Str == 0 || Str->isWide()) {
2588 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2589 "alias", std::string("1"));
2590 return;
2591 }
2592
2593 const char *Alias = Str->getStrData();
2594 unsigned AliasLen = Str->getByteLength();
2595
2596 // FIXME: check if target symbol exists in current file
2597
2598 d->addAttr(new AliasAttr(std::string(Alias, AliasLen)));
2599}
2600
Chris Lattner985abd92008-06-26 06:49:43 +00002601void Sema::HandleNoReturnAttribute(Decl *d, const AttributeList *rawAttr) {
Ted Kremenekaecb3832008-02-27 20:43:06 +00002602 // check the attribute arguments.
2603 if (rawAttr->getNumArgs() != 0) {
2604 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2605 std::string("0"));
2606 return;
2607 }
2608
Ted Kremenek3465fb32008-03-03 16:52:27 +00002609 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2610
2611 if (!Fn) {
2612 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2613 "noreturn", "function");
2614 return;
2615 }
2616
Ted Kremenekaecb3832008-02-27 20:43:06 +00002617 d->addAttr(new NoReturnAttr());
2618}
2619
Chris Lattner985abd92008-06-26 06:49:43 +00002620void Sema::HandleDeprecatedAttribute(Decl *d, const AttributeList *rawAttr) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002621 // check the attribute arguments.
2622 if (rawAttr->getNumArgs() != 0) {
2623 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2624 std::string("0"));
2625 return;
2626 }
2627
2628 d->addAttr(new DeprecatedAttr());
2629}
2630
Chris Lattner985abd92008-06-26 06:49:43 +00002631void Sema::HandleVisibilityAttribute(Decl *d, const AttributeList *rawAttr) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002632 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002633 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002634 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2635 std::string("1"));
2636 return;
2637 }
2638
Chris Lattner7b937ae2008-03-04 18:08:48 +00002639 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2640 Arg = Arg->IgnoreParenCasts();
2641 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2642
2643 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002644 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002645 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002646 return;
2647 }
2648
Chris Lattner7b937ae2008-03-04 18:08:48 +00002649 const char *TypeStr = Str->getStrData();
2650 unsigned TypeLen = Str->getByteLength();
Dan Gohman4f8d1232008-05-22 00:50:06 +00002651 VisibilityAttr::VisibilityTypes type;
Chris Lattnerddee4232008-03-03 03:28:21 +00002652
Chris Lattner7b937ae2008-03-04 18:08:48 +00002653 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002654 type = VisibilityAttr::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002655 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002656 type = VisibilityAttr::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002657 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002658 type = VisibilityAttr::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002659 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002660 type = VisibilityAttr::ProtectedVisibility;
Chris Lattnerddee4232008-03-03 03:28:21 +00002661 else {
2662 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002663 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002664 return;
2665 }
2666
2667 d->addAttr(new VisibilityAttr(type));
2668}
2669
Chris Lattner985abd92008-06-26 06:49:43 +00002670void Sema::HandleWeakAttribute(Decl *d, const AttributeList *rawAttr) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002671 // check the attribute arguments.
2672 if (rawAttr->getNumArgs() != 0) {
2673 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2674 std::string("0"));
2675 return;
2676 }
2677
2678 d->addAttr(new WeakAttr());
2679}
2680
Chris Lattner985abd92008-06-26 06:49:43 +00002681void Sema::HandleDLLImportAttribute(Decl *d, const AttributeList *rawAttr) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002682 // check the attribute arguments.
2683 if (rawAttr->getNumArgs() != 0) {
2684 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2685 std::string("0"));
2686 return;
2687 }
2688
2689 d->addAttr(new DLLImportAttr());
2690}
2691
Chris Lattner985abd92008-06-26 06:49:43 +00002692void Sema::HandleDLLExportAttribute(Decl *d, const AttributeList *rawAttr) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002693 // check the attribute arguments.
2694 if (rawAttr->getNumArgs() != 0) {
2695 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2696 std::string("0"));
2697 return;
2698 }
2699
2700 d->addAttr(new DLLExportAttr());
2701}
2702
Chris Lattner985abd92008-06-26 06:49:43 +00002703void Sema::HandleStdCallAttribute(Decl *d, const AttributeList *rawAttr) {
Nate Begeman440b4562008-03-07 20:04:22 +00002704 // check the attribute arguments.
2705 if (rawAttr->getNumArgs() != 0) {
2706 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2707 std::string("0"));
2708 return;
2709 }
2710
2711 d->addAttr(new StdCallAttr());
2712}
2713
Chris Lattner985abd92008-06-26 06:49:43 +00002714void Sema::HandleFastCallAttribute(Decl *d, const AttributeList *rawAttr) {
Nate Begeman440b4562008-03-07 20:04:22 +00002715 // check the attribute arguments.
2716 if (rawAttr->getNumArgs() != 0) {
2717 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2718 std::string("0"));
2719 return;
2720 }
2721
2722 d->addAttr(new FastCallAttr());
2723}
2724
Chris Lattner985abd92008-06-26 06:49:43 +00002725void Sema::HandleNothrowAttribute(Decl *d, const AttributeList *rawAttr) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002726 // check the attribute arguments.
2727 if (rawAttr->getNumArgs() != 0) {
2728 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2729 std::string("0"));
2730 return;
2731 }
2732
2733 d->addAttr(new NoThrowAttr());
2734}
2735
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002736static const FunctionTypeProto *getFunctionProto(Decl *d) {
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002737 QualType Ty;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002738
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002739 if (ValueDecl *decl = dyn_cast<ValueDecl>(d))
2740 Ty = decl->getType();
2741 else if (FieldDecl *decl = dyn_cast<FieldDecl>(d))
2742 Ty = decl->getType();
Ted Kremenek72786e02008-05-09 17:36:24 +00002743 else if (TypedefDecl* decl = dyn_cast<TypedefDecl>(d))
2744 Ty = decl->getUnderlyingType();
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002745 else
2746 return 0;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002747
2748 if (Ty->isFunctionPointerType()) {
2749 const PointerType *PtrTy = Ty->getAsPointerType();
2750 Ty = PtrTy->getPointeeType();
2751 }
2752
2753 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2754 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2755
2756 return 0;
2757}
2758
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002759static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
2760 if (!T->isPointerType())
2761 return false;
2762
2763 T = T->getAsPointerType()->getPointeeType().getCanonicalType();
2764 ObjCInterfaceType* ClsT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
2765
2766 if (!ClsT)
2767 return false;
2768
2769 IdentifierInfo* ClsName = ClsT->getDecl()->getIdentifier();
2770
2771 // FIXME: Should we walk the chain of classes?
2772 return ClsName == &Ctx.Idents.get("NSString") ||
2773 ClsName == &Ctx.Idents.get("NSMutableString");
2774}
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002775
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002776/// Handle __attribute__((format(type,idx,firstarg))) attributes
2777/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattner985abd92008-06-26 06:49:43 +00002778void Sema::HandleFormatAttribute(Decl *d, const AttributeList *rawAttr) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002779
2780 if (!rawAttr->getParameterName()) {
2781 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2782 "format", std::string("1"));
2783 return;
2784 }
2785
2786 if (rawAttr->getNumArgs() != 2) {
2787 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2788 std::string("3"));
2789 return;
2790 }
2791
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002792 // GCC ignores the format attribute on K&R style function
2793 // prototypes, so we ignore it as well
2794 const FunctionTypeProto *proto = getFunctionProto(d);
2795
2796 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002797 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2798 "format", "function");
2799 return;
2800 }
2801
2802 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002803 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002804 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002805 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002806 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002807
2808 const char *Format = rawAttr->getParameterName()->getName();
2809 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2810
2811 // Normalize the argument, __foo__ becomes foo.
2812 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2813 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2814 Format += 2;
2815 FormatLen -= 4;
2816 }
2817
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002818 bool Supported = false;
2819 bool is_NSString = false;
2820 bool is_strftime = false;
2821
2822 switch (FormatLen) {
2823 default: break;
2824 case 5:
2825 Supported = !memcmp(Format, "scanf", 5);
2826 break;
2827 case 6:
2828 Supported = !memcmp(Format, "printf", 6);
2829 break;
2830 case 7:
2831 Supported = !memcmp(Format, "strfmon", 7);
2832 break;
2833 case 8:
2834 Supported = (is_strftime = !memcmp(Format, "strftime", 8)) ||
2835 (is_NSString = !memcmp(Format, "NSString", 8));
2836 break;
2837 }
2838
2839 if (!Supported) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002840 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2841 "format", rawAttr->getParameterName()->getName());
2842 return;
2843 }
2844
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002845 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002846 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002847 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002848 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2849 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2850 "format", std::string("2"), IdxExpr->getSourceRange());
2851 return;
2852 }
2853
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002854 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002855 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2856 "format", std::string("2"), IdxExpr->getSourceRange());
2857 return;
2858 }
2859
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002860 // FIXME: Do we need to bounds check?
2861 unsigned ArgIdx = Idx.getZExtValue() - 1;
2862
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002863 // make sure the format string is really a string
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002864 QualType Ty = proto->getArgType(ArgIdx);
2865
2866 if (is_NSString) {
2867 // FIXME: do we need to check if the type is NSString*? What are
2868 // the semantics?
2869 if (!isNSStringType(Ty, Context)) {
2870 // FIXME: Should highlight the actual expression that has the
2871 // wrong type.
2872 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_NSString,
2873 IdxExpr->getSourceRange());
2874 return;
2875 }
2876 }
2877 else if (!Ty->isPointerType() ||
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002878 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002879 // FIXME: Should highlight the actual expression that has the
2880 // wrong type.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002881 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2882 IdxExpr->getSourceRange());
2883 return;
2884 }
2885
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002886 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002887 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002888 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002889 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2890 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2891 "format", std::string("3"), FirstArgExpr->getSourceRange());
2892 return;
2893 }
2894
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002895 // check if the function is variadic if the 3rd argument non-zero
2896 if (FirstArg != 0) {
2897 if (proto->isVariadic()) {
2898 ++NumArgs; // +1 for ...
2899 } else {
2900 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2901 return;
2902 }
2903 }
2904
2905 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2906 // the input is just the current time + the format string
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002907 if (is_strftime) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002908 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002909 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2910 FirstArgExpr->getSourceRange());
2911 return;
2912 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002913 // if 0 it disables parameter checking (to use with e.g. va_list)
2914 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002915 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2916 "format", std::string("3"), FirstArgExpr->getSourceRange());
2917 return;
2918 }
2919
2920 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2921 Idx.getZExtValue(), FirstArg.getZExtValue()));
2922}
2923
Chris Lattner985abd92008-06-26 06:49:43 +00002924void Sema::HandleTransparentUnionAttribute(Decl *d,
2925 const AttributeList *rawAttr) {
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002926 // check the attribute arguments.
2927 if (rawAttr->getNumArgs() != 0) {
2928 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2929 std::string("0"));
2930 return;
2931 }
2932
2933 TypeDecl *decl = dyn_cast<TypeDecl>(d);
2934
2935 if (!decl || !Context.getTypeDeclType(decl)->isUnionType()) {
2936 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2937 "transparent_union", "union");
2938 return;
2939 }
2940
Chris Lattner22624942008-04-30 16:04:01 +00002941 //QualType QTy = Context.getTypeDeclType(decl);
2942 //const RecordType *Ty = QTy->getAsUnionType();
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002943
2944// FIXME
2945// Ty->addAttr(new TransparentUnionAttr());
2946}
2947
Chris Lattner985abd92008-06-26 06:49:43 +00002948void Sema::HandleAnnotateAttribute(Decl *d, const AttributeList *rawAttr) {
Nate Begemanc398f0b2008-02-21 19:30:49 +00002949 // check the attribute arguments.
2950 if (rawAttr->getNumArgs() != 1) {
2951 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2952 std::string("1"));
2953 return;
2954 }
2955 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2956 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002957
Nate Begemanc398f0b2008-02-21 19:30:49 +00002958 // Make sure that there is a string literal as the annotation's single
2959 // argument.
2960 if (!SE) {
2961 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2962 return;
2963 }
2964 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2965 SE->getByteLength())));
2966}
2967
Chris Lattner985abd92008-06-26 06:49:43 +00002968void Sema::HandleAlignedAttribute(Decl *d, const AttributeList *rawAttr)
Anders Carlsson78aaae92007-12-19 07:19:40 +00002969{
2970 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002971 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002972 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002973 std::string("1"));
2974 return;
2975 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002976
Anders Carlsson042c4e72008-02-16 19:51:27 +00002977 unsigned Align = 0;
2978
2979 if (rawAttr->getNumArgs() == 0) {
2980 // FIXME: This should be the target specific maximum alignment.
2981 // (For now we just use 128 bits which is the maximum on X86.
2982 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002983 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002984 } else {
2985 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2986 llvm::APSInt alignment(32);
2987 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002988 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002989 "aligned", alignmentExpr->getSourceRange());
2990 return;
2991 }
2992
2993 Align = alignment.getZExtValue() * 8;
2994 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002995
Anders Carlsson042c4e72008-02-16 19:51:27 +00002996 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002997}