blob: 2d6422fb0071b87e1324fe9f11bf4c09e8a37972 [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;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000233
234 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
235 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
236 // *either* declaration is in a system header. The code below implements
237 // this adhoc compatibility rule. FIXME: The following code will not
238 // work properly when compiling ".i" files (containing preprocessed output).
239 SourceManager &SrcMgr = Context.getSourceManager();
240 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
241 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
242 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
243 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
244 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
245
Steve Naroffc5e2f342008-03-26 21:27:00 +0000246 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
247 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
248 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroffd62701b2008-02-07 03:50:06 +0000249 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000250 return New;
Steve Naroffc5e2f342008-03-26 21:27:00 +0000251
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
253 // TODO: This is totally simplistic. It should handle merging functions
254 // together etc, merging extern int X; int X; ...
Ted Kremenek2d05c082008-05-23 21:28:18 +0000255 Diag(New->getLocation(), diag::err_redefinition, New->getName());
256 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000257 return New;
258}
259
Chris Lattnerddee4232008-03-03 03:28:21 +0000260/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
261static bool DeclHasAttr(const Decl *decl, const Attr *target) {
262 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
263 if (attr->getKind() == target->getKind())
264 return true;
265
266 return false;
267}
268
269/// MergeAttributes - append attributes from the Old decl to the New one.
270static void MergeAttributes(Decl *New, Decl *Old) {
271 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
272
Chris Lattnerddee4232008-03-03 03:28:21 +0000273 while (attr) {
274 tmp = attr;
275 attr = attr->getNext();
276
277 if (!DeclHasAttr(New, tmp)) {
278 New->addAttr(tmp);
279 } else {
280 tmp->setNext(0);
281 delete(tmp);
282 }
283 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000284
285 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000286}
287
Chris Lattner04421082008-04-08 04:40:51 +0000288/// MergeFunctionDecl - We just parsed a function 'New' from
289/// declarator D which has the same name and scope as a previous
290/// declaration 'Old'. Figure out how to resolve this situation,
291/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000292/// Redeclaration will be set true if thisNew is a redeclaration OldD.
293FunctionDecl *
294Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
295 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000296 // Verify the old decl was also a function.
297 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
298 if (!Old) {
299 Diag(New->getLocation(), diag::err_redefinition_different_kind,
300 New->getName());
301 Diag(OldD->getLocation(), diag::err_previous_definition);
302 return New;
303 }
Chris Lattner04421082008-04-08 04:40:51 +0000304
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000305 QualType OldQType = Context.getCanonicalType(Old->getType());
306 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000307
Chris Lattner04421082008-04-08 04:40:51 +0000308 // C++ [dcl.fct]p3:
309 // All declarations for a function shall agree exactly in both the
310 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000311 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
312 MergeAttributes(New, Old);
313 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000314 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000315 }
Chris Lattner04421082008-04-08 04:40:51 +0000316
317 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000318 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000319 if (!getLangOptions().CPlusPlus &&
320 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000321 MergeAttributes(New, Old);
322 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000323 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000324 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000325
Steve Naroff837618c2008-01-16 15:01:34 +0000326 // A function that has already been declared has been redeclared or defined
327 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000328 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000329 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000330 PrevDiag = diag::err_previous_definition;
331 else if (Old->isImplicit())
332 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000333 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000334 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000335
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
337 // TODO: This is totally simplistic. It should handle merging functions
338 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000339 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
340 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000341 return New;
342}
343
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000344/// equivalentArrayTypes - Used to determine whether two array types are
345/// equivalent.
346/// We need to check this explicitly as an incomplete array definition is
347/// considered a VariableArrayType, so will not match a complete array
348/// definition that would be otherwise equivalent.
349static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
350 const ArrayType *NewAT = NewQType->getAsArrayType();
351 const ArrayType *OldAT = OldQType->getAsArrayType();
352
353 if (!NewAT || !OldAT)
354 return false;
355
356 // If either (or both) array types in incomplete we need to strip off the
357 // outer VariableArrayType. Once the outer VAT is removed the remaining
358 // types must be identical if the array types are to be considered
359 // equivalent.
360 // eg. int[][1] and int[1][1] become
361 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
362 // removing the outermost VAT gives
363 // CAT(1, int) and CAT(1, int)
364 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000365 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000366 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
367 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000368 NewQType = NewAT->getElementType().getCanonicalType();
369 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000370 }
371
372 return NewQType == OldQType;
373}
374
Reid Spencer5f016e22007-07-11 17:01:13 +0000375/// MergeVarDecl - We just parsed a variable 'New' which has the same name
376/// and scope as a previous declaration 'Old'. Figure out how to resolve this
377/// situation, merging decls or emitting diagnostics as appropriate.
378///
379/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
380/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
381///
Steve Naroffe8043c32008-04-01 23:04:06 +0000382VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 // Verify the old decl was also a variable.
384 VarDecl *Old = dyn_cast<VarDecl>(OldD);
385 if (!Old) {
386 Diag(New->getLocation(), diag::err_redefinition_different_kind,
387 New->getName());
388 Diag(OldD->getLocation(), diag::err_previous_definition);
389 return New;
390 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000391
392 MergeAttributes(New, Old);
393
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000395 QualType OldCType = Context.getCanonicalType(Old->getType());
396 QualType NewCType = Context.getCanonicalType(New->getType());
397 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 Diag(New->getLocation(), diag::err_redefinition, New->getName());
399 Diag(Old->getLocation(), diag::err_previous_definition);
400 return New;
401 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000402 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
403 if (New->getStorageClass() == VarDecl::Static &&
404 (Old->getStorageClass() == VarDecl::None ||
405 Old->getStorageClass() == VarDecl::Extern)) {
406 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
407 Diag(Old->getLocation(), diag::err_previous_definition);
408 return New;
409 }
410 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
411 if (New->getStorageClass() != VarDecl::Static &&
412 Old->getStorageClass() == VarDecl::Static) {
413 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
414 Diag(Old->getLocation(), diag::err_previous_definition);
415 return New;
416 }
417 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff248a7532008-04-15 22:42:06 +0000418 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb7b032e2008-01-30 00:44:01 +0000419 // Handle C "tentative" external object definitions (C99 6.9.2).
420 bool OldIsTentative = false;
421 bool NewIsTentative = false;
422
Steve Naroff248a7532008-04-15 22:42:06 +0000423 if (!Old->getInit() &&
424 (Old->getStorageClass() == VarDecl::None ||
425 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000426 OldIsTentative = true;
427
428 // FIXME: this check doesn't work (since the initializer hasn't been
429 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
430 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
431 // thrown out the old decl.
Steve Naroff248a7532008-04-15 22:42:06 +0000432 if (!New->getInit() &&
433 (New->getStorageClass() == VarDecl::None ||
434 New->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000435 ; // change to NewIsTentative = true; once the code is moved.
436
437 if (NewIsTentative || OldIsTentative)
438 return New;
439 }
Steve Naroff235549c2008-05-12 22:36:43 +0000440 // Handle __private_extern__ just like extern.
Steve Naroffb7b032e2008-01-30 00:44:01 +0000441 if (Old->getStorageClass() != VarDecl::Extern &&
Steve Naroff235549c2008-05-12 22:36:43 +0000442 Old->getStorageClass() != VarDecl::PrivateExtern &&
443 New->getStorageClass() != VarDecl::Extern &&
444 New->getStorageClass() != VarDecl::PrivateExtern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000445 Diag(New->getLocation(), diag::err_redefinition, New->getName());
446 Diag(Old->getLocation(), diag::err_previous_definition);
447 }
448 return New;
449}
450
Chris Lattner04421082008-04-08 04:40:51 +0000451/// CheckParmsForFunctionDef - Check that the parameters of the given
452/// function are appropriate for the definition of a function. This
453/// takes care of any checks that cannot be performed on the
454/// declaration itself, e.g., that the types of each of the function
455/// parameters are complete.
456bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
457 bool HasInvalidParm = false;
458 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
459 ParmVarDecl *Param = FD->getParamDecl(p);
460
461 // C99 6.7.5.3p4: the parameters in a parameter type list in a
462 // function declarator that is part of a function definition of
463 // that function shall not have incomplete type.
464 if (Param->getType()->isIncompleteType() &&
465 !Param->isInvalidDecl()) {
466 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
467 Param->getType().getAsString());
468 Param->setInvalidDecl();
469 HasInvalidParm = true;
470 }
471 }
472
473 return HasInvalidParm;
474}
475
476/// CreateImplicitParameter - Creates an implicit function parameter
477/// in the scope S and with the given type. This routine is used, for
478/// example, to create the implicit "self" parameter in an Objective-C
479/// method.
480ParmVarDecl *
481Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
482 SourceLocation IdLoc, QualType Type) {
483 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
484 VarDecl::None, 0, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000485 if (Id)
486 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000487
488 return New;
489}
490
Reid Spencer5f016e22007-07-11 17:01:13 +0000491/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
492/// no declarator (e.g. "struct foo;") is parsed.
493Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
494 // TODO: emit error on 'int;' or 'const enum foo;'.
495 // TODO: emit error on 'typedef int;'
496 // if (!DS.isMissingDeclaratorOk()) Diag(...);
497
Steve Naroff92199282007-11-17 21:37:36 +0000498 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000499}
500
Steve Naroffd0091aa2008-01-10 22:15:12 +0000501bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000502 // Get the type before calling CheckSingleAssignmentConstraints(), since
503 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000504 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000505
Chris Lattner5cf216b2008-01-04 18:04:52 +0000506 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
507 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
508 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000509}
510
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000511bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000512 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000513 // C99 6.7.8p14. We have an array of character type with unknown size
514 // being initialized to a string literal.
515 llvm::APSInt ConstVal(32);
516 ConstVal = strLiteral->getByteLength() + 1;
517 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000518 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000519 ArrayType::Normal, 0);
520 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
521 // C99 6.7.8p14. We have an array of character type with known size.
522 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
523 Diag(strLiteral->getSourceRange().getBegin(),
524 diag::warn_initializer_string_for_char_array_too_long,
525 strLiteral->getSourceRange());
526 } else {
527 assert(0 && "HandleStringLiteralInit(): Invalid array type");
528 }
529 // Set type from "char *" to "constant array of char".
530 strLiteral->setType(DeclT);
531 // For now, we always return false (meaning success).
532 return false;
533}
534
535StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000536 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000537 if (AT && AT->getElementType()->isCharType()) {
538 return dyn_cast<StringLiteral>(Init);
539 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000540 return 0;
541}
542
Steve Naroffa9960332008-01-25 00:51:06 +0000543bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000544 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
545 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000546 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000547 return Diag(VAT->getSizeExpr()->getLocStart(),
548 diag::err_variable_object_no_init,
549 VAT->getSizeExpr()->getSourceRange());
550
Steve Naroff2fdc3742007-12-10 22:44:33 +0000551 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
552 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000553 // FIXME: Handle wide strings
554 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
555 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000556
557 if (DeclType->isArrayType())
558 return Diag(Init->getLocStart(),
559 diag::err_array_init_list_required,
560 Init->getSourceRange());
561
Steve Naroffd0091aa2008-01-10 22:15:12 +0000562 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000563 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000564
Steve Naroff0cca7492008-05-01 22:18:59 +0000565 InitListChecker CheckInitList(this, InitList, DeclType);
566 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000567}
568
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000569Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000570Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000571 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 IdentifierInfo *II = D.getIdentifier();
573
Chris Lattnere80a59c2007-07-25 00:24:17 +0000574 // All of these full declarators require an identifier. If it doesn't have
575 // one, the ParsedFreeStandingDeclSpec action should be used.
576 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000577 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000578 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000579 D.getDeclSpec().getSourceRange(), D.getSourceRange());
580 return 0;
581 }
582
Chris Lattner31e05722007-08-26 06:24:45 +0000583 // The scope passed in may not be a decl scope. Zip up the scope tree until
584 // we find one that is.
585 while ((S->getFlags() & Scope::DeclScope) == 0)
586 S = S->getParent();
587
Reid Spencer5f016e22007-07-11 17:01:13 +0000588 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000589 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000590 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000591 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000592
593 // In C++, the previous declaration we find might be a tag type
594 // (class or enum). In this case, the new declaration will hide the
595 // tag type.
596 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
597 PrevDecl = 0;
598
Chris Lattner41af0932007-11-14 06:34:38 +0000599 QualType R = GetTypeForDeclarator(D, S);
600 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
601
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000603 // Check that there are no default arguments (C++ only).
604 if (getLangOptions().CPlusPlus)
605 CheckExtraCXXDefaultArguments(D);
606
Chris Lattner41af0932007-11-14 06:34:38 +0000607 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000608 if (!NewTD) return 0;
609
610 // Handle attributes prior to checking for duplicates in MergeVarDecl
611 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
612 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000613 // Merge the decl with the existing one if appropriate. If the decl is
614 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000615 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000616 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
617 if (NewTD == 0) return 0;
618 }
619 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000620 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000621 // C99 6.7.7p2: If a typedef name specifies a variably modified type
622 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000623 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
624 // FIXME: Diagnostic needs to be fixed.
625 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000626 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000627 }
628 }
Chris Lattner41af0932007-11-14 06:34:38 +0000629 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000630 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 switch (D.getDeclSpec().getStorageClassSpec()) {
632 default: assert(0 && "Unknown storage class!");
633 case DeclSpec::SCS_auto:
634 case DeclSpec::SCS_register:
635 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
636 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000637 InvalidDecl = true;
638 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000639 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
640 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
641 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000642 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 }
644
Chris Lattnera98e58d2008-03-15 21:24:04 +0000645 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000646 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
647 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000648 II, R, SC, isInline,
649 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000650 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000651 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
652 D.getAttributes());
Chris Lattner04421082008-04-08 04:40:51 +0000653
654 // Copy the parameter declarations from the declarator D to
655 // the function declaration NewFD, if they are available.
656 if (D.getNumTypeObjects() > 0 &&
657 D.getTypeObject(0).Fun.hasPrototype) {
658 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
659
660 // Create Decl objects for each parameter, adding them to the
661 // FunctionDecl.
662 llvm::SmallVector<ParmVarDecl*, 16> Params;
663
664 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
665 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000666 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000667 // We let through "const void" here because Sema::GetTypeForDeclarator
668 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000669 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
670 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000671 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
672 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000673 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
674
Chris Lattnerdef026a2008-04-10 02:26:16 +0000675 // In C++, the empty parameter-type-list must be spelled "void"; a
676 // typedef of void is not permitted.
677 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000678 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000679 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
680 }
681
Chris Lattner04421082008-04-08 04:40:51 +0000682 } else {
683 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
684 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
685 }
686
687 NewFD->setParams(&Params[0], Params.size());
688 }
689
Steve Naroffffce4d52008-01-09 23:34:55 +0000690 // Merge the decl with the existing one if appropriate. Since C functions
691 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000692 if (PrevDecl &&
693 (!getLangOptions().CPlusPlus ||
694 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000695 bool Redeclaration = false;
696 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000698 if (Redeclaration) {
Eli Friedman27424962008-05-27 05:07:37 +0000699 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregorf0097952008-04-21 02:02:58 +0000700 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 }
702 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000703
704 // In C++, check default arguments now that we have merged decls.
705 if (getLangOptions().CPlusPlus)
706 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000708 // Check that there are no default arguments (C++ only).
709 if (getLangOptions().CPlusPlus)
710 CheckExtraCXXDefaultArguments(D);
711
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000712 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000713 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
714 D.getIdentifier()->getName());
715 InvalidDecl = true;
716 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000717
718 VarDecl *NewVD;
719 VarDecl::StorageClass SC;
720 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000721 default: assert(0 && "Unknown storage class!");
722 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
723 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
724 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
725 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
726 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
727 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000729 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 // C99 6.9p2: The storage-class specifiers auto and register shall not
731 // appear in the declaration specifiers in an external declaration.
732 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
733 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
734 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000735 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 }
Steve Naroff248a7532008-04-15 22:42:06 +0000737 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
738 II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000739 } else {
Steve Naroff248a7532008-04-15 22:42:06 +0000740 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
741 II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000742 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000743 // Handle attributes prior to checking for duplicates in MergeVarDecl
744 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
745 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000746
747 // Emit an error if an address space was applied to decl with local storage.
748 // This includes arrays of objects with address space qualifiers, but not
749 // automatic variables that point to other address spaces.
750 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000751 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
752 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
753 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000754 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000755 // Merge the decl with the existing one if appropriate. If the decl is
756 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000757 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000758 NewVD = MergeVarDecl(NewVD, PrevDecl);
759 if (NewVD == 0) return 0;
760 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 New = NewVD;
762 }
763
764 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000765 if (II)
766 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000767 // If any semantic error occurred, mark the decl as invalid.
768 if (D.getInvalidType() || InvalidDecl)
769 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000770
771 return New;
772}
773
Eli Friedmanc594b322008-05-20 13:48:25 +0000774bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
775 switch (Init->getStmtClass()) {
776 default:
777 Diag(Init->getExprLoc(),
778 diag::err_init_element_not_constant, Init->getSourceRange());
779 return true;
780 case Expr::ParenExprClass: {
781 const ParenExpr* PE = cast<ParenExpr>(Init);
782 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
783 }
784 case Expr::CompoundLiteralExprClass:
785 return cast<CompoundLiteralExpr>(Init)->isFileScope();
786 case Expr::DeclRefExprClass: {
787 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +0000788 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
789 if (VD->hasGlobalStorage())
790 return false;
791 Diag(Init->getExprLoc(),
792 diag::err_init_element_not_constant, Init->getSourceRange());
793 return true;
794 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000795 if (isa<FunctionDecl>(D))
796 return false;
797 Diag(Init->getExprLoc(),
798 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroffd0091aa2008-01-10 22:15:12 +0000799 return true;
800 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000801 case Expr::MemberExprClass: {
802 const MemberExpr *M = cast<MemberExpr>(Init);
803 if (M->isArrow())
804 return CheckAddressConstantExpression(M->getBase());
805 return CheckAddressConstantExpressionLValue(M->getBase());
806 }
807 case Expr::ArraySubscriptExprClass: {
808 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
809 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
810 return CheckAddressConstantExpression(ASE->getBase()) ||
811 CheckArithmeticConstantExpression(ASE->getIdx());
812 }
813 case Expr::StringLiteralClass:
814 case Expr::PreDefinedExprClass:
815 return false;
816 case Expr::UnaryOperatorClass: {
817 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
818
819 // C99 6.6p9
820 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +0000821 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +0000822
823 Diag(Init->getExprLoc(),
824 diag::err_init_element_not_constant, Init->getSourceRange());
825 return true;
826 }
827 }
828}
829
830bool Sema::CheckAddressConstantExpression(const Expr* Init) {
831 switch (Init->getStmtClass()) {
832 default:
833 Diag(Init->getExprLoc(),
834 diag::err_init_element_not_constant, Init->getSourceRange());
835 return true;
836 case Expr::ParenExprClass: {
837 const ParenExpr* PE = cast<ParenExpr>(Init);
838 return CheckAddressConstantExpression(PE->getSubExpr());
839 }
840 case Expr::StringLiteralClass:
841 case Expr::ObjCStringLiteralClass:
842 return false;
843 case Expr::CallExprClass: {
844 const CallExpr *CE = cast<CallExpr>(Init);
845 if (CE->isBuiltinConstantExpr())
846 return false;
847 Diag(Init->getExprLoc(),
848 diag::err_init_element_not_constant, Init->getSourceRange());
849 return true;
850 }
851 case Expr::UnaryOperatorClass: {
852 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
853
854 // C99 6.6p9
855 if (Exp->getOpcode() == UnaryOperator::AddrOf)
856 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
857
858 if (Exp->getOpcode() == UnaryOperator::Extension)
859 return CheckAddressConstantExpression(Exp->getSubExpr());
860
861 Diag(Init->getExprLoc(),
862 diag::err_init_element_not_constant, Init->getSourceRange());
863 return true;
864 }
865 case Expr::BinaryOperatorClass: {
866 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
867 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
868
869 Expr *PExp = Exp->getLHS();
870 Expr *IExp = Exp->getRHS();
871 if (IExp->getType()->isPointerType())
872 std::swap(PExp, IExp);
873
874 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
875 return CheckAddressConstantExpression(PExp) ||
876 CheckArithmeticConstantExpression(IExp);
877 }
878 case Expr::ImplicitCastExprClass: {
879 const Expr* SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
880
881 // Check for implicit promotion
882 if (SubExpr->getType()->isFunctionType() ||
883 SubExpr->getType()->isArrayType())
884 return CheckAddressConstantExpressionLValue(SubExpr);
885
886 // Check for pointer->pointer cast
887 if (SubExpr->getType()->isPointerType())
888 return CheckAddressConstantExpression(SubExpr);
889
890 if (SubExpr->getType()->isArithmeticType())
891 return CheckArithmeticConstantExpression(SubExpr);
892
893 Diag(Init->getExprLoc(),
894 diag::err_init_element_not_constant, Init->getSourceRange());
895 return true;
896 }
897 case Expr::CastExprClass: {
898 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
899
900 // Check for pointer->pointer cast
901 if (SubExpr->getType()->isPointerType())
902 return CheckAddressConstantExpression(SubExpr);
903
904 // FIXME: Should we pedwarn for (int*)(0+0)?
905 if (SubExpr->getType()->isArithmeticType())
906 return CheckArithmeticConstantExpression(SubExpr);
907
908 Diag(Init->getExprLoc(),
909 diag::err_init_element_not_constant, Init->getSourceRange());
910 return true;
911 }
912 case Expr::ConditionalOperatorClass: {
913 // FIXME: Should we pedwarn here?
914 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
915 if (!Exp->getCond()->getType()->isArithmeticType()) {
916 Diag(Init->getExprLoc(),
917 diag::err_init_element_not_constant, Init->getSourceRange());
918 return true;
919 }
920 if (CheckArithmeticConstantExpression(Exp->getCond()))
921 return true;
922 if (Exp->getLHS() &&
923 CheckAddressConstantExpression(Exp->getLHS()))
924 return true;
925 return CheckAddressConstantExpression(Exp->getRHS());
926 }
927 case Expr::AddrLabelExprClass:
928 return false;
929 }
930}
931
Eli Friedman4caf0552008-06-09 05:05:07 +0000932static const Expr* FindExpressionBaseAddress(const Expr* E);
933
934static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
935 switch (E->getStmtClass()) {
936 default:
937 return E;
938 case Expr::ParenExprClass: {
939 const ParenExpr* PE = cast<ParenExpr>(E);
940 return FindExpressionBaseAddressLValue(PE->getSubExpr());
941 }
942 case Expr::MemberExprClass: {
943 const MemberExpr *M = cast<MemberExpr>(E);
944 if (M->isArrow())
945 return FindExpressionBaseAddress(M->getBase());
946 return FindExpressionBaseAddressLValue(M->getBase());
947 }
948 case Expr::ArraySubscriptExprClass: {
949 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
950 return FindExpressionBaseAddress(ASE->getBase());
951 }
952 case Expr::UnaryOperatorClass: {
953 const UnaryOperator *Exp = cast<UnaryOperator>(E);
954
955 if (Exp->getOpcode() == UnaryOperator::Deref)
956 return FindExpressionBaseAddress(Exp->getSubExpr());
957
958 return E;
959 }
960 }
961}
962
963static const Expr* FindExpressionBaseAddress(const Expr* E) {
964 switch (E->getStmtClass()) {
965 default:
966 return E;
967 case Expr::ParenExprClass: {
968 const ParenExpr* PE = cast<ParenExpr>(E);
969 return FindExpressionBaseAddress(PE->getSubExpr());
970 }
971 case Expr::UnaryOperatorClass: {
972 const UnaryOperator *Exp = cast<UnaryOperator>(E);
973
974 // C99 6.6p9
975 if (Exp->getOpcode() == UnaryOperator::AddrOf)
976 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
977
978 if (Exp->getOpcode() == UnaryOperator::Extension)
979 return FindExpressionBaseAddress(Exp->getSubExpr());
980
981 return E;
982 }
983 case Expr::BinaryOperatorClass: {
984 const BinaryOperator *Exp = cast<BinaryOperator>(E);
985
986 Expr *PExp = Exp->getLHS();
987 Expr *IExp = Exp->getRHS();
988 if (IExp->getType()->isPointerType())
989 std::swap(PExp, IExp);
990
991 return FindExpressionBaseAddress(PExp);
992 }
993 case Expr::ImplicitCastExprClass: {
994 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
995
996 // Check for implicit promotion
997 if (SubExpr->getType()->isFunctionType() ||
998 SubExpr->getType()->isArrayType())
999 return FindExpressionBaseAddressLValue(SubExpr);
1000
1001 // Check for pointer->pointer cast
1002 if (SubExpr->getType()->isPointerType())
1003 return FindExpressionBaseAddress(SubExpr);
1004
1005 // We assume that we have an arithmetic expression here;
1006 // if we don't, we'll figure it out later
1007 return 0;
1008 }
1009 case Expr::CastExprClass: {
1010 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1011
1012 // Check for pointer->pointer cast
1013 if (SubExpr->getType()->isPointerType())
1014 return FindExpressionBaseAddress(SubExpr);
1015
1016 // We assume that we have an arithmetic expression here;
1017 // if we don't, we'll figure it out later
1018 return 0;
1019 }
1020 }
1021}
1022
Eli Friedmanc594b322008-05-20 13:48:25 +00001023bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1024 switch (Init->getStmtClass()) {
1025 default:
1026 Diag(Init->getExprLoc(),
1027 diag::err_init_element_not_constant, Init->getSourceRange());
1028 return true;
1029 case Expr::ParenExprClass: {
1030 const ParenExpr* PE = cast<ParenExpr>(Init);
1031 return CheckArithmeticConstantExpression(PE->getSubExpr());
1032 }
1033 case Expr::FloatingLiteralClass:
1034 case Expr::IntegerLiteralClass:
1035 case Expr::CharacterLiteralClass:
1036 case Expr::ImaginaryLiteralClass:
1037 case Expr::TypesCompatibleExprClass:
1038 case Expr::CXXBoolLiteralExprClass:
1039 return false;
1040 case Expr::CallExprClass: {
1041 const CallExpr *CE = cast<CallExpr>(Init);
1042 if (CE->isBuiltinConstantExpr())
1043 return false;
1044 Diag(Init->getExprLoc(),
1045 diag::err_init_element_not_constant, Init->getSourceRange());
1046 return true;
1047 }
1048 case Expr::DeclRefExprClass: {
1049 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1050 if (isa<EnumConstantDecl>(D))
1051 return false;
1052 Diag(Init->getExprLoc(),
1053 diag::err_init_element_not_constant, Init->getSourceRange());
1054 return true;
1055 }
1056 case Expr::CompoundLiteralExprClass:
1057 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1058 // but vectors are allowed to be magic.
1059 if (Init->getType()->isVectorType())
1060 return false;
1061 Diag(Init->getExprLoc(),
1062 diag::err_init_element_not_constant, Init->getSourceRange());
1063 return true;
1064 case Expr::UnaryOperatorClass: {
1065 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1066
1067 switch (Exp->getOpcode()) {
1068 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1069 // See C99 6.6p3.
1070 default:
1071 Diag(Init->getExprLoc(),
1072 diag::err_init_element_not_constant, Init->getSourceRange());
1073 return true;
1074 case UnaryOperator::SizeOf:
1075 case UnaryOperator::AlignOf:
1076 case UnaryOperator::OffsetOf:
1077 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1078 // See C99 6.5.3.4p2 and 6.6p3.
1079 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1080 return false;
1081 Diag(Init->getExprLoc(),
1082 diag::err_init_element_not_constant, Init->getSourceRange());
1083 return true;
1084 case UnaryOperator::Extension:
1085 case UnaryOperator::LNot:
1086 case UnaryOperator::Plus:
1087 case UnaryOperator::Minus:
1088 case UnaryOperator::Not:
1089 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1090 }
1091 }
1092 case Expr::SizeOfAlignOfTypeExprClass: {
1093 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1094 // Special check for void types, which are allowed as an extension
1095 if (Exp->getArgumentType()->isVoidType())
1096 return false;
1097 // alignof always evaluates to a constant.
1098 // FIXME: is sizeof(int[3.0]) a constant expression?
1099 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1100 Diag(Init->getExprLoc(),
1101 diag::err_init_element_not_constant, Init->getSourceRange());
1102 return true;
1103 }
1104 return false;
1105 }
1106 case Expr::BinaryOperatorClass: {
1107 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1108
1109 if (Exp->getLHS()->getType()->isArithmeticType() &&
1110 Exp->getRHS()->getType()->isArithmeticType()) {
1111 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1112 CheckArithmeticConstantExpression(Exp->getRHS());
1113 }
1114
Eli Friedman4caf0552008-06-09 05:05:07 +00001115 if (Exp->getLHS()->getType()->isPointerType() &&
1116 Exp->getRHS()->getType()->isPointerType()) {
1117 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1118 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1119
1120 // Only allow a null (constant integer) base; we could
1121 // allow some additional cases if necessary, but this
1122 // is sufficient to cover offsetof-like constructs.
1123 if (!LHSBase && !RHSBase) {
1124 return CheckAddressConstantExpression(Exp->getLHS()) ||
1125 CheckAddressConstantExpression(Exp->getRHS());
1126 }
1127 }
1128
Eli Friedmanc594b322008-05-20 13:48:25 +00001129 Diag(Init->getExprLoc(),
1130 diag::err_init_element_not_constant, Init->getSourceRange());
1131 return true;
1132 }
1133 case Expr::ImplicitCastExprClass:
1134 case Expr::CastExprClass: {
1135 const Expr *SubExpr;
1136 if (const CastExpr *C = dyn_cast<CastExpr>(Init)) {
1137 SubExpr = C->getSubExpr();
1138 } else {
1139 SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1140 }
1141
1142 if (SubExpr->getType()->isArithmeticType())
1143 return CheckArithmeticConstantExpression(SubExpr);
1144
1145 Diag(Init->getExprLoc(),
1146 diag::err_init_element_not_constant, Init->getSourceRange());
1147 return true;
1148 }
1149 case Expr::ConditionalOperatorClass: {
1150 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1151 if (CheckArithmeticConstantExpression(Exp->getCond()))
1152 return true;
1153 if (Exp->getLHS() &&
1154 CheckArithmeticConstantExpression(Exp->getLHS()))
1155 return true;
1156 return CheckArithmeticConstantExpression(Exp->getRHS());
1157 }
1158 }
1159}
1160
1161bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
1162 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1163 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1164 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1165
1166 if (Init->getType()->isReferenceType()) {
1167 // FIXME: Work out how the heck reference types work
1168 return false;
1169#if 0
1170 // A reference is constant if the address of the expression
1171 // is constant
1172 // We look through initlists here to simplify
1173 // CheckAddressConstantExpressionLValue.
1174 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1175 assert(Exp->getNumInits() > 0 &&
1176 "Refernce initializer cannot be empty");
1177 Init = Exp->getInit(0);
1178 }
1179 return CheckAddressConstantExpressionLValue(Init);
1180#endif
1181 }
1182
1183 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1184 unsigned numInits = Exp->getNumInits();
1185 for (unsigned i = 0; i < numInits; i++) {
1186 // FIXME: Need to get the type of the declaration for C++,
1187 // because it could be a reference?
1188 if (CheckForConstantInitializer(Exp->getInit(i),
1189 Exp->getInit(i)->getType()))
1190 return true;
1191 }
1192 return false;
1193 }
1194
1195 if (Init->isNullPointerConstant(Context))
1196 return false;
1197 if (Init->getType()->isArithmeticType()) {
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001198 QualType InitTy = Init->getType().getCanonicalType().getUnqualifiedType();
1199 if (InitTy == Context.BoolTy) {
1200 // Special handling for pointers implicitly cast to bool;
1201 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1202 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1203 Expr* SubE = ICE->getSubExpr();
1204 if (SubE->getType()->isPointerType() ||
1205 SubE->getType()->isArrayType() ||
1206 SubE->getType()->isFunctionType()) {
1207 return CheckAddressConstantExpression(Init);
1208 }
1209 }
1210 } else if (InitTy->isIntegralType()) {
1211 Expr* SubE = 0;
1212 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init))
1213 SubE = ICE->getSubExpr();
1214 else if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1215 SubE = CE->getSubExpr();
1216 // Special check for pointer cast to int; we allow as an extension
1217 // an address constant cast to an integer if the integer
1218 // is of an appropriate width (this sort of code is apparently used
1219 // in some places).
1220 // FIXME: Add pedwarn?
1221 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1222 if (SubE && (SubE->getType()->isPointerType() ||
1223 SubE->getType()->isArrayType() ||
1224 SubE->getType()->isFunctionType())) {
1225 unsigned IntWidth = Context.getTypeSize(Init->getType());
1226 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1227 if (IntWidth >= PointerWidth)
1228 return CheckAddressConstantExpression(Init);
1229 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001230 }
1231
1232 return CheckArithmeticConstantExpression(Init);
1233 }
1234
1235 if (Init->getType()->isPointerType())
1236 return CheckAddressConstantExpression(Init);
1237
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001238 // An array type at the top level that isn't an init-list must
1239 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001240 if (Init->getType()->isArrayType())
1241 return false;
1242
1243 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1244 Init->getSourceRange());
1245 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001246}
1247
Steve Naroffbb204692007-09-12 14:07:44 +00001248void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001249 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001250 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001251 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001252
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001253 // If there is no declaration, there was an error parsing it. Just ignore
1254 // the initializer.
1255 if (RealDecl == 0) {
1256 delete Init;
1257 return;
1258 }
Steve Naroffbb204692007-09-12 14:07:44 +00001259
Steve Naroff410e3e22007-09-12 20:13:48 +00001260 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1261 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001262 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1263 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001264 RealDecl->setInvalidDecl();
1265 return;
1266 }
Steve Naroffbb204692007-09-12 14:07:44 +00001267 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001268 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001269 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001270 if (VDecl->isBlockVarDecl()) {
1271 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001272 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001273 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001274 VDecl->setInvalidDecl();
1275 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +00001276 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001277 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001278 if (SC == VarDecl::Static) // C99 6.7.8p4.
1279 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001280 }
Steve Naroff248a7532008-04-15 22:42:06 +00001281 } else if (VDecl->isFileVarDecl()) {
1282 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001283 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001284 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001285 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001286 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001287
1288 // C99 6.7.8p4. All file scoped initializers need to be constant.
1289 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001290 }
1291 // If the type changed, it means we had an incomplete type that was
1292 // completed by the initializer. For example:
1293 // int ary[] = { 1, 3, 5 };
1294 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001295 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001296 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001297 Init->setType(DclT);
1298 }
Steve Naroffbb204692007-09-12 14:07:44 +00001299
1300 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001301 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001302 return;
1303}
1304
Reid Spencer5f016e22007-07-11 17:01:13 +00001305/// The declarators are chained together backwards, reverse the list.
1306Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1307 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001308 Decl *GroupDecl = static_cast<Decl*>(group);
1309 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001310 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001311
1312 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1313 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001314 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001315 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001316 else { // reverse the list.
1317 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001318 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001319 Group->setNextDeclarator(NewGroup);
1320 NewGroup = Group;
1321 Group = Next;
1322 }
1323 }
1324 // Perform semantic analysis that depends on having fully processed both
1325 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001326 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001327 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1328 if (!IDecl)
1329 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001330 QualType T = IDecl->getType();
1331
1332 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1333 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001334 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1335 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +00001336 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001337 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1338 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001339 }
1340 }
1341 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1342 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001343 if (IDecl->isBlockVarDecl() &&
1344 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001345 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001346 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1347 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001348 IDecl->setInvalidDecl();
1349 }
1350 }
1351 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1352 // object that has file scope without an initializer, and without a
1353 // storage-class specifier or with the storage-class specifier "static",
1354 // constitutes a tentative definition. Note: A tentative definition with
1355 // external linkage is valid (C99 6.2.2p5).
Steve Naroff248a7532008-04-15 22:42:06 +00001356 if (IDecl && !IDecl->getInit() &&
1357 (IDecl->getStorageClass() == VarDecl::Static ||
1358 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001359 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001360 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1361 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001362 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001363 // C99 6.9.2p3: If the declaration of an identifier for an object is
1364 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1365 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001366 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1367 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001368 IDecl->setInvalidDecl();
1369 }
1370 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 }
1372 return NewGroup;
1373}
Steve Naroffe1223f72007-08-28 03:03:08 +00001374
Chris Lattner04421082008-04-08 04:40:51 +00001375/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1376/// to introduce parameters into function prototype scope.
1377Sema::DeclTy *
1378Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1379 DeclSpec &DS = D.getDeclSpec();
1380
1381 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1382 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1383 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1384 Diag(DS.getStorageClassSpecLoc(),
1385 diag::err_invalid_storage_class_in_func_decl);
1386 DS.ClearStorageClassSpecs();
1387 }
1388 if (DS.isThreadSpecified()) {
1389 Diag(DS.getThreadSpecLoc(),
1390 diag::err_invalid_storage_class_in_func_decl);
1391 DS.ClearStorageClassSpecs();
1392 }
1393
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001394 // Check that there are no default arguments inside the type of this
1395 // parameter (C++ only).
1396 if (getLangOptions().CPlusPlus)
1397 CheckExtraCXXDefaultArguments(D);
1398
Chris Lattner04421082008-04-08 04:40:51 +00001399 // In this context, we *do not* check D.getInvalidType(). If the declarator
1400 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1401 // though it will not reflect the user specified type.
1402 QualType parmDeclType = GetTypeForDeclarator(D, S);
1403
1404 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1405
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1407 // Can this happen for params? We already checked that they don't conflict
1408 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001409 IdentifierInfo *II = D.getIdentifier();
1410 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1411 if (S->isDeclScope(PrevDecl)) {
1412 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1413 dyn_cast<NamedDecl>(PrevDecl)->getName());
1414
1415 // Recover by removing the name
1416 II = 0;
1417 D.SetIdentifier(0, D.getIdentifierLoc());
1418 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001419 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001420
1421 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1422 // Doing the promotion here has a win and a loss. The win is the type for
1423 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1424 // code generator). The loss is the orginal type isn't preserved. For example:
1425 //
1426 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1427 // int blockvardecl[5];
1428 // sizeof(parmvardecl); // size == 4
1429 // sizeof(blockvardecl); // size == 20
1430 // }
1431 //
1432 // For expressions, all implicit conversions are captured using the
1433 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1434 //
1435 // FIXME: If a source translation tool needs to see the original type, then
1436 // we need to consider storing both types (in ParmVarDecl)...
1437 //
Chris Lattnere6327742008-04-02 05:18:44 +00001438 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001439 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001440 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001441 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001442 parmDeclType = Context.getPointerType(parmDeclType);
1443
Chris Lattner04421082008-04-08 04:40:51 +00001444 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1445 D.getIdentifierLoc(), II,
1446 parmDeclType, VarDecl::None,
1447 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001448
Chris Lattner04421082008-04-08 04:40:51 +00001449 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001450 New->setInvalidDecl();
1451
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001452 if (II)
1453 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001454
Nate Begemanfc584522008-05-09 16:56:01 +00001455 HandleDeclAttributes(New, D.getDeclSpec().getAttributes(),
1456 D.getAttributes());
Reid Spencer5f016e22007-07-11 17:01:13 +00001457 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001458
Reid Spencer5f016e22007-07-11 17:01:13 +00001459}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001460
Chris Lattnerb652cea2007-10-09 17:14:05 +00001461Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001462 assert(CurFunctionDecl == 0 && "Function parsing confused");
1463 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1464 "Not a function declarator!");
1465 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001466
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1468 // for a K&R function.
1469 if (!FTI.hasPrototype) {
1470 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001471 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1473 FTI.ArgInfo[i].Ident->getName());
1474 // Implicitly declare the argument as type 'int' for lack of a better
1475 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001476 DeclSpec DS;
1477 const char* PrevSpec; // unused
1478 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1479 PrevSpec);
1480 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1481 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1482 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 }
1484 }
Chris Lattner52804082008-02-17 19:31:09 +00001485
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 // Since this is a function definition, act as though we have information
1487 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001488 if (FTI.NumArgs)
1489 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001491 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 }
1493
1494 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001495
1496 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001497 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001498 GlobalScope);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001499 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1500 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1501 const FunctionDecl *Definition;
1502 if (FD->getBody(Definition)) {
1503 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1504 D.getIdentifier()->getName());
1505 Diag(Definition->getLocation(), diag::err_previous_definition);
1506 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001507 }
1508 }
Steve Narofffabbc342008-02-12 01:09:36 +00001509 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001510 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001511 CurFunctionDecl = FD;
Chris Lattnerb048c982008-04-06 04:47:34 +00001512 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001513
1514 // Check the validity of our function parameters
1515 CheckParmsForFunctionDef(FD);
1516
1517 // Introduce our parameters into the function scope
1518 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1519 ParmVarDecl *Param = FD->getParamDecl(p);
1520 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001521 if (Param->getIdentifier())
1522 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 }
Chris Lattner04421082008-04-08 04:40:51 +00001524
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 return FD;
1526}
1527
Steve Naroffd6d054d2007-11-11 23:20:51 +00001528Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1529 Decl *dcl = static_cast<Decl *>(D);
1530 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1531 FD->setBody((Stmt*)Body);
1532 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001533 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001534 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001535 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001536 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001537 }
Chris Lattnerb048c982008-04-06 04:47:34 +00001538 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 // Verify and clean out per-function state.
1540
1541 // Check goto/label use.
1542 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1543 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1544 // Verify that we have no forward references left. If so, there was a goto
1545 // or address of a label taken, but no definition of it. Label fwd
1546 // definitions are indicated with a null substmt.
1547 if (I->second->getSubStmt() == 0) {
1548 LabelStmt *L = I->second;
1549 // Emit error.
1550 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1551
1552 // At this point, we have gotos that use the bogus label. Stitch it into
1553 // the function body so that they aren't leaked and that the AST is well
1554 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001555 if (Body) {
1556 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1557 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1558 } else {
1559 // The whole function wasn't parsed correctly, just delete this.
1560 delete L;
1561 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 }
1563 }
1564 LabelMap.clear();
1565
Steve Naroffd6d054d2007-11-11 23:20:51 +00001566 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001567}
1568
Reid Spencer5f016e22007-07-11 17:01:13 +00001569/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1570/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001571ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1572 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001573 // Extension in C99. Legal in C90, but warn about it.
1574 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001576 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1578
1579 // FIXME: handle stuff like:
1580 // void foo() { extern float X(); }
1581 // void bar() { X(); } <-- implicit decl for X in another scope.
1582
1583 // Set a Declarator for the implicit definition: int foo();
1584 const char *Dummy;
1585 DeclSpec DS;
1586 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1587 Error = Error; // Silence warning.
1588 assert(!Error && "Error setting up implicit decl!");
1589 Declarator D(DS, Declarator::BlockContext);
1590 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1591 D.SetIdentifier(&II, Loc);
1592
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001593 // Insert this function into translation-unit scope.
1594
1595 DeclContext *PrevDC = CurContext;
1596 CurContext = Context.getTranslationUnitDecl();
1597
Steve Naroffe2ef8152008-04-04 14:32:09 +00001598 FunctionDecl *FD =
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001599 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001600 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001601
1602 CurContext = PrevDC;
1603
Steve Naroffe2ef8152008-04-04 14:32:09 +00001604 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001605}
1606
1607
Chris Lattner41af0932007-11-14 06:34:38 +00001608TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001609 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001611 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001612
1613 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001614 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1615 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001616 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001617 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001618 if (D.getInvalidType())
1619 NewTD->setInvalidDecl();
1620 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001621}
1622
Steve Naroff08d92e42007-09-15 18:49:24 +00001623/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001624/// former case, Name will be non-null. In the later case, Name will be null.
1625/// TagType indicates what kind of tag this is. TK indicates whether this is a
1626/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001627Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 SourceLocation KWLoc, IdentifierInfo *Name,
1629 SourceLocation NameLoc, AttributeList *Attr) {
1630 // If this is a use of an existing tag, it must have a name.
1631 assert((Name != 0 || TK == TK_Definition) &&
1632 "Nameless record must be a definition!");
1633
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001634 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 switch (TagType) {
1636 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001637 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1638 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1639 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1640 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 }
1642
1643 // If this is a named struct, check to see if there was a previous forward
1644 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001645 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1646 if (ScopedDecl *PrevDecl =
1647 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001648
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001649 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1650 "unexpected Decl type");
1651 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1652 // If this is a use of a previous tag, or if the tag is already declared in
1653 // the same scope (so that the definition/declaration completes or
1654 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001655 if (TK == TK_Reference ||
1656 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001657 // Make sure that this wasn't declared as an enum and now used as a struct
1658 // or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001659 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001660 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1661 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1662 }
1663
1664 // If this is a use or a forward declaration, we're good.
1665 if (TK != TK_Definition)
1666 return PrevDecl;
Reid Spencer5f016e22007-07-11 17:01:13 +00001667
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001668 // Diagnose attempts to redefine a tag.
1669 if (PrevTagDecl->isDefinition()) {
1670 Diag(NameLoc, diag::err_redefinition, Name->getName());
1671 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1672 // If this is a redefinition, recover by making this struct be
1673 // anonymous, which will make any later references get the previous
1674 // definition.
1675 Name = 0;
1676 } else {
1677 // Okay, this is definition of a previously declared or referenced tag.
1678 // Move the location of the decl to be the definition site.
1679 PrevDecl->setLocation(NameLoc);
1680 return PrevDecl;
1681 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001683 // If we get here, this is a definition of a new struct type in a nested
1684 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1685 // type.
1686 } else {
1687 // The tag name clashes with a namespace name, issue an error and recover
1688 // by making this tag be anonymous.
1689 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1690 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1691 Name = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001693 }
1694
1695 // If there is an identifier, use the location of the identifier as the
1696 // location of the decl, otherwise use the location of the struct/union
1697 // keyword.
1698 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1699
1700 // Otherwise, if this is the first time we've seen this tag, create the decl.
1701 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001702 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1704 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001705 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 // If this is an undefined enum, warn.
1707 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001708 } else {
1709 // struct/union/class
1710
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1712 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001713 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001714 }
1715
1716 // If this has an identifier, add it to the scope stack.
1717 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001718 // The scope passed in may not be a decl scope. Zip up the scope tree until
1719 // we find one that is.
1720 while ((S->getFlags() & Scope::DeclScope) == 0)
1721 S = S->getParent();
1722
1723 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001724 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001726
Anders Carlssonad148062008-02-16 00:29:18 +00001727 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 return New;
1729}
1730
Eli Friedman1b76ada2008-06-03 21:01:11 +00001731static bool CalcFakeICEVal(const Expr* Expr,
1732 llvm::APSInt& Result,
1733 ASTContext& Context) {
1734 // Calculate the value of an expression that has a calculatable
1735 // value, but isn't an ICE. Currently, this only supports
1736 // a very narrow set of extensions, but it can be expanded if needed.
1737 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Expr))
1738 return CalcFakeICEVal(PE->getSubExpr(), Result, Context);
1739
1740 if (const CastExpr *CE = dyn_cast<CastExpr>(Expr)) {
1741 QualType CETy = CE->getType();
1742 if ((CETy->isIntegralType() && !CETy->isBooleanType()) ||
1743 CETy->isPointerType()) {
1744 if (CalcFakeICEVal(CE->getSubExpr(), Result, Context)) {
1745 Result.extOrTrunc(Context.getTypeSize(CETy));
1746 // FIXME: This assumes pointers are signed.
1747 Result.setIsSigned(CETy->isSignedIntegerType() ||
1748 CETy->isPointerType());
1749 return true;
1750 }
1751 }
1752 }
1753
1754 if (Expr->getType()->isIntegralType())
1755 return Expr->isIntegerConstantExpr(Result, Context);
1756
1757 return false;
1758}
1759
1760QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1761 // This method tries to turn a variable array into a constant
1762 // array even when the size isn't an ICE. This is necessary
1763 // for compatibility with code that depends on gcc's buggy
1764 // constant expression folding, like struct {char x[(int)(char*)2];}
1765 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
1766 llvm::APSInt Result(32);
1767 if (VLATy->getSizeExpr() &&
1768 CalcFakeICEVal(VLATy->getSizeExpr(), Result, Context) &&
1769 Result > llvm::APSInt(Result.getBitWidth(), Result.isUnsigned())) {
1770 return Context.getConstantArrayType(VLATy->getElementType(),
1771 Result, ArrayType::Normal, 0);
1772 }
1773 }
1774 return QualType();
1775}
1776
Steve Naroff08d92e42007-09-15 18:49:24 +00001777/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001778/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001779Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 SourceLocation DeclStart,
1781 Declarator &D, ExprTy *BitfieldWidth) {
1782 IdentifierInfo *II = D.getIdentifier();
1783 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001784 SourceLocation Loc = DeclStart;
1785 if (II) Loc = D.getIdentifierLoc();
1786
1787 // FIXME: Unnamed fields can be handled in various different ways, for
1788 // example, unnamed unions inject all members into the struct namespace!
1789
1790
1791 if (BitWidth) {
1792 // TODO: Validate.
1793 //printf("WARNING: BITFIELDS IGNORED!\n");
1794
1795 // 6.7.2.1p3
1796 // 6.7.2.1p4
1797
1798 } else {
1799 // Not a bitfield.
1800
1801 // validate II.
1802
1803 }
1804
1805 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001806 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1807 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001808
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1810 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001811 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00001812 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1813 if (!FixedTy.isNull()) {
1814 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1815 T = FixedTy;
1816 } else {
1817 // FIXME: This diagnostic needs work
1818 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1819 InvalidDecl = true;
1820 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001821 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001822 // FIXME: Chain fielddecls together.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001823 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001824
Anders Carlssonad148062008-02-16 00:29:18 +00001825 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1826 D.getAttributes());
1827
Steve Naroff5912a352007-08-28 20:14:24 +00001828 if (D.getInvalidType() || InvalidDecl)
1829 NewFD->setInvalidDecl();
1830 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001831}
1832
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001833/// TranslateIvarVisibility - Translate visibility from a token ID to an
1834/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001835static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001836TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001837 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001838 case tok::objc_private: return ObjCIvarDecl::Private;
1839 case tok::objc_public: return ObjCIvarDecl::Public;
1840 case tok::objc_protected: return ObjCIvarDecl::Protected;
1841 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001842 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001843 }
1844}
1845
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001846/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1847/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001848Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001849 SourceLocation DeclStart,
1850 Declarator &D, ExprTy *BitfieldWidth,
1851 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001852 IdentifierInfo *II = D.getIdentifier();
1853 Expr *BitWidth = (Expr*)BitfieldWidth;
1854 SourceLocation Loc = DeclStart;
1855 if (II) Loc = D.getIdentifierLoc();
1856
1857 // FIXME: Unnamed fields can be handled in various different ways, for
1858 // example, unnamed unions inject all members into the struct namespace!
1859
1860
1861 if (BitWidth) {
1862 // TODO: Validate.
1863 //printf("WARNING: BITFIELDS IGNORED!\n");
1864
1865 // 6.7.2.1p3
1866 // 6.7.2.1p4
1867
1868 } else {
1869 // Not a bitfield.
1870
1871 // validate II.
1872
1873 }
1874
1875 QualType T = GetTypeForDeclarator(D, S);
1876 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1877 bool InvalidDecl = false;
1878
1879 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1880 // than a variably modified type.
1881 if (T->isVariablyModifiedType()) {
1882 // FIXME: This diagnostic needs work
1883 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1884 InvalidDecl = true;
1885 }
1886
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001887 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001888
1889 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1890 D.getAttributes());
1891
1892 if (D.getInvalidType() || InvalidDecl)
1893 NewID->setInvalidDecl();
1894 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001895 if (Visibility != tok::objc_not_keyword)
1896 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001897 return NewID;
1898}
1899
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001900void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001901 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001902 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001903 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001904 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1905 assert(EnclosingDecl && "missing record or interface decl");
1906 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1907
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001908 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 // Diagnose code like:
1910 // struct S { struct S {} X; };
1911 // We discover this when we complete the outer S. Reject and ignore the
1912 // outer S.
1913 Diag(Record->getLocation(), diag::err_nested_redefinition,
1914 Record->getKindName());
1915 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001916 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001917 return;
1918 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 // Verify that all the fields are okay.
1920 unsigned NumNamedMembers = 0;
1921 llvm::SmallVector<FieldDecl*, 32> RecFields;
1922 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001923
Reid Spencer5f016e22007-07-11 17:01:13 +00001924 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001925
Steve Naroff74216642007-09-14 22:20:54 +00001926 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1927 assert(FD && "missing field decl");
1928
1929 // Remember all fields.
1930 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001931
1932 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001933 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00001934
Reid Spencer5f016e22007-07-11 17:01:13 +00001935 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001936 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001937 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001938 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001939 FD->setInvalidDecl();
1940 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 continue;
1942 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1944 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001945 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001946 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001947 FD->setInvalidDecl();
1948 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001949 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001950 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001951 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001952 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001953 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001954 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001955 FD->setInvalidDecl();
1956 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001957 continue;
1958 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001959 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001960 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1961 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001962 FD->setInvalidDecl();
1963 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 continue;
1965 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001966 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001967 if (Record)
1968 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001969 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001970 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1971 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001972 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001973 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1974 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001975 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001976 Record->setHasFlexibleArrayMember(true);
1977 } else {
1978 // If this is a struct/class and this is not the last element, reject
1979 // it. Note that GCC supports variable sized arrays in the middle of
1980 // structures.
1981 if (i != NumFields-1) {
1982 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1983 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001984 FD->setInvalidDecl();
1985 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001986 continue;
1987 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 // We support flexible arrays at the end of structs in other structs
1989 // as an extension.
1990 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1991 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001992 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001993 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001994 }
1995 }
1996 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001997 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001998 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001999 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2000 FD->getName());
2001 FD->setInvalidDecl();
2002 EnclosingDecl->setInvalidDecl();
2003 continue;
2004 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002005 // Keep track of the number of named members.
2006 if (IdentifierInfo *II = FD->getIdentifier()) {
2007 // Detect duplicate member names.
2008 if (!FieldIDs.insert(II)) {
2009 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2010 // Find the previous decl.
2011 SourceLocation PrevLoc;
2012 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2013 assert(i != e && "Didn't find previous def!");
2014 if (RecFields[i]->getIdentifier() == II) {
2015 PrevLoc = RecFields[i]->getLocation();
2016 break;
2017 }
2018 }
2019 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002020 FD->setInvalidDecl();
2021 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002022 continue;
2023 }
2024 ++NumNamedMembers;
2025 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 }
2027
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002029 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002030 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00002031 Consumer.HandleTagDeclDefinition(Record);
2032 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002033 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2034 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2035 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2036 else if (ObjCImplementationDecl *IMPDecl =
2037 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002038 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2039 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002040 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002041 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002042 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002043}
2044
Steve Naroff08d92e42007-09-15 18:49:24 +00002045Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002046 DeclTy *lastEnumConst,
2047 SourceLocation IdLoc, IdentifierInfo *Id,
2048 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002049 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002050 EnumConstantDecl *LastEnumConst =
2051 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2052 Expr *Val = static_cast<Expr*>(val);
2053
Chris Lattner31e05722007-08-26 06:24:45 +00002054 // The scope passed in may not be a decl scope. Zip up the scope tree until
2055 // we find one that is.
2056 while ((S->getFlags() & Scope::DeclScope) == 0)
2057 S = S->getParent();
2058
Reid Spencer5f016e22007-07-11 17:01:13 +00002059 // Verify that there isn't already something declared with this name in this
2060 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002061 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00002062 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002063 if (isa<EnumConstantDecl>(PrevDecl))
2064 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2065 else
2066 Diag(IdLoc, diag::err_redefinition, Id->getName());
2067 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002068 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002069 return 0;
2070 }
2071 }
2072
2073 llvm::APSInt EnumVal(32);
2074 QualType EltTy;
2075 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002076 // Make sure to promote the operand type to int.
2077 UsualUnaryConversions(Val);
2078
Reid Spencer5f016e22007-07-11 17:01:13 +00002079 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2080 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002081 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002082 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2083 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002084 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002085 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002086 } else {
2087 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002089 }
2090
2091 if (!Val) {
2092 if (LastEnumConst) {
2093 // Assign the last value + 1.
2094 EnumVal = LastEnumConst->getInitVal();
2095 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002096
2097 // Check for overflow on increment.
2098 if (EnumVal < LastEnumConst->getInitVal())
2099 Diag(IdLoc, diag::warn_enum_value_overflow);
2100
Chris Lattnerb7416f92007-08-27 17:37:24 +00002101 EltTy = LastEnumConst->getType();
2102 } else {
2103 // First value, set to zero.
2104 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002105 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002106 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002107 }
2108
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002109 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002110 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2111 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002112 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002113
2114 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002115 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002116 return New;
2117}
2118
Steve Naroff08d92e42007-09-15 18:49:24 +00002119void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 DeclTy **Elements, unsigned NumElements) {
2121 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
2122 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
2123
Chris Lattnere37f0be2007-08-28 05:10:31 +00002124 // TODO: If the result value doesn't fit in an int, it must be a long or long
2125 // long value. ISO C does not support this, but GCC does as an extension,
2126 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002127 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002128
Chris Lattnerac609682007-08-28 06:15:15 +00002129 // Verify that all the values are okay, compute the size of the values, and
2130 // reverse the list.
2131 unsigned NumNegativeBits = 0;
2132 unsigned NumPositiveBits = 0;
2133
2134 // Keep track of whether all elements have type int.
2135 bool AllElementsInt = true;
2136
Reid Spencer5f016e22007-07-11 17:01:13 +00002137 EnumConstantDecl *EltList = 0;
2138 for (unsigned i = 0; i != NumElements; ++i) {
2139 EnumConstantDecl *ECD =
2140 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2141 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002142
2143 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002144 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002145 assert(InitVal.getBitWidth() >= IntWidth &&
2146 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002147 if (InitVal.getBitWidth() > IntWidth) {
2148 llvm::APSInt V(InitVal);
2149 V.trunc(IntWidth);
2150 V.extend(InitVal.getBitWidth());
2151 if (V != InitVal)
2152 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2153 InitVal.toString());
2154 }
Chris Lattnerac609682007-08-28 06:15:15 +00002155
2156 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002157 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002158 NumPositiveBits = std::max(NumPositiveBits,
2159 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002160 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002161 NumNegativeBits = std::max(NumNegativeBits,
2162 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002163
Chris Lattnerac609682007-08-28 06:15:15 +00002164 // Keep track of whether every enum element has type int (very commmon).
2165 if (AllElementsInt)
2166 AllElementsInt = ECD->getType() == Context.IntTy;
2167
Reid Spencer5f016e22007-07-11 17:01:13 +00002168 ECD->setNextDeclarator(EltList);
2169 EltList = ECD;
2170 }
2171
Chris Lattnerac609682007-08-28 06:15:15 +00002172 // Figure out the type that should be used for this enum.
2173 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2174 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002175 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002176
2177 if (NumNegativeBits) {
2178 // If there is a negative value, figure out the smallest integer type (of
2179 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002180 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002181 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002182 BestWidth = IntWidth;
2183 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002184 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002185
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002186 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002187 BestType = Context.LongTy;
2188 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002189 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002190
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002191 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002192 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2193 BestType = Context.LongLongTy;
2194 }
2195 }
2196 } else {
2197 // If there is no negative value, figure out which of uint, ulong, ulonglong
2198 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002199 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002200 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002201 BestWidth = IntWidth;
2202 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002203 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002204 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002205 } else {
2206 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002207 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002208 "How could an initializer get larger than ULL?");
2209 BestType = Context.UnsignedLongLongTy;
2210 }
2211 }
2212
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002213 // Loop over all of the enumerator constants, changing their types to match
2214 // the type of the enum if needed.
2215 for (unsigned i = 0; i != NumElements; ++i) {
2216 EnumConstantDecl *ECD =
2217 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2218 if (!ECD) continue; // Already issued a diagnostic.
2219
2220 // Standard C says the enumerators have int type, but we allow, as an
2221 // extension, the enumerators to be larger than int size. If each
2222 // enumerator value fits in an int, type it as an int, otherwise type it the
2223 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2224 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002225 if (ECD->getType() == Context.IntTy) {
2226 // Make sure the init value is signed.
2227 llvm::APSInt IV = ECD->getInitVal();
2228 IV.setIsSigned(true);
2229 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002230 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002231 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002232
2233 // Determine whether the value fits into an int.
2234 llvm::APSInt InitVal = ECD->getInitVal();
2235 bool FitsInInt;
2236 if (InitVal.isUnsigned() || !InitVal.isNegative())
2237 FitsInInt = InitVal.getActiveBits() < IntWidth;
2238 else
2239 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2240
2241 // If it fits into an integer type, force it. Otherwise force it to match
2242 // the enum decl type.
2243 QualType NewTy;
2244 unsigned NewWidth;
2245 bool NewSign;
2246 if (FitsInInt) {
2247 NewTy = Context.IntTy;
2248 NewWidth = IntWidth;
2249 NewSign = true;
2250 } else if (ECD->getType() == BestType) {
2251 // Already the right type!
2252 continue;
2253 } else {
2254 NewTy = BestType;
2255 NewWidth = BestWidth;
2256 NewSign = BestType->isSignedIntegerType();
2257 }
2258
2259 // Adjust the APSInt value.
2260 InitVal.extOrTrunc(NewWidth);
2261 InitVal.setIsSigned(NewSign);
2262 ECD->setInitVal(InitVal);
2263
2264 // Adjust the Expr initializer and type.
2265 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2266 ECD->setType(NewTy);
2267 }
Chris Lattnerac609682007-08-28 06:15:15 +00002268
Chris Lattnere00b18c2007-08-28 18:24:31 +00002269 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002270 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002271}
2272
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002273Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2274 ExprTy *expr) {
2275 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2276
Chris Lattner8e25d862008-03-16 00:16:02 +00002277 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002278}
2279
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002280Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002281 SourceLocation LBrace,
2282 SourceLocation RBrace,
2283 const char *Lang,
2284 unsigned StrSize,
2285 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002286 LinkageSpecDecl::LanguageIDs Language;
2287 Decl *dcl = static_cast<Decl *>(D);
2288 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2289 Language = LinkageSpecDecl::lang_c;
2290 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2291 Language = LinkageSpecDecl::lang_cxx;
2292 else {
2293 Diag(Loc, diag::err_bad_language);
2294 return 0;
2295 }
2296
2297 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002298 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002299}
2300
Chris Lattner74788ba2008-02-21 00:48:22 +00002301void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00002302
Chris Lattner74788ba2008-02-21 00:48:22 +00002303 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00002304 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00002305 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00002306 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002307 if (!newType.isNull()) // install the new vector type into the decl
2308 vDecl->setType(newType);
2309 }
2310 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2311 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00002312 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002313 if (!newType.isNull()) // install the new vector type into the decl
2314 tDecl->setUnderlyingType(newType);
2315 }
Chris Lattner212839c2008-02-20 23:17:35 +00002316 break;
Nate Begeman213541a2008-04-18 23:10:10 +00002317 case AttributeList::AT_ext_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00002318 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Nate Begeman213541a2008-04-18 23:10:10 +00002319 HandleExtVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00002320 else
Chris Lattner74788ba2008-02-21 00:48:22 +00002321 Diag(Attr->getLoc(),
Nate Begeman213541a2008-04-18 23:10:10 +00002322 diag::err_typecheck_ext_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00002323 break;
2324 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00002325 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2326 QualType newType = HandleAddressSpaceTypeAttribute(
2327 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00002328 Attr);
2329 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00002330 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2331 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00002332 Attr);
2333 // install the new addr spaced type into the decl
2334 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00002335 }
Chris Lattner212839c2008-02-20 23:17:35 +00002336 break;
Eli Friedman3c0eb162008-05-27 03:33:27 +00002337 case AttributeList::AT_mode:
2338 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2339 QualType newType = HandleModeTypeAttribute(tDecl->getUnderlyingType(),
2340 Attr);
2341 tDecl->setUnderlyingType(newType);
2342 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2343 QualType newType = HandleModeTypeAttribute(vDecl->getType(), Attr);
2344 vDecl->setType(newType);
2345 }
2346 // FIXME: Diagnostic?
2347 break;
Nuno Lopesd4cbda62008-06-08 15:45:52 +00002348 case AttributeList::AT_alias:
2349 HandleAliasAttribute(New, Attr);
2350 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00002351 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00002352 HandleDeprecatedAttribute(New, Attr);
2353 break;
2354 case AttributeList::AT_visibility:
2355 HandleVisibilityAttribute(New, Attr);
2356 break;
2357 case AttributeList::AT_weak:
2358 HandleWeakAttribute(New, Attr);
2359 break;
2360 case AttributeList::AT_dllimport:
2361 HandleDLLImportAttribute(New, Attr);
2362 break;
2363 case AttributeList::AT_dllexport:
2364 HandleDLLExportAttribute(New, Attr);
2365 break;
2366 case AttributeList::AT_nothrow:
2367 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00002368 break;
Nate Begeman440b4562008-03-07 20:04:22 +00002369 case AttributeList::AT_stdcall:
2370 HandleStdCallAttribute(New, Attr);
2371 break;
2372 case AttributeList::AT_fastcall:
2373 HandleFastCallAttribute(New, Attr);
2374 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002375 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00002376 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002377 break;
2378 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00002379 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002380 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00002381 case AttributeList::AT_annotate:
2382 HandleAnnotateAttribute(New, Attr);
2383 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00002384 case AttributeList::AT_noreturn:
2385 HandleNoReturnAttribute(New, Attr);
2386 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00002387 case AttributeList::AT_format:
2388 HandleFormatAttribute(New, Attr);
2389 break;
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002390 case AttributeList::AT_transparent_union:
2391 HandleTransparentUnionAttribute(New, Attr);
2392 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002393 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00002394#if 0
2395 // TODO: when we have the full set of attributes, warn about unknown ones.
2396 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
2397 Attr->getName()->getName());
2398#endif
Chris Lattner212839c2008-02-20 23:17:35 +00002399 break;
2400 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002401}
2402
2403void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2404 AttributeList *declarator_postfix) {
2405 while (declspec_prefix) {
2406 HandleDeclAttribute(New, declspec_prefix);
2407 declspec_prefix = declspec_prefix->getNext();
2408 }
2409 while (declarator_postfix) {
2410 HandleDeclAttribute(New, declarator_postfix);
2411 declarator_postfix = declarator_postfix->getNext();
2412 }
2413}
2414
Nate Begeman213541a2008-04-18 23:10:10 +00002415void Sema::HandleExtVectorTypeAttribute(TypedefDecl *tDecl,
Steve Naroffbea0b342007-07-29 16:33:31 +00002416 AttributeList *rawAttr) {
2417 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00002418 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00002419 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002420 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00002421 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002422 return;
Steve Naroff73322922007-07-18 18:00:27 +00002423 }
2424 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2425 llvm::APSInt vecSize(32);
2426 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002427 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Nate Begeman213541a2008-04-18 23:10:10 +00002428 "ext_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002429 return;
Steve Naroff73322922007-07-18 18:00:27 +00002430 }
2431 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2432 // in conjunction with complex types (pointers, arrays, functions, etc.).
2433 Type *canonType = curType.getCanonicalType().getTypePtr();
2434 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002435 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00002436 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002437 return;
Steve Naroff73322922007-07-18 18:00:27 +00002438 }
2439 // unlike gcc's vector_size attribute, the size is specified as the
2440 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002441 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002442
2443 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002444 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00002445 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002446 return;
Steve Naroff73322922007-07-18 18:00:27 +00002447 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002448 // Instantiate/Install the vector type, the number of elements is > 0.
Nate Begeman213541a2008-04-18 23:10:10 +00002449 tDecl->setUnderlyingType(Context.getExtVectorType(curType, vectorSize));
Steve Naroffbea0b342007-07-29 16:33:31 +00002450 // Remember this typedef decl, we will need it later for diagnostics.
Nate Begeman213541a2008-04-18 23:10:10 +00002451 ExtVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002452}
2453
Reid Spencer5f016e22007-07-11 17:01:13 +00002454QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002455 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002456 // check the attribute arugments.
2457 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002458 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00002459 std::string("1"));
2460 return QualType();
2461 }
2462 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2463 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002464 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002465 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002466 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002467 return QualType();
2468 }
2469 // navigate to the base type - we need to provide for vector pointers,
2470 // vector arrays, and functions returning vectors.
2471 Type *canonType = curType.getCanonicalType().getTypePtr();
2472
Steve Naroff73322922007-07-18 18:00:27 +00002473 if (canonType->isPointerType() || canonType->isArrayType() ||
2474 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00002475 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00002476 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2477 do {
2478 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2479 canonType = PT->getPointeeType().getTypePtr();
2480 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2481 canonType = AT->getElementType().getTypePtr();
2482 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2483 canonType = FT->getResultType().getTypePtr();
2484 } while (canonType->isPointerType() || canonType->isArrayType() ||
2485 canonType->isFunctionType());
2486 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 }
2488 // the base type must be integer or float.
2489 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002490 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00002491 curType.getCanonicalType().getAsString());
2492 return QualType();
2493 }
Chris Lattner98be4942008-03-05 18:54:05 +00002494 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00002495 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002496 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002497
2498 // the vector size needs to be an integral multiple of the type size.
2499 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00002500 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002501 sizeExpr->getSourceRange());
2502 return QualType();
2503 }
2504 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002505 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002506 sizeExpr->getSourceRange());
2507 return QualType();
2508 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00002509 // Instantiate the vector type, the number of elements is > 0, and not
2510 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00002511 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002512}
2513
Chris Lattner2070d802008-02-20 23:25:22 +00002514void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00002515 // check the attribute arguments.
2516 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002517 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00002518 std::string("0"));
2519 return;
2520 }
2521
2522 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2523 TD->addAttr(new PackedAttr);
2524 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2525 // If the alignment is less than or equal to 8 bits, the packed attribute
2526 // has no effect.
Chris Lattnerabb57582008-05-09 05:34:49 +00002527 if (!FD->getType()->isIncompleteType() &&
2528 Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002529 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002530 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002531 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002532 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002533 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002534 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002535 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2536 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002537}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002538
Nuno Lopesd4cbda62008-06-08 15:45:52 +00002539void Sema::HandleAliasAttribute(Decl *d, AttributeList *rawAttr) {
2540 // check the attribute arguments.
2541 if (rawAttr->getNumArgs() != 1) {
2542 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2543 std::string("1"));
2544 return;
2545 }
2546
2547 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2548 Arg = Arg->IgnoreParenCasts();
2549 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2550
2551 if (Str == 0 || Str->isWide()) {
2552 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2553 "alias", std::string("1"));
2554 return;
2555 }
2556
2557 const char *Alias = Str->getStrData();
2558 unsigned AliasLen = Str->getByteLength();
2559
2560 // FIXME: check if target symbol exists in current file
2561
2562 d->addAttr(new AliasAttr(std::string(Alias, AliasLen)));
2563}
2564
Ted Kremenekaecb3832008-02-27 20:43:06 +00002565void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2566 // check the attribute arguments.
2567 if (rawAttr->getNumArgs() != 0) {
2568 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2569 std::string("0"));
2570 return;
2571 }
2572
Ted Kremenek3465fb32008-03-03 16:52:27 +00002573 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2574
2575 if (!Fn) {
2576 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2577 "noreturn", "function");
2578 return;
2579 }
2580
Ted Kremenekaecb3832008-02-27 20:43:06 +00002581 d->addAttr(new NoReturnAttr());
2582}
2583
Chris Lattnerddee4232008-03-03 03:28:21 +00002584void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2585 // check the attribute arguments.
2586 if (rawAttr->getNumArgs() != 0) {
2587 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2588 std::string("0"));
2589 return;
2590 }
2591
2592 d->addAttr(new DeprecatedAttr());
2593}
2594
2595void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2596 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002597 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002598 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2599 std::string("1"));
2600 return;
2601 }
2602
Chris Lattner7b937ae2008-03-04 18:08:48 +00002603 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2604 Arg = Arg->IgnoreParenCasts();
2605 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2606
2607 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002608 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002609 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002610 return;
2611 }
2612
Chris Lattner7b937ae2008-03-04 18:08:48 +00002613 const char *TypeStr = Str->getStrData();
2614 unsigned TypeLen = Str->getByteLength();
Dan Gohman4f8d1232008-05-22 00:50:06 +00002615 VisibilityAttr::VisibilityTypes type;
Chris Lattnerddee4232008-03-03 03:28:21 +00002616
Chris Lattner7b937ae2008-03-04 18:08:48 +00002617 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002618 type = VisibilityAttr::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002619 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002620 type = VisibilityAttr::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002621 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002622 type = VisibilityAttr::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002623 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002624 type = VisibilityAttr::ProtectedVisibility;
Chris Lattnerddee4232008-03-03 03:28:21 +00002625 else {
2626 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002627 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002628 return;
2629 }
2630
2631 d->addAttr(new VisibilityAttr(type));
2632}
2633
2634void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2635 // check the attribute arguments.
2636 if (rawAttr->getNumArgs() != 0) {
2637 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2638 std::string("0"));
2639 return;
2640 }
2641
2642 d->addAttr(new WeakAttr());
2643}
2644
2645void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2646 // check the attribute arguments.
2647 if (rawAttr->getNumArgs() != 0) {
2648 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2649 std::string("0"));
2650 return;
2651 }
2652
2653 d->addAttr(new DLLImportAttr());
2654}
2655
2656void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2657 // check the attribute arguments.
2658 if (rawAttr->getNumArgs() != 0) {
2659 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2660 std::string("0"));
2661 return;
2662 }
2663
2664 d->addAttr(new DLLExportAttr());
2665}
2666
Nate Begeman440b4562008-03-07 20:04:22 +00002667void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2668 // check the attribute arguments.
2669 if (rawAttr->getNumArgs() != 0) {
2670 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2671 std::string("0"));
2672 return;
2673 }
2674
2675 d->addAttr(new StdCallAttr());
2676}
2677
2678void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2679 // check the attribute arguments.
2680 if (rawAttr->getNumArgs() != 0) {
2681 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2682 std::string("0"));
2683 return;
2684 }
2685
2686 d->addAttr(new FastCallAttr());
2687}
2688
Chris Lattnerddee4232008-03-03 03:28:21 +00002689void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2690 // check the attribute arguments.
2691 if (rawAttr->getNumArgs() != 0) {
2692 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2693 std::string("0"));
2694 return;
2695 }
2696
2697 d->addAttr(new NoThrowAttr());
2698}
2699
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002700static const FunctionTypeProto *getFunctionProto(Decl *d) {
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002701 QualType Ty;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002702
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002703 if (ValueDecl *decl = dyn_cast<ValueDecl>(d))
2704 Ty = decl->getType();
2705 else if (FieldDecl *decl = dyn_cast<FieldDecl>(d))
2706 Ty = decl->getType();
Ted Kremenek72786e02008-05-09 17:36:24 +00002707 else if (TypedefDecl* decl = dyn_cast<TypedefDecl>(d))
2708 Ty = decl->getUnderlyingType();
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002709 else
2710 return 0;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002711
2712 if (Ty->isFunctionPointerType()) {
2713 const PointerType *PtrTy = Ty->getAsPointerType();
2714 Ty = PtrTy->getPointeeType();
2715 }
2716
2717 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2718 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2719
2720 return 0;
2721}
2722
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002723static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
2724 if (!T->isPointerType())
2725 return false;
2726
2727 T = T->getAsPointerType()->getPointeeType().getCanonicalType();
2728 ObjCInterfaceType* ClsT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
2729
2730 if (!ClsT)
2731 return false;
2732
2733 IdentifierInfo* ClsName = ClsT->getDecl()->getIdentifier();
2734
2735 // FIXME: Should we walk the chain of classes?
2736 return ClsName == &Ctx.Idents.get("NSString") ||
2737 ClsName == &Ctx.Idents.get("NSMutableString");
2738}
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002739
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002740/// Handle __attribute__((format(type,idx,firstarg))) attributes
2741/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002742void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2743
2744 if (!rawAttr->getParameterName()) {
2745 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2746 "format", std::string("1"));
2747 return;
2748 }
2749
2750 if (rawAttr->getNumArgs() != 2) {
2751 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2752 std::string("3"));
2753 return;
2754 }
2755
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002756 // GCC ignores the format attribute on K&R style function
2757 // prototypes, so we ignore it as well
2758 const FunctionTypeProto *proto = getFunctionProto(d);
2759
2760 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002761 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2762 "format", "function");
2763 return;
2764 }
2765
2766 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002767 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002768 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002769 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002770 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002771
2772 const char *Format = rawAttr->getParameterName()->getName();
2773 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2774
2775 // Normalize the argument, __foo__ becomes foo.
2776 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2777 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2778 Format += 2;
2779 FormatLen -= 4;
2780 }
2781
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002782 bool Supported = false;
2783 bool is_NSString = false;
2784 bool is_strftime = false;
2785
2786 switch (FormatLen) {
2787 default: break;
2788 case 5:
2789 Supported = !memcmp(Format, "scanf", 5);
2790 break;
2791 case 6:
2792 Supported = !memcmp(Format, "printf", 6);
2793 break;
2794 case 7:
2795 Supported = !memcmp(Format, "strfmon", 7);
2796 break;
2797 case 8:
2798 Supported = (is_strftime = !memcmp(Format, "strftime", 8)) ||
2799 (is_NSString = !memcmp(Format, "NSString", 8));
2800 break;
2801 }
2802
2803 if (!Supported) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002804 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2805 "format", rawAttr->getParameterName()->getName());
2806 return;
2807 }
2808
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002809 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002810 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002811 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002812 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2813 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2814 "format", std::string("2"), IdxExpr->getSourceRange());
2815 return;
2816 }
2817
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002818 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002819 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2820 "format", std::string("2"), IdxExpr->getSourceRange());
2821 return;
2822 }
2823
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002824 // FIXME: Do we need to bounds check?
2825 unsigned ArgIdx = Idx.getZExtValue() - 1;
2826
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002827 // make sure the format string is really a string
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002828 QualType Ty = proto->getArgType(ArgIdx);
2829
2830 if (is_NSString) {
2831 // FIXME: do we need to check if the type is NSString*? What are
2832 // the semantics?
2833 if (!isNSStringType(Ty, Context)) {
2834 // FIXME: Should highlight the actual expression that has the
2835 // wrong type.
2836 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_NSString,
2837 IdxExpr->getSourceRange());
2838 return;
2839 }
2840 }
2841 else if (!Ty->isPointerType() ||
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002842 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002843 // FIXME: Should highlight the actual expression that has the
2844 // wrong type.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002845 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2846 IdxExpr->getSourceRange());
2847 return;
2848 }
2849
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002850 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002851 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002852 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002853 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2854 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2855 "format", std::string("3"), FirstArgExpr->getSourceRange());
2856 return;
2857 }
2858
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002859 // check if the function is variadic if the 3rd argument non-zero
2860 if (FirstArg != 0) {
2861 if (proto->isVariadic()) {
2862 ++NumArgs; // +1 for ...
2863 } else {
2864 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2865 return;
2866 }
2867 }
2868
2869 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2870 // the input is just the current time + the format string
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002871 if (is_strftime) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002872 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002873 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2874 FirstArgExpr->getSourceRange());
2875 return;
2876 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002877 // if 0 it disables parameter checking (to use with e.g. va_list)
2878 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002879 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2880 "format", std::string("3"), FirstArgExpr->getSourceRange());
2881 return;
2882 }
2883
2884 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2885 Idx.getZExtValue(), FirstArg.getZExtValue()));
2886}
2887
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002888void Sema::HandleTransparentUnionAttribute(Decl *d, AttributeList *rawAttr) {
2889 // check the attribute arguments.
2890 if (rawAttr->getNumArgs() != 0) {
2891 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2892 std::string("0"));
2893 return;
2894 }
2895
2896 TypeDecl *decl = dyn_cast<TypeDecl>(d);
2897
2898 if (!decl || !Context.getTypeDeclType(decl)->isUnionType()) {
2899 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2900 "transparent_union", "union");
2901 return;
2902 }
2903
Chris Lattner22624942008-04-30 16:04:01 +00002904 //QualType QTy = Context.getTypeDeclType(decl);
2905 //const RecordType *Ty = QTy->getAsUnionType();
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002906
2907// FIXME
2908// Ty->addAttr(new TransparentUnionAttr());
2909}
2910
Nate Begemanc398f0b2008-02-21 19:30:49 +00002911void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2912 // check the attribute arguments.
2913 if (rawAttr->getNumArgs() != 1) {
2914 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2915 std::string("1"));
2916 return;
2917 }
2918 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2919 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002920
Nate Begemanc398f0b2008-02-21 19:30:49 +00002921 // Make sure that there is a string literal as the annotation's single
2922 // argument.
2923 if (!SE) {
2924 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2925 return;
2926 }
2927 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2928 SE->getByteLength())));
2929}
2930
Anders Carlsson78aaae92007-12-19 07:19:40 +00002931void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2932{
2933 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002934 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002935 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002936 std::string("1"));
2937 return;
2938 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002939
Anders Carlsson042c4e72008-02-16 19:51:27 +00002940 unsigned Align = 0;
2941
2942 if (rawAttr->getNumArgs() == 0) {
2943 // FIXME: This should be the target specific maximum alignment.
2944 // (For now we just use 128 bits which is the maximum on X86.
2945 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002946 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002947 } else {
2948 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2949 llvm::APSInt alignment(32);
2950 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002951 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002952 "aligned", alignmentExpr->getSourceRange());
2953 return;
2954 }
2955
2956 Align = alignment.getZExtValue() * 8;
2957 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002958
Anders Carlsson042c4e72008-02-16 19:51:27 +00002959 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002960}