blob: 230ea3cb9da72d6fec8d0faebcf7973b4ba0eb4a [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"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Type.h"
22#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Basic/SourceManager.h"
Eli Friedmanc594b322008-05-20 13:48:25 +000027#include "clang/AST/ExprCXX.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000028// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000029#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000030#include "clang/Lex/HeaderSearch.h"
Steve Naroff563477d2007-09-18 23:55:05 +000031#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000033#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034using namespace clang;
35
Steve Naroffb327ce02008-04-02 14:35:35 +000036Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
37 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
38
Douglas Gregor2ce52f32008-04-13 21:07:44 +000039 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
40 isa<ObjCInterfaceDecl>(IIDecl) ||
41 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000042 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000043 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000044}
45
Chris Lattner9fdf9c62008-04-22 18:39:57 +000046void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000047 assert( ( (isa<ObjCMethodDecl>(DC) && isa<TranslationUnitDecl>(CurContext))
Chris Lattner9fdf9c62008-04-22 18:39:57 +000048 || DC->getParent() == CurContext ) &&
Chris Lattnerb048c982008-04-06 04:47:34 +000049 "The next DeclContext should be directly contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000050 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000051}
52
Chris Lattnerb048c982008-04-06 04:47:34 +000053void Sema::PopDeclContext() {
54 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000055 // If CurContext is a ObjC method, getParent() will return NULL.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000056 CurContext = isa<ObjCMethodDecl>(CurContext)
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000057 ? Context.getTranslationUnitDecl()
58 : CurContext->getParent();
Chris Lattner0ed844b2008-04-04 06:12:32 +000059}
60
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000061/// Add this decl to the scope shadowed decl chains.
62void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000063 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000064
65 // C++ [basic.scope]p4:
66 // -- exactly one declaration shall declare a class name or
67 // enumeration name that is not a typedef name and the other
68 // declarations shall all refer to the same object or
69 // enumerator, or all refer to functions and function templates;
70 // in this case the class name or enumeration name is hidden.
71 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
72 // We are pushing the name of a tag (enum or class).
73 IdentifierResolver::ctx_iterator
74 CIT = IdResolver.ctx_begin(TD->getIdentifier(), TD->getDeclContext());
75 if (CIT != IdResolver.ctx_end(TD->getIdentifier()) &&
76 IdResolver.isDeclInScope(*CIT, TD->getDeclContext(), S)) {
77 // There is already a declaration with the same name in the same
78 // scope. It must be found before we find the new declaration,
79 // so swap the order on the shadowed declaration chain.
80
81 IdResolver.AddShadowedDecl(TD, *CIT);
82 return;
83 }
84 }
85
86 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000087}
88
Steve Naroffb216c882007-10-09 22:01:59 +000089void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000090 if (S->decl_empty()) return;
91 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000092
93 // We only want to remove the decls from the identifier decl chains for local
94 // scopes, when inside a function/method.
95 if (S->getFnParent() == 0)
96 return;
Chris Lattner31e05722007-08-26 06:24:45 +000097
Reid Spencer5f016e22007-07-11 17:01:13 +000098 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
99 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000100 Decl *TmpD = static_cast<Decl*>(*I);
101 assert(TmpD && "This decl didn't get pushed??");
102 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
103 assert(D && "This decl isn't a ScopedDecl?");
104
Reid Spencer5f016e22007-07-11 17:01:13 +0000105 IdentifierInfo *II = D->getIdentifier();
106 if (!II) continue;
107
Chris Lattner7f925cc2008-04-11 07:00:53 +0000108 // Unlink this decl from the identifier.
109 IdResolver.RemoveDecl(D);
110
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 // This will have to be revisited for C++: there we want to nest stuff in
112 // namespace decls etc. Even for C, we might want a top-level translation
113 // unit decl or something.
114 if (!CurFunctionDecl)
115 continue;
116
117 // Chain this decl to the containing function, it now owns the memory for
118 // the decl.
119 D->setNext(CurFunctionDecl->getDeclChain());
120 CurFunctionDecl->setDeclChain(D);
121 }
122}
123
Steve Naroffe8043c32008-04-01 23:04:06 +0000124/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
125/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000126ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000127 // The third "scope" argument is 0 since we aren't enabling lazy built-in
128 // creation from this context.
129 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000130
Steve Naroffb327ce02008-04-02 14:35:35 +0000131 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000132}
133
Steve Naroffe8043c32008-04-01 23:04:06 +0000134/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000135/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000136Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
137 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000138 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000139 unsigned NS = NSI;
140 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
141 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000142
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 // Scan up the scope chain looking for a decl that matches this identifier
144 // that is in the appropriate namespace. This search should not take long, as
145 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000146 for (IdentifierResolver::iterator
147 I = IdResolver.begin(II, CurContext), E = IdResolver.end(II); I != E; ++I)
148 if ((*I)->getIdentifierNamespace() & NS)
149 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000150
Reid Spencer5f016e22007-07-11 17:01:13 +0000151 // If we didn't find a use of this identifier, and if the identifier
152 // corresponds to a compiler builtin, create the decl object for the builtin
153 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000154 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000155 if (enableLazyBuiltinCreation) {
156 // If this is a builtin on this (or all) targets, create the decl.
157 if (unsigned BuiltinID = II->getBuiltinID())
158 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
159 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000160 if (getLangOptions().ObjC1) {
161 // @interface and @compatibility_alias introduce typedef-like names.
162 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000163 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000164 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000165 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
166 if (IDI != ObjCInterfaceDecls.end())
167 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000168 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
169 if (I != ObjCAliasDecls.end())
170 return I->second->getClassInterface();
171 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000172 }
173 return 0;
174}
175
Chris Lattner95e2c712008-05-05 22:18:14 +0000176void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000177 if (!Context.getBuiltinVaListType().isNull())
178 return;
179
180 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000181 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000182 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000183 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
184}
185
Reid Spencer5f016e22007-07-11 17:01:13 +0000186/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
187/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000188ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
189 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 Builtin::ID BID = (Builtin::ID)bid;
191
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000192 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattner95e2c712008-05-05 22:18:14 +0000193 BID == Builtin::BI__builtin_va_copy ||
194 BID == Builtin::BI__builtin_va_end)
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000195 InitBuiltinVaListType();
196
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000197 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000198 FunctionDecl *New = FunctionDecl::Create(Context,
199 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000200 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000201 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000202
Chris Lattner95e2c712008-05-05 22:18:14 +0000203 // Create Decl objects for each parameter, adding them to the
204 // FunctionDecl.
205 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
206 llvm::SmallVector<ParmVarDecl*, 16> Params;
207 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
208 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
209 FT->getArgType(i), VarDecl::None, 0,
210 0));
211 New->setParams(&Params[0], Params.size());
212 }
213
214
215
Chris Lattner7f925cc2008-04-11 07:00:53 +0000216 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000217 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000218 return New;
219}
220
221/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
222/// and scope as a previous declaration 'Old'. Figure out how to resolve this
223/// situation, merging decls or emitting diagnostics as appropriate.
224///
Steve Naroffe8043c32008-04-01 23:04:06 +0000225TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000226 // Verify the old decl was also a typedef.
227 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
228 if (!Old) {
229 Diag(New->getLocation(), diag::err_redefinition_different_kind,
230 New->getName());
231 Diag(OldD->getLocation(), diag::err_previous_definition);
232 return New;
233 }
234
Steve Naroff8ee529b2007-10-31 18:42:27 +0000235 // Allow multiple definitions for ObjC built-in typedefs.
236 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000237 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000238 return Old;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000239
240 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
241 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
242 // *either* declaration is in a system header. The code below implements
243 // this adhoc compatibility rule. FIXME: The following code will not
244 // work properly when compiling ".i" files (containing preprocessed output).
245 SourceManager &SrcMgr = Context.getSourceManager();
246 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
247 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
248 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
249 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
250 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
251
Steve Naroffc5e2f342008-03-26 21:27:00 +0000252 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
253 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
254 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroffd62701b2008-02-07 03:50:06 +0000255 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000256 return New;
Steve Naroffc5e2f342008-03-26 21:27:00 +0000257
Reid Spencer5f016e22007-07-11 17:01:13 +0000258 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
259 // TODO: This is totally simplistic. It should handle merging functions
260 // together etc, merging extern int X; int X; ...
Ted Kremenek2d05c082008-05-23 21:28:18 +0000261 Diag(New->getLocation(), diag::err_redefinition, New->getName());
262 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000263 return New;
264}
265
Chris Lattnerddee4232008-03-03 03:28:21 +0000266/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
267static bool DeclHasAttr(const Decl *decl, const Attr *target) {
268 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
269 if (attr->getKind() == target->getKind())
270 return true;
271
272 return false;
273}
274
275/// MergeAttributes - append attributes from the Old decl to the New one.
276static void MergeAttributes(Decl *New, Decl *Old) {
277 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
278
Chris Lattnerddee4232008-03-03 03:28:21 +0000279 while (attr) {
280 tmp = attr;
281 attr = attr->getNext();
282
283 if (!DeclHasAttr(New, tmp)) {
284 New->addAttr(tmp);
285 } else {
286 tmp->setNext(0);
287 delete(tmp);
288 }
289 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000290
291 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000292}
293
Chris Lattner04421082008-04-08 04:40:51 +0000294/// MergeFunctionDecl - We just parsed a function 'New' from
295/// declarator D which has the same name and scope as a previous
296/// declaration 'Old'. Figure out how to resolve this situation,
297/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000298/// Redeclaration will be set true if thisNew is a redeclaration OldD.
299FunctionDecl *
300Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
301 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 // Verify the old decl was also a function.
303 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
304 if (!Old) {
305 Diag(New->getLocation(), diag::err_redefinition_different_kind,
306 New->getName());
307 Diag(OldD->getLocation(), diag::err_previous_definition);
308 return New;
309 }
Chris Lattner04421082008-04-08 04:40:51 +0000310
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000311 QualType OldQType = Context.getCanonicalType(Old->getType());
312 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000313
Chris Lattner04421082008-04-08 04:40:51 +0000314 // C++ [dcl.fct]p3:
315 // All declarations for a function shall agree exactly in both the
316 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000317 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
318 MergeAttributes(New, Old);
319 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000320 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000321 }
Chris Lattner04421082008-04-08 04:40:51 +0000322
323 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000324 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000325 if (!getLangOptions().CPlusPlus &&
326 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000327 MergeAttributes(New, Old);
328 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000329 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000330 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000331
Steve Naroff837618c2008-01-16 15:01:34 +0000332 // A function that has already been declared has been redeclared or defined
333 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000334 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000335 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000336 PrevDiag = diag::err_previous_definition;
337 else if (Old->isImplicit())
338 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000339 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000340 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000341
Reid Spencer5f016e22007-07-11 17:01:13 +0000342 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
343 // TODO: This is totally simplistic. It should handle merging functions
344 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000345 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
346 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 return New;
348}
349
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000350/// equivalentArrayTypes - Used to determine whether two array types are
351/// equivalent.
352/// We need to check this explicitly as an incomplete array definition is
353/// considered a VariableArrayType, so will not match a complete array
354/// definition that would be otherwise equivalent.
355static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
356 const ArrayType *NewAT = NewQType->getAsArrayType();
357 const ArrayType *OldAT = OldQType->getAsArrayType();
358
359 if (!NewAT || !OldAT)
360 return false;
361
362 // If either (or both) array types in incomplete we need to strip off the
363 // outer VariableArrayType. Once the outer VAT is removed the remaining
364 // types must be identical if the array types are to be considered
365 // equivalent.
366 // eg. int[][1] and int[1][1] become
367 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
368 // removing the outermost VAT gives
369 // CAT(1, int) and CAT(1, int)
370 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000371 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000372 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
373 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000374 NewQType = NewAT->getElementType().getCanonicalType();
375 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000376 }
377
378 return NewQType == OldQType;
379}
380
Reid Spencer5f016e22007-07-11 17:01:13 +0000381/// MergeVarDecl - We just parsed a variable 'New' which has the same name
382/// and scope as a previous declaration 'Old'. Figure out how to resolve this
383/// situation, merging decls or emitting diagnostics as appropriate.
384///
385/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
386/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
387///
Steve Naroffe8043c32008-04-01 23:04:06 +0000388VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 // Verify the old decl was also a variable.
390 VarDecl *Old = dyn_cast<VarDecl>(OldD);
391 if (!Old) {
392 Diag(New->getLocation(), diag::err_redefinition_different_kind,
393 New->getName());
394 Diag(OldD->getLocation(), diag::err_previous_definition);
395 return New;
396 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000397
398 MergeAttributes(New, Old);
399
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000401 QualType OldCType = Context.getCanonicalType(Old->getType());
402 QualType NewCType = Context.getCanonicalType(New->getType());
403 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 Diag(New->getLocation(), diag::err_redefinition, New->getName());
405 Diag(Old->getLocation(), diag::err_previous_definition);
406 return New;
407 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000408 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
409 if (New->getStorageClass() == VarDecl::Static &&
410 (Old->getStorageClass() == VarDecl::None ||
411 Old->getStorageClass() == VarDecl::Extern)) {
412 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
413 Diag(Old->getLocation(), diag::err_previous_definition);
414 return New;
415 }
416 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
417 if (New->getStorageClass() != VarDecl::Static &&
418 Old->getStorageClass() == VarDecl::Static) {
419 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
420 Diag(Old->getLocation(), diag::err_previous_definition);
421 return New;
422 }
423 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff248a7532008-04-15 22:42:06 +0000424 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb7b032e2008-01-30 00:44:01 +0000425 // Handle C "tentative" external object definitions (C99 6.9.2).
426 bool OldIsTentative = false;
427 bool NewIsTentative = false;
428
Steve Naroff248a7532008-04-15 22:42:06 +0000429 if (!Old->getInit() &&
430 (Old->getStorageClass() == VarDecl::None ||
431 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000432 OldIsTentative = true;
433
434 // FIXME: this check doesn't work (since the initializer hasn't been
435 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
436 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
437 // thrown out the old decl.
Steve Naroff248a7532008-04-15 22:42:06 +0000438 if (!New->getInit() &&
439 (New->getStorageClass() == VarDecl::None ||
440 New->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000441 ; // change to NewIsTentative = true; once the code is moved.
442
443 if (NewIsTentative || OldIsTentative)
444 return New;
445 }
Steve Naroff235549c2008-05-12 22:36:43 +0000446 // Handle __private_extern__ just like extern.
Steve Naroffb7b032e2008-01-30 00:44:01 +0000447 if (Old->getStorageClass() != VarDecl::Extern &&
Steve Naroff235549c2008-05-12 22:36:43 +0000448 Old->getStorageClass() != VarDecl::PrivateExtern &&
449 New->getStorageClass() != VarDecl::Extern &&
450 New->getStorageClass() != VarDecl::PrivateExtern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 Diag(New->getLocation(), diag::err_redefinition, New->getName());
452 Diag(Old->getLocation(), diag::err_previous_definition);
453 }
454 return New;
455}
456
Chris Lattner04421082008-04-08 04:40:51 +0000457/// CheckParmsForFunctionDef - Check that the parameters of the given
458/// function are appropriate for the definition of a function. This
459/// takes care of any checks that cannot be performed on the
460/// declaration itself, e.g., that the types of each of the function
461/// parameters are complete.
462bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
463 bool HasInvalidParm = false;
464 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
465 ParmVarDecl *Param = FD->getParamDecl(p);
466
467 // C99 6.7.5.3p4: the parameters in a parameter type list in a
468 // function declarator that is part of a function definition of
469 // that function shall not have incomplete type.
470 if (Param->getType()->isIncompleteType() &&
471 !Param->isInvalidDecl()) {
472 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
473 Param->getType().getAsString());
474 Param->setInvalidDecl();
475 HasInvalidParm = true;
476 }
477 }
478
479 return HasInvalidParm;
480}
481
482/// CreateImplicitParameter - Creates an implicit function parameter
483/// in the scope S and with the given type. This routine is used, for
484/// example, to create the implicit "self" parameter in an Objective-C
485/// method.
486ParmVarDecl *
487Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
488 SourceLocation IdLoc, QualType Type) {
489 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
490 VarDecl::None, 0, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000491 if (Id)
492 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000493
494 return New;
495}
496
Reid Spencer5f016e22007-07-11 17:01:13 +0000497/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
498/// no declarator (e.g. "struct foo;") is parsed.
499Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
500 // TODO: emit error on 'int;' or 'const enum foo;'.
501 // TODO: emit error on 'typedef int;'
502 // if (!DS.isMissingDeclaratorOk()) Diag(...);
503
Steve Naroff92199282007-11-17 21:37:36 +0000504 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000505}
506
Steve Naroffd0091aa2008-01-10 22:15:12 +0000507bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000508 // Get the type before calling CheckSingleAssignmentConstraints(), since
509 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000510 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000511
Chris Lattner5cf216b2008-01-04 18:04:52 +0000512 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
513 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
514 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000515}
516
Steve Naroff9e8925e2007-09-04 14:36:54 +0000517bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000518 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000519 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000520 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000521 return true; // types weren't compatible.
522
Steve Naroff9e8925e2007-09-04 14:36:54 +0000523 if (savExpr != expr) // The type was promoted, update initializer list.
524 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000525 return false;
526}
527
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000528bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000529 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000530 // C99 6.7.8p14. We have an array of character type with unknown size
531 // being initialized to a string literal.
532 llvm::APSInt ConstVal(32);
533 ConstVal = strLiteral->getByteLength() + 1;
534 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000535 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000536 ArrayType::Normal, 0);
537 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
538 // C99 6.7.8p14. We have an array of character type with known size.
539 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
540 Diag(strLiteral->getSourceRange().getBegin(),
541 diag::warn_initializer_string_for_char_array_too_long,
542 strLiteral->getSourceRange());
543 } else {
544 assert(0 && "HandleStringLiteralInit(): Invalid array type");
545 }
546 // Set type from "char *" to "constant array of char".
547 strLiteral->setType(DeclT);
548 // For now, we always return false (meaning success).
549 return false;
550}
551
552StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000553 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000554 if (AT && AT->getElementType()->isCharType()) {
555 return dyn_cast<StringLiteral>(Init);
556 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000557 return 0;
558}
559
Steve Naroffa9960332008-01-25 00:51:06 +0000560// CheckInitializerListTypes - Checks the types of elements of an initializer
561// list. This function is recursive: it calls itself to initialize subelements
562// of aggregate types. Note that the topLevel parameter essentially refers to
563// whether this expression "owns" the initializer list passed in, or if this
564// initialization is taking elements out of a parent initializer. Each
565// call to this function adds zero or more to startIndex, reports any errors,
566// and returns true if it found any inconsistent types.
567bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
568 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000569 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000570
571 if (DeclType->isScalarType()) {
572 // The simplest case: initializing a single scalar
573 if (topLevel) {
574 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
575 IList->getSourceRange());
576 }
577 if (startIndex < IList->getNumInits()) {
578 Expr* expr = IList->getInit(startIndex);
579 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
580 // FIXME: Should an error be reported here instead?
581 unsigned newIndex = 0;
582 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
583 } else {
584 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
585 }
586 ++startIndex;
587 }
588 // FIXME: Should an error be reported for empty initializer list + scalar?
589 } else if (DeclType->isVectorType()) {
590 if (startIndex < IList->getNumInits()) {
591 const VectorType *VT = DeclType->getAsVectorType();
592 int maxElements = VT->getNumElements();
593 QualType elementType = VT->getElementType();
594
595 for (int i = 0; i < maxElements; ++i) {
596 // Don't attempt to go past the end of the init list
597 if (startIndex >= IList->getNumInits())
598 break;
599 Expr* expr = IList->getInit(startIndex);
600 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
601 unsigned newIndex = 0;
602 hadError |= CheckInitializerListTypes(SubInitList, elementType,
603 true, newIndex);
604 ++startIndex;
605 } else {
606 hadError |= CheckInitializerListTypes(IList, elementType,
607 false, startIndex);
608 }
609 }
610 }
611 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
612 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000613 if (startIndex < IList->getNumInits() && !topLevel &&
614 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
615 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000616 // We found a compatible struct; per the standard, this initializes the
617 // struct. (The C standard technically says that this only applies for
618 // initializers for declarations with automatic scope; however, this
619 // construct is unambiguous anyway because a struct cannot contain
620 // a type compatible with itself. We'll output an error when we check
621 // if the initializer is constant.)
622 // FIXME: Is a call to CheckSingleInitializer required here?
623 ++startIndex;
624 } else {
625 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffb43eaa52008-02-11 00:06:17 +0000626
Steve Naroff406db932008-02-11 21:52:37 +0000627 // If the record is invalid, some of it's members are invalid. To avoid
628 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffb43eaa52008-02-11 00:06:17 +0000629 if (structDecl->isInvalidDecl())
630 return true;
631
Steve Naroffa9960332008-01-25 00:51:06 +0000632 // If structDecl is a forward declaration, this loop won't do anything;
633 // That's okay, because an error should get printed out elsewhere. It
634 // might be worthwhile to skip over the rest of the initializer, though.
635 int numMembers = structDecl->getNumMembers() -
636 structDecl->hasFlexibleArrayMember();
637 for (int i = 0; i < numMembers; i++) {
638 // Don't attempt to go past the end of the init list
639 if (startIndex >= IList->getNumInits())
640 break;
641 FieldDecl * curField = structDecl->getMember(i);
642 if (!curField->getIdentifier()) {
643 // Don't initialize unnamed fields, e.g. "int : 20;"
644 continue;
645 }
646 QualType fieldType = curField->getType();
647 Expr* expr = IList->getInit(startIndex);
648 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
649 unsigned newStart = 0;
650 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
651 true, newStart);
652 ++startIndex;
653 } else {
654 hadError |= CheckInitializerListTypes(IList, fieldType,
655 false, startIndex);
656 }
657 if (DeclType->isUnionType())
658 break;
659 }
660 // FIXME: Implement flexible array initialization GCC extension (it's a
661 // really messy extension to implement, unfortunately...the necessary
662 // information isn't actually even here!)
663 }
664 } else if (DeclType->isArrayType()) {
665 // Check for the special-case of initializing an array with a string.
666 if (startIndex < IList->getNumInits()) {
667 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
668 DeclType)) {
669 CheckStringLiteralInit(lit, DeclType);
670 ++startIndex;
671 if (topLevel && startIndex < IList->getNumInits()) {
672 // We have leftover initializers; warn
673 Diag(IList->getInit(startIndex)->getLocStart(),
674 diag::err_excess_initializers_in_char_array_initializer,
675 IList->getInit(startIndex)->getSourceRange());
676 }
677 return false;
678 }
679 }
680 int maxElements;
Eli Friedmanc5773c42008-02-15 18:16:39 +0000681 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000682 // FIXME: use a proper constant
683 maxElements = 0x7FFFFFFF;
Chris Lattner212839c2008-02-20 23:17:35 +0000684 } else if (const VariableArrayType *VAT =
685 DeclType->getAsVariableArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000686 // Check for VLAs; in standard C it would be possible to check this
687 // earlier, but I don't know where clang accepts VLAs (gcc accepts
688 // them in all sorts of strange places).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000689 Diag(VAT->getSizeExpr()->getLocStart(),
690 diag::err_variable_object_no_init,
691 VAT->getSizeExpr()->getSourceRange());
692 hadError = true;
693 maxElements = 0x7FFFFFFF;
Steve Naroffa9960332008-01-25 00:51:06 +0000694 } else {
695 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
696 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
697 }
698 QualType elementType = DeclType->getAsArrayType()->getElementType();
699 int numElements = 0;
700 for (int i = 0; i < maxElements; ++i, ++numElements) {
701 // Don't attempt to go past the end of the init list
702 if (startIndex >= IList->getNumInits())
703 break;
704 Expr* expr = IList->getInit(startIndex);
705 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
706 unsigned newIndex = 0;
707 hadError |= CheckInitializerListTypes(SubInitList, elementType,
708 true, newIndex);
709 ++startIndex;
710 } else {
711 hadError |= CheckInitializerListTypes(IList, elementType,
712 false, startIndex);
713 }
714 }
Eli Friedman9db13972008-02-15 12:53:51 +0000715 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000716 // If this is an incomplete array type, the actual type needs to
717 // be calculated here
718 if (numElements == 0) {
719 // Sizing an array implicitly to zero is not allowed
720 // (It could in theory be allowed, but it doesn't really matter.)
721 Diag(IList->getLocStart(),
722 diag::err_at_least_one_initializer_needed_to_size_array);
723 hadError = true;
724 } else {
725 llvm::APSInt ConstVal(32);
726 ConstVal = numElements;
727 DeclType = Context.getConstantArrayType(elementType, ConstVal,
728 ArrayType::Normal, 0);
729 }
730 }
731 } else {
732 assert(0 && "Aggregate that isn't a function or array?!");
733 }
734 } else {
735 // In C, all types are either scalars or aggregates, but
736 // additional handling is needed here for C++ (and possibly others?).
737 assert(0 && "Unsupported initializer type");
738 }
739
740 // If this init list is a base list, we set the type; an initializer doesn't
741 // fundamentally have a type, but this makes the ASTs a bit easier to read
742 if (topLevel)
743 IList->setType(DeclType);
744
745 if (topLevel && startIndex < IList->getNumInits()) {
746 // We have leftover initializers; warn
747 Diag(IList->getInit(startIndex)->getLocStart(),
748 diag::warn_excess_initializers,
749 IList->getInit(startIndex)->getSourceRange());
750 }
751 return hadError;
752}
753
754bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000755 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
756 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000757 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000758 return Diag(VAT->getSizeExpr()->getLocStart(),
759 diag::err_variable_object_no_init,
760 VAT->getSizeExpr()->getSourceRange());
761
Steve Naroff2fdc3742007-12-10 22:44:33 +0000762 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
763 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000764 // FIXME: Handle wide strings
765 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
766 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000767
768 if (DeclType->isArrayType())
769 return Diag(Init->getLocStart(),
770 diag::err_array_init_list_required,
771 Init->getSourceRange());
772
Steve Naroffd0091aa2008-01-10 22:15:12 +0000773 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000774 }
Eli Friedmanc56c9772008-05-19 20:29:35 +0000775#if 0
Steve Naroffa9960332008-01-25 00:51:06 +0000776 unsigned newIndex = 0;
777 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000778#else
779 InitListChecker CheckInitList(this, InitList, DeclType);
780 return CheckInitList.HadError();
781#endif
Steve Narofff0090632007-09-02 02:04:30 +0000782}
783
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000784Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000785Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000786 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 IdentifierInfo *II = D.getIdentifier();
788
Chris Lattnere80a59c2007-07-25 00:24:17 +0000789 // All of these full declarators require an identifier. If it doesn't have
790 // one, the ParsedFreeStandingDeclSpec action should be used.
791 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000792 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000793 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000794 D.getDeclSpec().getSourceRange(), D.getSourceRange());
795 return 0;
796 }
797
Chris Lattner31e05722007-08-26 06:24:45 +0000798 // The scope passed in may not be a decl scope. Zip up the scope tree until
799 // we find one that is.
800 while ((S->getFlags() & Scope::DeclScope) == 0)
801 S = S->getParent();
802
Reid Spencer5f016e22007-07-11 17:01:13 +0000803 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000804 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000805 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000806 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000807
808 // In C++, the previous declaration we find might be a tag type
809 // (class or enum). In this case, the new declaration will hide the
810 // tag type.
811 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
812 PrevDecl = 0;
813
Chris Lattner41af0932007-11-14 06:34:38 +0000814 QualType R = GetTypeForDeclarator(D, S);
815 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
816
Reid Spencer5f016e22007-07-11 17:01:13 +0000817 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000818 // Check that there are no default arguments (C++ only).
819 if (getLangOptions().CPlusPlus)
820 CheckExtraCXXDefaultArguments(D);
821
Chris Lattner41af0932007-11-14 06:34:38 +0000822 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000823 if (!NewTD) return 0;
824
825 // Handle attributes prior to checking for duplicates in MergeVarDecl
826 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
827 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000828 // Merge the decl with the existing one if appropriate. If the decl is
829 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000830 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000831 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
832 if (NewTD == 0) return 0;
833 }
834 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000835 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000836 // C99 6.7.7p2: If a typedef name specifies a variably modified type
837 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000838 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
839 // FIXME: Diagnostic needs to be fixed.
840 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000841 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000842 }
843 }
Chris Lattner41af0932007-11-14 06:34:38 +0000844 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000845 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000846 switch (D.getDeclSpec().getStorageClassSpec()) {
847 default: assert(0 && "Unknown storage class!");
848 case DeclSpec::SCS_auto:
849 case DeclSpec::SCS_register:
850 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
851 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000852 InvalidDecl = true;
853 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000854 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
855 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
856 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000857 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000858 }
859
Chris Lattnera98e58d2008-03-15 21:24:04 +0000860 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000861 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
862 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000863 II, R, SC, isInline,
864 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000865 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000866 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
867 D.getAttributes());
Chris Lattner04421082008-04-08 04:40:51 +0000868
869 // Copy the parameter declarations from the declarator D to
870 // the function declaration NewFD, if they are available.
871 if (D.getNumTypeObjects() > 0 &&
872 D.getTypeObject(0).Fun.hasPrototype) {
873 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
874
875 // Create Decl objects for each parameter, adding them to the
876 // FunctionDecl.
877 llvm::SmallVector<ParmVarDecl*, 16> Params;
878
879 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
880 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000881 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000882 // We let through "const void" here because Sema::GetTypeForDeclarator
883 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000884 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
885 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000886 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
887 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000888 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
889
Chris Lattnerdef026a2008-04-10 02:26:16 +0000890 // In C++, the empty parameter-type-list must be spelled "void"; a
891 // typedef of void is not permitted.
892 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000893 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000894 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
895 }
896
Chris Lattner04421082008-04-08 04:40:51 +0000897 } else {
898 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
899 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
900 }
901
902 NewFD->setParams(&Params[0], Params.size());
903 }
904
Steve Naroffffce4d52008-01-09 23:34:55 +0000905 // Merge the decl with the existing one if appropriate. Since C functions
906 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000907 if (PrevDecl &&
908 (!getLangOptions().CPlusPlus ||
909 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000910 bool Redeclaration = false;
911 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000912 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000913 if (Redeclaration) {
Eli Friedman27424962008-05-27 05:07:37 +0000914 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregorf0097952008-04-21 02:02:58 +0000915 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000916 }
917 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000918
919 // In C++, check default arguments now that we have merged decls.
920 if (getLangOptions().CPlusPlus)
921 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000922 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000923 // Check that there are no default arguments (C++ only).
924 if (getLangOptions().CPlusPlus)
925 CheckExtraCXXDefaultArguments(D);
926
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000927 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000928 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
929 D.getIdentifier()->getName());
930 InvalidDecl = true;
931 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000932
933 VarDecl *NewVD;
934 VarDecl::StorageClass SC;
935 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000936 default: assert(0 && "Unknown storage class!");
937 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
938 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
939 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
940 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
941 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
942 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000943 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000944 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000945 // C99 6.9p2: The storage-class specifiers auto and register shall not
946 // appear in the declaration specifiers in an external declaration.
947 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
948 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
949 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000950 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000951 }
Steve Naroff248a7532008-04-15 22:42:06 +0000952 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
953 II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000954 } else {
Steve Naroff248a7532008-04-15 22:42:06 +0000955 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
956 II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000957 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000958 // Handle attributes prior to checking for duplicates in MergeVarDecl
959 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
960 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000961
962 // Emit an error if an address space was applied to decl with local storage.
963 // This includes arrays of objects with address space qualifiers, but not
964 // automatic variables that point to other address spaces.
965 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000966 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
967 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
968 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000969 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000970 // Merge the decl with the existing one if appropriate. If the decl is
971 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000972 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000973 NewVD = MergeVarDecl(NewVD, PrevDecl);
974 if (NewVD == 0) return 0;
975 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 New = NewVD;
977 }
978
979 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000980 if (II)
981 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000982 // If any semantic error occurred, mark the decl as invalid.
983 if (D.getInvalidType() || InvalidDecl)
984 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000985
986 return New;
987}
988
Eli Friedmanc594b322008-05-20 13:48:25 +0000989bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
990 switch (Init->getStmtClass()) {
991 default:
992 Diag(Init->getExprLoc(),
993 diag::err_init_element_not_constant, Init->getSourceRange());
994 return true;
995 case Expr::ParenExprClass: {
996 const ParenExpr* PE = cast<ParenExpr>(Init);
997 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
998 }
999 case Expr::CompoundLiteralExprClass:
1000 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1001 case Expr::DeclRefExprClass: {
1002 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001003 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1004 if (VD->hasGlobalStorage())
1005 return false;
1006 Diag(Init->getExprLoc(),
1007 diag::err_init_element_not_constant, Init->getSourceRange());
1008 return true;
1009 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001010 if (isa<FunctionDecl>(D))
1011 return false;
1012 Diag(Init->getExprLoc(),
1013 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroffd0091aa2008-01-10 22:15:12 +00001014 return true;
1015 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001016 case Expr::MemberExprClass: {
1017 const MemberExpr *M = cast<MemberExpr>(Init);
1018 if (M->isArrow())
1019 return CheckAddressConstantExpression(M->getBase());
1020 return CheckAddressConstantExpressionLValue(M->getBase());
1021 }
1022 case Expr::ArraySubscriptExprClass: {
1023 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1024 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1025 return CheckAddressConstantExpression(ASE->getBase()) ||
1026 CheckArithmeticConstantExpression(ASE->getIdx());
1027 }
1028 case Expr::StringLiteralClass:
1029 case Expr::PreDefinedExprClass:
1030 return false;
1031 case Expr::UnaryOperatorClass: {
1032 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1033
1034 // C99 6.6p9
1035 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001036 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001037
1038 Diag(Init->getExprLoc(),
1039 diag::err_init_element_not_constant, Init->getSourceRange());
1040 return true;
1041 }
1042 }
1043}
1044
1045bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1046 switch (Init->getStmtClass()) {
1047 default:
1048 Diag(Init->getExprLoc(),
1049 diag::err_init_element_not_constant, Init->getSourceRange());
1050 return true;
1051 case Expr::ParenExprClass: {
1052 const ParenExpr* PE = cast<ParenExpr>(Init);
1053 return CheckAddressConstantExpression(PE->getSubExpr());
1054 }
1055 case Expr::StringLiteralClass:
1056 case Expr::ObjCStringLiteralClass:
1057 return false;
1058 case Expr::CallExprClass: {
1059 const CallExpr *CE = cast<CallExpr>(Init);
1060 if (CE->isBuiltinConstantExpr())
1061 return false;
1062 Diag(Init->getExprLoc(),
1063 diag::err_init_element_not_constant, Init->getSourceRange());
1064 return true;
1065 }
1066 case Expr::UnaryOperatorClass: {
1067 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1068
1069 // C99 6.6p9
1070 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1071 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1072
1073 if (Exp->getOpcode() == UnaryOperator::Extension)
1074 return CheckAddressConstantExpression(Exp->getSubExpr());
1075
1076 Diag(Init->getExprLoc(),
1077 diag::err_init_element_not_constant, Init->getSourceRange());
1078 return true;
1079 }
1080 case Expr::BinaryOperatorClass: {
1081 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1082 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1083
1084 Expr *PExp = Exp->getLHS();
1085 Expr *IExp = Exp->getRHS();
1086 if (IExp->getType()->isPointerType())
1087 std::swap(PExp, IExp);
1088
1089 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1090 return CheckAddressConstantExpression(PExp) ||
1091 CheckArithmeticConstantExpression(IExp);
1092 }
1093 case Expr::ImplicitCastExprClass: {
1094 const Expr* SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1095
1096 // Check for implicit promotion
1097 if (SubExpr->getType()->isFunctionType() ||
1098 SubExpr->getType()->isArrayType())
1099 return CheckAddressConstantExpressionLValue(SubExpr);
1100
1101 // Check for pointer->pointer cast
1102 if (SubExpr->getType()->isPointerType())
1103 return CheckAddressConstantExpression(SubExpr);
1104
1105 if (SubExpr->getType()->isArithmeticType())
1106 return CheckArithmeticConstantExpression(SubExpr);
1107
1108 Diag(Init->getExprLoc(),
1109 diag::err_init_element_not_constant, Init->getSourceRange());
1110 return true;
1111 }
1112 case Expr::CastExprClass: {
1113 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
1114
1115 // Check for pointer->pointer cast
1116 if (SubExpr->getType()->isPointerType())
1117 return CheckAddressConstantExpression(SubExpr);
1118
1119 // FIXME: Should we pedwarn for (int*)(0+0)?
1120 if (SubExpr->getType()->isArithmeticType())
1121 return CheckArithmeticConstantExpression(SubExpr);
1122
1123 Diag(Init->getExprLoc(),
1124 diag::err_init_element_not_constant, Init->getSourceRange());
1125 return true;
1126 }
1127 case Expr::ConditionalOperatorClass: {
1128 // FIXME: Should we pedwarn here?
1129 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1130 if (!Exp->getCond()->getType()->isArithmeticType()) {
1131 Diag(Init->getExprLoc(),
1132 diag::err_init_element_not_constant, Init->getSourceRange());
1133 return true;
1134 }
1135 if (CheckArithmeticConstantExpression(Exp->getCond()))
1136 return true;
1137 if (Exp->getLHS() &&
1138 CheckAddressConstantExpression(Exp->getLHS()))
1139 return true;
1140 return CheckAddressConstantExpression(Exp->getRHS());
1141 }
1142 case Expr::AddrLabelExprClass:
1143 return false;
1144 }
1145}
1146
1147bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1148 switch (Init->getStmtClass()) {
1149 default:
1150 Diag(Init->getExprLoc(),
1151 diag::err_init_element_not_constant, Init->getSourceRange());
1152 return true;
1153 case Expr::ParenExprClass: {
1154 const ParenExpr* PE = cast<ParenExpr>(Init);
1155 return CheckArithmeticConstantExpression(PE->getSubExpr());
1156 }
1157 case Expr::FloatingLiteralClass:
1158 case Expr::IntegerLiteralClass:
1159 case Expr::CharacterLiteralClass:
1160 case Expr::ImaginaryLiteralClass:
1161 case Expr::TypesCompatibleExprClass:
1162 case Expr::CXXBoolLiteralExprClass:
1163 return false;
1164 case Expr::CallExprClass: {
1165 const CallExpr *CE = cast<CallExpr>(Init);
1166 if (CE->isBuiltinConstantExpr())
1167 return false;
1168 Diag(Init->getExprLoc(),
1169 diag::err_init_element_not_constant, Init->getSourceRange());
1170 return true;
1171 }
1172 case Expr::DeclRefExprClass: {
1173 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1174 if (isa<EnumConstantDecl>(D))
1175 return false;
1176 Diag(Init->getExprLoc(),
1177 diag::err_init_element_not_constant, Init->getSourceRange());
1178 return true;
1179 }
1180 case Expr::CompoundLiteralExprClass:
1181 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1182 // but vectors are allowed to be magic.
1183 if (Init->getType()->isVectorType())
1184 return false;
1185 Diag(Init->getExprLoc(),
1186 diag::err_init_element_not_constant, Init->getSourceRange());
1187 return true;
1188 case Expr::UnaryOperatorClass: {
1189 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1190
1191 switch (Exp->getOpcode()) {
1192 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1193 // See C99 6.6p3.
1194 default:
1195 Diag(Init->getExprLoc(),
1196 diag::err_init_element_not_constant, Init->getSourceRange());
1197 return true;
1198 case UnaryOperator::SizeOf:
1199 case UnaryOperator::AlignOf:
1200 case UnaryOperator::OffsetOf:
1201 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1202 // See C99 6.5.3.4p2 and 6.6p3.
1203 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1204 return false;
1205 Diag(Init->getExprLoc(),
1206 diag::err_init_element_not_constant, Init->getSourceRange());
1207 return true;
1208 case UnaryOperator::Extension:
1209 case UnaryOperator::LNot:
1210 case UnaryOperator::Plus:
1211 case UnaryOperator::Minus:
1212 case UnaryOperator::Not:
1213 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1214 }
1215 }
1216 case Expr::SizeOfAlignOfTypeExprClass: {
1217 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1218 // Special check for void types, which are allowed as an extension
1219 if (Exp->getArgumentType()->isVoidType())
1220 return false;
1221 // alignof always evaluates to a constant.
1222 // FIXME: is sizeof(int[3.0]) a constant expression?
1223 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1224 Diag(Init->getExprLoc(),
1225 diag::err_init_element_not_constant, Init->getSourceRange());
1226 return true;
1227 }
1228 return false;
1229 }
1230 case Expr::BinaryOperatorClass: {
1231 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1232
1233 if (Exp->getLHS()->getType()->isArithmeticType() &&
1234 Exp->getRHS()->getType()->isArithmeticType()) {
1235 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1236 CheckArithmeticConstantExpression(Exp->getRHS());
1237 }
1238
1239 Diag(Init->getExprLoc(),
1240 diag::err_init_element_not_constant, Init->getSourceRange());
1241 return true;
1242 }
1243 case Expr::ImplicitCastExprClass:
1244 case Expr::CastExprClass: {
1245 const Expr *SubExpr;
1246 if (const CastExpr *C = dyn_cast<CastExpr>(Init)) {
1247 SubExpr = C->getSubExpr();
1248 } else {
1249 SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1250 }
1251
1252 if (SubExpr->getType()->isArithmeticType())
1253 return CheckArithmeticConstantExpression(SubExpr);
1254
1255 Diag(Init->getExprLoc(),
1256 diag::err_init_element_not_constant, Init->getSourceRange());
1257 return true;
1258 }
1259 case Expr::ConditionalOperatorClass: {
1260 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1261 if (CheckArithmeticConstantExpression(Exp->getCond()))
1262 return true;
1263 if (Exp->getLHS() &&
1264 CheckArithmeticConstantExpression(Exp->getLHS()))
1265 return true;
1266 return CheckArithmeticConstantExpression(Exp->getRHS());
1267 }
1268 }
1269}
1270
1271bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
1272 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1273 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1274 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1275
1276 if (Init->getType()->isReferenceType()) {
1277 // FIXME: Work out how the heck reference types work
1278 return false;
1279#if 0
1280 // A reference is constant if the address of the expression
1281 // is constant
1282 // We look through initlists here to simplify
1283 // CheckAddressConstantExpressionLValue.
1284 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1285 assert(Exp->getNumInits() > 0 &&
1286 "Refernce initializer cannot be empty");
1287 Init = Exp->getInit(0);
1288 }
1289 return CheckAddressConstantExpressionLValue(Init);
1290#endif
1291 }
1292
1293 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1294 unsigned numInits = Exp->getNumInits();
1295 for (unsigned i = 0; i < numInits; i++) {
1296 // FIXME: Need to get the type of the declaration for C++,
1297 // because it could be a reference?
1298 if (CheckForConstantInitializer(Exp->getInit(i),
1299 Exp->getInit(i)->getType()))
1300 return true;
1301 }
1302 return false;
1303 }
1304
1305 if (Init->isNullPointerConstant(Context))
1306 return false;
1307 if (Init->getType()->isArithmeticType()) {
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001308 QualType InitTy = Init->getType().getCanonicalType().getUnqualifiedType();
1309 if (InitTy == Context.BoolTy) {
1310 // Special handling for pointers implicitly cast to bool;
1311 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1312 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1313 Expr* SubE = ICE->getSubExpr();
1314 if (SubE->getType()->isPointerType() ||
1315 SubE->getType()->isArrayType() ||
1316 SubE->getType()->isFunctionType()) {
1317 return CheckAddressConstantExpression(Init);
1318 }
1319 }
1320 } else if (InitTy->isIntegralType()) {
1321 Expr* SubE = 0;
1322 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init))
1323 SubE = ICE->getSubExpr();
1324 else if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1325 SubE = CE->getSubExpr();
1326 // Special check for pointer cast to int; we allow as an extension
1327 // an address constant cast to an integer if the integer
1328 // is of an appropriate width (this sort of code is apparently used
1329 // in some places).
1330 // FIXME: Add pedwarn?
1331 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1332 if (SubE && (SubE->getType()->isPointerType() ||
1333 SubE->getType()->isArrayType() ||
1334 SubE->getType()->isFunctionType())) {
1335 unsigned IntWidth = Context.getTypeSize(Init->getType());
1336 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1337 if (IntWidth >= PointerWidth)
1338 return CheckAddressConstantExpression(Init);
1339 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001340 }
1341
1342 return CheckArithmeticConstantExpression(Init);
1343 }
1344
1345 if (Init->getType()->isPointerType())
1346 return CheckAddressConstantExpression(Init);
1347
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001348 // An array type at the top level that isn't an init-list must
1349 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001350 if (Init->getType()->isArrayType())
1351 return false;
1352
1353 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1354 Init->getSourceRange());
1355 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001356}
1357
Steve Naroffbb204692007-09-12 14:07:44 +00001358void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001359 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001360 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001361 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001362
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001363 // If there is no declaration, there was an error parsing it. Just ignore
1364 // the initializer.
1365 if (RealDecl == 0) {
1366 delete Init;
1367 return;
1368 }
Steve Naroffbb204692007-09-12 14:07:44 +00001369
Steve Naroff410e3e22007-09-12 20:13:48 +00001370 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1371 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001372 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1373 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001374 RealDecl->setInvalidDecl();
1375 return;
1376 }
Steve Naroffbb204692007-09-12 14:07:44 +00001377 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001378 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001379 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001380 if (VDecl->isBlockVarDecl()) {
1381 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001382 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001383 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001384 VDecl->setInvalidDecl();
1385 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +00001386 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001387 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001388 if (SC == VarDecl::Static) // C99 6.7.8p4.
1389 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001390 }
Steve Naroff248a7532008-04-15 22:42:06 +00001391 } else if (VDecl->isFileVarDecl()) {
1392 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001393 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001394 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001395 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001396 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001397
1398 // C99 6.7.8p4. All file scoped initializers need to be constant.
1399 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001400 }
1401 // If the type changed, it means we had an incomplete type that was
1402 // completed by the initializer. For example:
1403 // int ary[] = { 1, 3, 5 };
1404 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001405 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001406 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001407 Init->setType(DclT);
1408 }
Steve Naroffbb204692007-09-12 14:07:44 +00001409
1410 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001411 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001412 return;
1413}
1414
Reid Spencer5f016e22007-07-11 17:01:13 +00001415/// The declarators are chained together backwards, reverse the list.
1416Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1417 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001418 Decl *GroupDecl = static_cast<Decl*>(group);
1419 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001420 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001421
1422 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1423 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001424 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001426 else { // reverse the list.
1427 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001428 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001429 Group->setNextDeclarator(NewGroup);
1430 NewGroup = Group;
1431 Group = Next;
1432 }
1433 }
1434 // Perform semantic analysis that depends on having fully processed both
1435 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001436 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001437 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1438 if (!IDecl)
1439 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001440 QualType T = IDecl->getType();
1441
1442 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1443 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001444 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1445 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +00001446 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001447 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1448 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001449 }
1450 }
1451 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1452 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001453 if (IDecl->isBlockVarDecl() &&
1454 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001455 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001456 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1457 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001458 IDecl->setInvalidDecl();
1459 }
1460 }
1461 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1462 // object that has file scope without an initializer, and without a
1463 // storage-class specifier or with the storage-class specifier "static",
1464 // constitutes a tentative definition. Note: A tentative definition with
1465 // external linkage is valid (C99 6.2.2p5).
Steve Naroff248a7532008-04-15 22:42:06 +00001466 if (IDecl && !IDecl->getInit() &&
1467 (IDecl->getStorageClass() == VarDecl::Static ||
1468 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001469 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001470 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1471 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001472 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001473 // C99 6.9.2p3: If the declaration of an identifier for an object is
1474 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1475 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001476 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1477 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001478 IDecl->setInvalidDecl();
1479 }
1480 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001481 }
1482 return NewGroup;
1483}
Steve Naroffe1223f72007-08-28 03:03:08 +00001484
Chris Lattner04421082008-04-08 04:40:51 +00001485/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1486/// to introduce parameters into function prototype scope.
1487Sema::DeclTy *
1488Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1489 DeclSpec &DS = D.getDeclSpec();
1490
1491 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1492 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1493 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1494 Diag(DS.getStorageClassSpecLoc(),
1495 diag::err_invalid_storage_class_in_func_decl);
1496 DS.ClearStorageClassSpecs();
1497 }
1498 if (DS.isThreadSpecified()) {
1499 Diag(DS.getThreadSpecLoc(),
1500 diag::err_invalid_storage_class_in_func_decl);
1501 DS.ClearStorageClassSpecs();
1502 }
1503
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001504 // Check that there are no default arguments inside the type of this
1505 // parameter (C++ only).
1506 if (getLangOptions().CPlusPlus)
1507 CheckExtraCXXDefaultArguments(D);
1508
Chris Lattner04421082008-04-08 04:40:51 +00001509 // In this context, we *do not* check D.getInvalidType(). If the declarator
1510 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1511 // though it will not reflect the user specified type.
1512 QualType parmDeclType = GetTypeForDeclarator(D, S);
1513
1514 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1515
Reid Spencer5f016e22007-07-11 17:01:13 +00001516 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1517 // Can this happen for params? We already checked that they don't conflict
1518 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001519 IdentifierInfo *II = D.getIdentifier();
1520 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1521 if (S->isDeclScope(PrevDecl)) {
1522 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1523 dyn_cast<NamedDecl>(PrevDecl)->getName());
1524
1525 // Recover by removing the name
1526 II = 0;
1527 D.SetIdentifier(0, D.getIdentifierLoc());
1528 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001529 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001530
1531 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1532 // Doing the promotion here has a win and a loss. The win is the type for
1533 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1534 // code generator). The loss is the orginal type isn't preserved. For example:
1535 //
1536 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1537 // int blockvardecl[5];
1538 // sizeof(parmvardecl); // size == 4
1539 // sizeof(blockvardecl); // size == 20
1540 // }
1541 //
1542 // For expressions, all implicit conversions are captured using the
1543 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1544 //
1545 // FIXME: If a source translation tool needs to see the original type, then
1546 // we need to consider storing both types (in ParmVarDecl)...
1547 //
Chris Lattnere6327742008-04-02 05:18:44 +00001548 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001549 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001550 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001551 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001552 parmDeclType = Context.getPointerType(parmDeclType);
1553
Chris Lattner04421082008-04-08 04:40:51 +00001554 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1555 D.getIdentifierLoc(), II,
1556 parmDeclType, VarDecl::None,
1557 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001558
Chris Lattner04421082008-04-08 04:40:51 +00001559 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001560 New->setInvalidDecl();
1561
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001562 if (II)
1563 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001564
Nate Begemanfc584522008-05-09 16:56:01 +00001565 HandleDeclAttributes(New, D.getDeclSpec().getAttributes(),
1566 D.getAttributes());
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001568
Reid Spencer5f016e22007-07-11 17:01:13 +00001569}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001570
Chris Lattnerb652cea2007-10-09 17:14:05 +00001571Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 assert(CurFunctionDecl == 0 && "Function parsing confused");
1573 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1574 "Not a function declarator!");
1575 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001576
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1578 // for a K&R function.
1579 if (!FTI.hasPrototype) {
1580 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001581 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1583 FTI.ArgInfo[i].Ident->getName());
1584 // Implicitly declare the argument as type 'int' for lack of a better
1585 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001586 DeclSpec DS;
1587 const char* PrevSpec; // unused
1588 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1589 PrevSpec);
1590 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1591 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1592 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 }
1594 }
Chris Lattner52804082008-02-17 19:31:09 +00001595
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 // Since this is a function definition, act as though we have information
1597 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001598 if (FTI.NumArgs)
1599 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001601 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 }
1603
1604 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001605
1606 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001607 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001608 GlobalScope);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001609 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1610 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1611 const FunctionDecl *Definition;
1612 if (FD->getBody(Definition)) {
1613 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1614 D.getIdentifier()->getName());
1615 Diag(Definition->getLocation(), diag::err_previous_definition);
1616 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001617 }
1618 }
Steve Narofffabbc342008-02-12 01:09:36 +00001619 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001620 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001621 CurFunctionDecl = FD;
Chris Lattnerb048c982008-04-06 04:47:34 +00001622 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001623
1624 // Check the validity of our function parameters
1625 CheckParmsForFunctionDef(FD);
1626
1627 // Introduce our parameters into the function scope
1628 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1629 ParmVarDecl *Param = FD->getParamDecl(p);
1630 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001631 if (Param->getIdentifier())
1632 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 }
Chris Lattner04421082008-04-08 04:40:51 +00001634
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 return FD;
1636}
1637
Steve Naroffd6d054d2007-11-11 23:20:51 +00001638Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1639 Decl *dcl = static_cast<Decl *>(D);
1640 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1641 FD->setBody((Stmt*)Body);
1642 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001643 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001644 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001645 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001646 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001647 }
Chris Lattnerb048c982008-04-06 04:47:34 +00001648 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001649 // Verify and clean out per-function state.
1650
1651 // Check goto/label use.
1652 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1653 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1654 // Verify that we have no forward references left. If so, there was a goto
1655 // or address of a label taken, but no definition of it. Label fwd
1656 // definitions are indicated with a null substmt.
1657 if (I->second->getSubStmt() == 0) {
1658 LabelStmt *L = I->second;
1659 // Emit error.
1660 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1661
1662 // At this point, we have gotos that use the bogus label. Stitch it into
1663 // the function body so that they aren't leaked and that the AST is well
1664 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001665 if (Body) {
1666 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1667 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1668 } else {
1669 // The whole function wasn't parsed correctly, just delete this.
1670 delete L;
1671 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 }
1673 }
1674 LabelMap.clear();
1675
Steve Naroffd6d054d2007-11-11 23:20:51 +00001676 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001677}
1678
Reid Spencer5f016e22007-07-11 17:01:13 +00001679/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1680/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001681ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1682 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001683 // Extension in C99. Legal in C90, but warn about it.
1684 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001686 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001687 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1688
1689 // FIXME: handle stuff like:
1690 // void foo() { extern float X(); }
1691 // void bar() { X(); } <-- implicit decl for X in another scope.
1692
1693 // Set a Declarator for the implicit definition: int foo();
1694 const char *Dummy;
1695 DeclSpec DS;
1696 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1697 Error = Error; // Silence warning.
1698 assert(!Error && "Error setting up implicit decl!");
1699 Declarator D(DS, Declarator::BlockContext);
1700 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1701 D.SetIdentifier(&II, Loc);
1702
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001703 // Insert this function into translation-unit scope.
1704
1705 DeclContext *PrevDC = CurContext;
1706 CurContext = Context.getTranslationUnitDecl();
1707
Steve Naroffe2ef8152008-04-04 14:32:09 +00001708 FunctionDecl *FD =
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001709 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001710 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001711
1712 CurContext = PrevDC;
1713
Steve Naroffe2ef8152008-04-04 14:32:09 +00001714 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001715}
1716
1717
Chris Lattner41af0932007-11-14 06:34:38 +00001718TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001719 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001720 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001721 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001722
1723 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001724 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1725 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001726 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001727 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001728 if (D.getInvalidType())
1729 NewTD->setInvalidDecl();
1730 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001731}
1732
Steve Naroff08d92e42007-09-15 18:49:24 +00001733/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001734/// former case, Name will be non-null. In the later case, Name will be null.
1735/// TagType indicates what kind of tag this is. TK indicates whether this is a
1736/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001737Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001738 SourceLocation KWLoc, IdentifierInfo *Name,
1739 SourceLocation NameLoc, AttributeList *Attr) {
1740 // If this is a use of an existing tag, it must have a name.
1741 assert((Name != 0 || TK == TK_Definition) &&
1742 "Nameless record must be a definition!");
1743
1744 Decl::Kind Kind;
1745 switch (TagType) {
1746 default: assert(0 && "Unknown tag type!");
1747 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1748 case DeclSpec::TST_union: Kind = Decl::Union; break;
Chris Lattner99dc9142008-04-13 18:59:07 +00001749 case DeclSpec::TST_class: Kind = Decl::Class; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001750 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1751 }
1752
1753 // If this is a named struct, check to see if there was a previous forward
1754 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001755 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1756 if (ScopedDecl *PrevDecl =
1757 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001758
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001759 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1760 "unexpected Decl type");
1761 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1762 // If this is a use of a previous tag, or if the tag is already declared in
1763 // the same scope (so that the definition/declaration completes or
1764 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001765 if (TK == TK_Reference ||
1766 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001767 // Make sure that this wasn't declared as an enum and now used as a struct
1768 // or something similar.
1769 if (PrevDecl->getKind() != Kind) {
1770 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1771 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1772 }
1773
1774 // If this is a use or a forward declaration, we're good.
1775 if (TK != TK_Definition)
1776 return PrevDecl;
Reid Spencer5f016e22007-07-11 17:01:13 +00001777
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001778 // Diagnose attempts to redefine a tag.
1779 if (PrevTagDecl->isDefinition()) {
1780 Diag(NameLoc, diag::err_redefinition, Name->getName());
1781 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1782 // If this is a redefinition, recover by making this struct be
1783 // anonymous, which will make any later references get the previous
1784 // definition.
1785 Name = 0;
1786 } else {
1787 // Okay, this is definition of a previously declared or referenced tag.
1788 // Move the location of the decl to be the definition site.
1789 PrevDecl->setLocation(NameLoc);
1790 return PrevDecl;
1791 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001792 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001793 // If we get here, this is a definition of a new struct type in a nested
1794 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1795 // type.
1796 } else {
1797 // The tag name clashes with a namespace name, issue an error and recover
1798 // by making this tag be anonymous.
1799 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1800 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1801 Name = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001803 }
1804
1805 // If there is an identifier, use the location of the identifier as the
1806 // location of the decl, otherwise use the location of the struct/union
1807 // keyword.
1808 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1809
1810 // Otherwise, if this is the first time we've seen this tag, create the decl.
1811 TagDecl *New;
1812 switch (Kind) {
1813 default: assert(0 && "Unknown tag kind!");
1814 case Decl::Enum:
1815 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1816 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001817 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001818 // If this is an undefined enum, warn.
1819 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1820 break;
1821 case Decl::Union:
1822 case Decl::Struct:
1823 case Decl::Class:
1824 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1825 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001826 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001827 break;
1828 }
1829
1830 // If this has an identifier, add it to the scope stack.
1831 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001832 // The scope passed in may not be a decl scope. Zip up the scope tree until
1833 // we find one that is.
1834 while ((S->getFlags() & Scope::DeclScope) == 0)
1835 S = S->getParent();
1836
1837 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001838 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001839 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001840
Anders Carlssonad148062008-02-16 00:29:18 +00001841 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001842 return New;
1843}
1844
Steve Naroff08d92e42007-09-15 18:49:24 +00001845/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001846/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001847Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001848 SourceLocation DeclStart,
1849 Declarator &D, ExprTy *BitfieldWidth) {
1850 IdentifierInfo *II = D.getIdentifier();
1851 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001852 SourceLocation Loc = DeclStart;
1853 if (II) Loc = D.getIdentifierLoc();
1854
1855 // FIXME: Unnamed fields can be handled in various different ways, for
1856 // example, unnamed unions inject all members into the struct namespace!
1857
1858
1859 if (BitWidth) {
1860 // TODO: Validate.
1861 //printf("WARNING: BITFIELDS IGNORED!\n");
1862
1863 // 6.7.2.1p3
1864 // 6.7.2.1p4
1865
1866 } else {
1867 // Not a bitfield.
1868
1869 // validate II.
1870
1871 }
1872
1873 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001874 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1875 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001876
Reid Spencer5f016e22007-07-11 17:01:13 +00001877 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1878 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001879 if (T->isVariablyModifiedType()) {
1880 // FIXME: This diagnostic needs work
1881 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroffd7444aa2007-08-31 17:20:07 +00001882 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001883 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001884 // FIXME: Chain fielddecls together.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001885 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001886
Anders Carlssonad148062008-02-16 00:29:18 +00001887 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1888 D.getAttributes());
1889
Steve Naroff5912a352007-08-28 20:14:24 +00001890 if (D.getInvalidType() || InvalidDecl)
1891 NewFD->setInvalidDecl();
1892 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001893}
1894
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001895/// TranslateIvarVisibility - Translate visibility from a token ID to an
1896/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001897static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001898TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001899 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001900 case tok::objc_private: return ObjCIvarDecl::Private;
1901 case tok::objc_public: return ObjCIvarDecl::Public;
1902 case tok::objc_protected: return ObjCIvarDecl::Protected;
1903 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001904 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001905 }
1906}
1907
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001908/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1909/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001910Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001911 SourceLocation DeclStart,
1912 Declarator &D, ExprTy *BitfieldWidth,
1913 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001914 IdentifierInfo *II = D.getIdentifier();
1915 Expr *BitWidth = (Expr*)BitfieldWidth;
1916 SourceLocation Loc = DeclStart;
1917 if (II) Loc = D.getIdentifierLoc();
1918
1919 // FIXME: Unnamed fields can be handled in various different ways, for
1920 // example, unnamed unions inject all members into the struct namespace!
1921
1922
1923 if (BitWidth) {
1924 // TODO: Validate.
1925 //printf("WARNING: BITFIELDS IGNORED!\n");
1926
1927 // 6.7.2.1p3
1928 // 6.7.2.1p4
1929
1930 } else {
1931 // Not a bitfield.
1932
1933 // validate II.
1934
1935 }
1936
1937 QualType T = GetTypeForDeclarator(D, S);
1938 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1939 bool InvalidDecl = false;
1940
1941 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1942 // than a variably modified type.
1943 if (T->isVariablyModifiedType()) {
1944 // FIXME: This diagnostic needs work
1945 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1946 InvalidDecl = true;
1947 }
1948
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001949 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001950
1951 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1952 D.getAttributes());
1953
1954 if (D.getInvalidType() || InvalidDecl)
1955 NewID->setInvalidDecl();
1956 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001957 if (Visibility != tok::objc_not_keyword)
1958 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001959 return NewID;
1960}
1961
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001962void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001963 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001964 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001965 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001966 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1967 assert(EnclosingDecl && "missing record or interface decl");
1968 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1969
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001970 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001971 // Diagnose code like:
1972 // struct S { struct S {} X; };
1973 // We discover this when we complete the outer S. Reject and ignore the
1974 // outer S.
1975 Diag(Record->getLocation(), diag::err_nested_redefinition,
1976 Record->getKindName());
1977 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001978 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001979 return;
1980 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001981 // Verify that all the fields are okay.
1982 unsigned NumNamedMembers = 0;
1983 llvm::SmallVector<FieldDecl*, 32> RecFields;
1984 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001985
Reid Spencer5f016e22007-07-11 17:01:13 +00001986 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001987
Steve Naroff74216642007-09-14 22:20:54 +00001988 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1989 assert(FD && "missing field decl");
1990
1991 // Remember all fields.
1992 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001993
1994 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001995 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00001996
Reid Spencer5f016e22007-07-11 17:01:13 +00001997 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001998 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001999 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002000 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002001 FD->setInvalidDecl();
2002 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 continue;
2004 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002005 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2006 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002007 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002008 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002009 FD->setInvalidDecl();
2010 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002011 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002012 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002013 if (i != NumFields-1 || // ... that the last member ...
2014 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002015 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002016 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002017 FD->setInvalidDecl();
2018 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002019 continue;
2020 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002021 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002022 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2023 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002024 FD->setInvalidDecl();
2025 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 continue;
2027 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002029 if (Record)
2030 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002031 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002032 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2033 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002034 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002035 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2036 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002037 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002038 Record->setHasFlexibleArrayMember(true);
2039 } else {
2040 // If this is a struct/class and this is not the last element, reject
2041 // it. Note that GCC supports variable sized arrays in the middle of
2042 // structures.
2043 if (i != NumFields-1) {
2044 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2045 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002046 FD->setInvalidDecl();
2047 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002048 continue;
2049 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002050 // We support flexible arrays at the end of structs in other structs
2051 // as an extension.
2052 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2053 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002054 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002055 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002056 }
2057 }
2058 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002059 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002060 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002061 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2062 FD->getName());
2063 FD->setInvalidDecl();
2064 EnclosingDecl->setInvalidDecl();
2065 continue;
2066 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002067 // Keep track of the number of named members.
2068 if (IdentifierInfo *II = FD->getIdentifier()) {
2069 // Detect duplicate member names.
2070 if (!FieldIDs.insert(II)) {
2071 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2072 // Find the previous decl.
2073 SourceLocation PrevLoc;
2074 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2075 assert(i != e && "Didn't find previous def!");
2076 if (RecFields[i]->getIdentifier() == II) {
2077 PrevLoc = RecFields[i]->getLocation();
2078 break;
2079 }
2080 }
2081 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002082 FD->setInvalidDecl();
2083 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002084 continue;
2085 }
2086 ++NumNamedMembers;
2087 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 }
2089
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002091 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002092 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00002093 Consumer.HandleTagDeclDefinition(Record);
2094 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002095 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2096 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2097 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2098 else if (ObjCImplementationDecl *IMPDecl =
2099 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002100 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2101 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002102 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002103 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002104 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002105}
2106
Steve Naroff08d92e42007-09-15 18:49:24 +00002107Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002108 DeclTy *lastEnumConst,
2109 SourceLocation IdLoc, IdentifierInfo *Id,
2110 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002111 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 EnumConstantDecl *LastEnumConst =
2113 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2114 Expr *Val = static_cast<Expr*>(val);
2115
Chris Lattner31e05722007-08-26 06:24:45 +00002116 // The scope passed in may not be a decl scope. Zip up the scope tree until
2117 // we find one that is.
2118 while ((S->getFlags() & Scope::DeclScope) == 0)
2119 S = S->getParent();
2120
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 // Verify that there isn't already something declared with this name in this
2122 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002123 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00002124 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 if (isa<EnumConstantDecl>(PrevDecl))
2126 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2127 else
2128 Diag(IdLoc, diag::err_redefinition, Id->getName());
2129 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002130 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002131 return 0;
2132 }
2133 }
2134
2135 llvm::APSInt EnumVal(32);
2136 QualType EltTy;
2137 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002138 // Make sure to promote the operand type to int.
2139 UsualUnaryConversions(Val);
2140
Reid Spencer5f016e22007-07-11 17:01:13 +00002141 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2142 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002143 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002144 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2145 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002146 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002147 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002148 } else {
2149 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002151 }
2152
2153 if (!Val) {
2154 if (LastEnumConst) {
2155 // Assign the last value + 1.
2156 EnumVal = LastEnumConst->getInitVal();
2157 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002158
2159 // Check for overflow on increment.
2160 if (EnumVal < LastEnumConst->getInitVal())
2161 Diag(IdLoc, diag::warn_enum_value_overflow);
2162
Chris Lattnerb7416f92007-08-27 17:37:24 +00002163 EltTy = LastEnumConst->getType();
2164 } else {
2165 // First value, set to zero.
2166 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002167 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002168 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002169 }
2170
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002171 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002172 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2173 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002174 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002175
2176 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002177 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002178 return New;
2179}
2180
Steve Naroff08d92e42007-09-15 18:49:24 +00002181void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002182 DeclTy **Elements, unsigned NumElements) {
2183 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
2184 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
2185
Chris Lattnere37f0be2007-08-28 05:10:31 +00002186 // TODO: If the result value doesn't fit in an int, it must be a long or long
2187 // long value. ISO C does not support this, but GCC does as an extension,
2188 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002189 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002190
Chris Lattnerac609682007-08-28 06:15:15 +00002191 // Verify that all the values are okay, compute the size of the values, and
2192 // reverse the list.
2193 unsigned NumNegativeBits = 0;
2194 unsigned NumPositiveBits = 0;
2195
2196 // Keep track of whether all elements have type int.
2197 bool AllElementsInt = true;
2198
Reid Spencer5f016e22007-07-11 17:01:13 +00002199 EnumConstantDecl *EltList = 0;
2200 for (unsigned i = 0; i != NumElements; ++i) {
2201 EnumConstantDecl *ECD =
2202 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2203 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002204
2205 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002206 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002207 assert(InitVal.getBitWidth() >= IntWidth &&
2208 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002209 if (InitVal.getBitWidth() > IntWidth) {
2210 llvm::APSInt V(InitVal);
2211 V.trunc(IntWidth);
2212 V.extend(InitVal.getBitWidth());
2213 if (V != InitVal)
2214 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2215 InitVal.toString());
2216 }
Chris Lattnerac609682007-08-28 06:15:15 +00002217
2218 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002219 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002220 NumPositiveBits = std::max(NumPositiveBits,
2221 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002222 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002223 NumNegativeBits = std::max(NumNegativeBits,
2224 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002225
Chris Lattnerac609682007-08-28 06:15:15 +00002226 // Keep track of whether every enum element has type int (very commmon).
2227 if (AllElementsInt)
2228 AllElementsInt = ECD->getType() == Context.IntTy;
2229
Reid Spencer5f016e22007-07-11 17:01:13 +00002230 ECD->setNextDeclarator(EltList);
2231 EltList = ECD;
2232 }
2233
Chris Lattnerac609682007-08-28 06:15:15 +00002234 // Figure out the type that should be used for this enum.
2235 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2236 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002237 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002238
2239 if (NumNegativeBits) {
2240 // If there is a negative value, figure out the smallest integer type (of
2241 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002242 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002243 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002244 BestWidth = IntWidth;
2245 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002246 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002247
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002248 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002249 BestType = Context.LongTy;
2250 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002251 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002252
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002253 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002254 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2255 BestType = Context.LongLongTy;
2256 }
2257 }
2258 } else {
2259 // If there is no negative value, figure out which of uint, ulong, ulonglong
2260 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002261 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002262 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002263 BestWidth = IntWidth;
2264 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002265 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002266 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002267 } else {
2268 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002269 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002270 "How could an initializer get larger than ULL?");
2271 BestType = Context.UnsignedLongLongTy;
2272 }
2273 }
2274
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002275 // Loop over all of the enumerator constants, changing their types to match
2276 // the type of the enum if needed.
2277 for (unsigned i = 0; i != NumElements; ++i) {
2278 EnumConstantDecl *ECD =
2279 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2280 if (!ECD) continue; // Already issued a diagnostic.
2281
2282 // Standard C says the enumerators have int type, but we allow, as an
2283 // extension, the enumerators to be larger than int size. If each
2284 // enumerator value fits in an int, type it as an int, otherwise type it the
2285 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2286 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002287 if (ECD->getType() == Context.IntTy) {
2288 // Make sure the init value is signed.
2289 llvm::APSInt IV = ECD->getInitVal();
2290 IV.setIsSigned(true);
2291 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002292 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002293 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002294
2295 // Determine whether the value fits into an int.
2296 llvm::APSInt InitVal = ECD->getInitVal();
2297 bool FitsInInt;
2298 if (InitVal.isUnsigned() || !InitVal.isNegative())
2299 FitsInInt = InitVal.getActiveBits() < IntWidth;
2300 else
2301 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2302
2303 // If it fits into an integer type, force it. Otherwise force it to match
2304 // the enum decl type.
2305 QualType NewTy;
2306 unsigned NewWidth;
2307 bool NewSign;
2308 if (FitsInInt) {
2309 NewTy = Context.IntTy;
2310 NewWidth = IntWidth;
2311 NewSign = true;
2312 } else if (ECD->getType() == BestType) {
2313 // Already the right type!
2314 continue;
2315 } else {
2316 NewTy = BestType;
2317 NewWidth = BestWidth;
2318 NewSign = BestType->isSignedIntegerType();
2319 }
2320
2321 // Adjust the APSInt value.
2322 InitVal.extOrTrunc(NewWidth);
2323 InitVal.setIsSigned(NewSign);
2324 ECD->setInitVal(InitVal);
2325
2326 // Adjust the Expr initializer and type.
2327 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2328 ECD->setType(NewTy);
2329 }
Chris Lattnerac609682007-08-28 06:15:15 +00002330
Chris Lattnere00b18c2007-08-28 18:24:31 +00002331 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002332 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002333}
2334
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002335Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2336 ExprTy *expr) {
2337 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2338
Chris Lattner8e25d862008-03-16 00:16:02 +00002339 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002340}
2341
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002342Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002343 SourceLocation LBrace,
2344 SourceLocation RBrace,
2345 const char *Lang,
2346 unsigned StrSize,
2347 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002348 LinkageSpecDecl::LanguageIDs Language;
2349 Decl *dcl = static_cast<Decl *>(D);
2350 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2351 Language = LinkageSpecDecl::lang_c;
2352 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2353 Language = LinkageSpecDecl::lang_cxx;
2354 else {
2355 Diag(Loc, diag::err_bad_language);
2356 return 0;
2357 }
2358
2359 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002360 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002361}
2362
Chris Lattner74788ba2008-02-21 00:48:22 +00002363void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00002364
Chris Lattner74788ba2008-02-21 00:48:22 +00002365 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00002366 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00002368 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002369 if (!newType.isNull()) // install the new vector type into the decl
2370 vDecl->setType(newType);
2371 }
2372 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2373 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00002374 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002375 if (!newType.isNull()) // install the new vector type into the decl
2376 tDecl->setUnderlyingType(newType);
2377 }
Chris Lattner212839c2008-02-20 23:17:35 +00002378 break;
Nate Begeman213541a2008-04-18 23:10:10 +00002379 case AttributeList::AT_ext_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00002380 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Nate Begeman213541a2008-04-18 23:10:10 +00002381 HandleExtVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00002382 else
Chris Lattner74788ba2008-02-21 00:48:22 +00002383 Diag(Attr->getLoc(),
Nate Begeman213541a2008-04-18 23:10:10 +00002384 diag::err_typecheck_ext_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00002385 break;
2386 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00002387 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2388 QualType newType = HandleAddressSpaceTypeAttribute(
2389 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00002390 Attr);
2391 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00002392 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2393 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00002394 Attr);
2395 // install the new addr spaced type into the decl
2396 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00002397 }
Chris Lattner212839c2008-02-20 23:17:35 +00002398 break;
Eli Friedman3c0eb162008-05-27 03:33:27 +00002399 case AttributeList::AT_mode:
2400 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2401 QualType newType = HandleModeTypeAttribute(tDecl->getUnderlyingType(),
2402 Attr);
2403 tDecl->setUnderlyingType(newType);
2404 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2405 QualType newType = HandleModeTypeAttribute(vDecl->getType(), Attr);
2406 vDecl->setType(newType);
2407 }
2408 // FIXME: Diagnostic?
2409 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00002410 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00002411 HandleDeprecatedAttribute(New, Attr);
2412 break;
2413 case AttributeList::AT_visibility:
2414 HandleVisibilityAttribute(New, Attr);
2415 break;
2416 case AttributeList::AT_weak:
2417 HandleWeakAttribute(New, Attr);
2418 break;
2419 case AttributeList::AT_dllimport:
2420 HandleDLLImportAttribute(New, Attr);
2421 break;
2422 case AttributeList::AT_dllexport:
2423 HandleDLLExportAttribute(New, Attr);
2424 break;
2425 case AttributeList::AT_nothrow:
2426 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00002427 break;
Nate Begeman440b4562008-03-07 20:04:22 +00002428 case AttributeList::AT_stdcall:
2429 HandleStdCallAttribute(New, Attr);
2430 break;
2431 case AttributeList::AT_fastcall:
2432 HandleFastCallAttribute(New, Attr);
2433 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002434 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00002435 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002436 break;
2437 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00002438 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002439 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00002440 case AttributeList::AT_annotate:
2441 HandleAnnotateAttribute(New, Attr);
2442 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00002443 case AttributeList::AT_noreturn:
2444 HandleNoReturnAttribute(New, Attr);
2445 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00002446 case AttributeList::AT_format:
2447 HandleFormatAttribute(New, Attr);
2448 break;
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002449 case AttributeList::AT_transparent_union:
2450 HandleTransparentUnionAttribute(New, Attr);
2451 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002452 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00002453#if 0
2454 // TODO: when we have the full set of attributes, warn about unknown ones.
2455 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
2456 Attr->getName()->getName());
2457#endif
Chris Lattner212839c2008-02-20 23:17:35 +00002458 break;
2459 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002460}
2461
2462void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2463 AttributeList *declarator_postfix) {
2464 while (declspec_prefix) {
2465 HandleDeclAttribute(New, declspec_prefix);
2466 declspec_prefix = declspec_prefix->getNext();
2467 }
2468 while (declarator_postfix) {
2469 HandleDeclAttribute(New, declarator_postfix);
2470 declarator_postfix = declarator_postfix->getNext();
2471 }
2472}
2473
Nate Begeman213541a2008-04-18 23:10:10 +00002474void Sema::HandleExtVectorTypeAttribute(TypedefDecl *tDecl,
Steve Naroffbea0b342007-07-29 16:33:31 +00002475 AttributeList *rawAttr) {
2476 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00002477 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00002478 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002479 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00002480 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002481 return;
Steve Naroff73322922007-07-18 18:00:27 +00002482 }
2483 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2484 llvm::APSInt vecSize(32);
2485 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002486 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Nate Begeman213541a2008-04-18 23:10:10 +00002487 "ext_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002488 return;
Steve Naroff73322922007-07-18 18:00:27 +00002489 }
2490 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2491 // in conjunction with complex types (pointers, arrays, functions, etc.).
2492 Type *canonType = curType.getCanonicalType().getTypePtr();
2493 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002494 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00002495 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002496 return;
Steve Naroff73322922007-07-18 18:00:27 +00002497 }
2498 // unlike gcc's vector_size attribute, the size is specified as the
2499 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002500 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002501
2502 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002503 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00002504 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002505 return;
Steve Naroff73322922007-07-18 18:00:27 +00002506 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002507 // Instantiate/Install the vector type, the number of elements is > 0.
Nate Begeman213541a2008-04-18 23:10:10 +00002508 tDecl->setUnderlyingType(Context.getExtVectorType(curType, vectorSize));
Steve Naroffbea0b342007-07-29 16:33:31 +00002509 // Remember this typedef decl, we will need it later for diagnostics.
Nate Begeman213541a2008-04-18 23:10:10 +00002510 ExtVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002511}
2512
Reid Spencer5f016e22007-07-11 17:01:13 +00002513QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002514 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002515 // check the attribute arugments.
2516 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002517 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00002518 std::string("1"));
2519 return QualType();
2520 }
2521 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2522 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002523 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002524 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002525 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002526 return QualType();
2527 }
2528 // navigate to the base type - we need to provide for vector pointers,
2529 // vector arrays, and functions returning vectors.
2530 Type *canonType = curType.getCanonicalType().getTypePtr();
2531
Steve Naroff73322922007-07-18 18:00:27 +00002532 if (canonType->isPointerType() || canonType->isArrayType() ||
2533 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00002534 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00002535 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2536 do {
2537 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2538 canonType = PT->getPointeeType().getTypePtr();
2539 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2540 canonType = AT->getElementType().getTypePtr();
2541 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2542 canonType = FT->getResultType().getTypePtr();
2543 } while (canonType->isPointerType() || canonType->isArrayType() ||
2544 canonType->isFunctionType());
2545 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002546 }
2547 // the base type must be integer or float.
2548 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002549 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00002550 curType.getCanonicalType().getAsString());
2551 return QualType();
2552 }
Chris Lattner98be4942008-03-05 18:54:05 +00002553 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00002554 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002555 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002556
2557 // the vector size needs to be an integral multiple of the type size.
2558 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00002559 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002560 sizeExpr->getSourceRange());
2561 return QualType();
2562 }
2563 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002564 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002565 sizeExpr->getSourceRange());
2566 return QualType();
2567 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00002568 // Instantiate the vector type, the number of elements is > 0, and not
2569 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00002570 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002571}
2572
Chris Lattner2070d802008-02-20 23:25:22 +00002573void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00002574 // check the attribute arguments.
2575 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002576 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00002577 std::string("0"));
2578 return;
2579 }
2580
2581 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2582 TD->addAttr(new PackedAttr);
2583 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2584 // If the alignment is less than or equal to 8 bits, the packed attribute
2585 // has no effect.
Chris Lattnerabb57582008-05-09 05:34:49 +00002586 if (!FD->getType()->isIncompleteType() &&
2587 Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002588 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002589 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002590 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002591 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002592 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002593 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002594 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2595 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002596}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002597
Ted Kremenekaecb3832008-02-27 20:43:06 +00002598void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2599 // check the attribute arguments.
2600 if (rawAttr->getNumArgs() != 0) {
2601 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2602 std::string("0"));
2603 return;
2604 }
2605
Ted Kremenek3465fb32008-03-03 16:52:27 +00002606 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2607
2608 if (!Fn) {
2609 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2610 "noreturn", "function");
2611 return;
2612 }
2613
Ted Kremenekaecb3832008-02-27 20:43:06 +00002614 d->addAttr(new NoReturnAttr());
2615}
2616
Chris Lattnerddee4232008-03-03 03:28:21 +00002617void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2618 // check the attribute arguments.
2619 if (rawAttr->getNumArgs() != 0) {
2620 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2621 std::string("0"));
2622 return;
2623 }
2624
2625 d->addAttr(new DeprecatedAttr());
2626}
2627
2628void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2629 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002630 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002631 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2632 std::string("1"));
2633 return;
2634 }
2635
Chris Lattner7b937ae2008-03-04 18:08:48 +00002636 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2637 Arg = Arg->IgnoreParenCasts();
2638 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2639
2640 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002641 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002642 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002643 return;
2644 }
2645
Chris Lattner7b937ae2008-03-04 18:08:48 +00002646 const char *TypeStr = Str->getStrData();
2647 unsigned TypeLen = Str->getByteLength();
Dan Gohman4f8d1232008-05-22 00:50:06 +00002648 VisibilityAttr::VisibilityTypes type;
Chris Lattnerddee4232008-03-03 03:28:21 +00002649
Chris Lattner7b937ae2008-03-04 18:08:48 +00002650 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002651 type = VisibilityAttr::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002652 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002653 type = VisibilityAttr::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002654 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002655 type = VisibilityAttr::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002656 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Dan Gohman4f8d1232008-05-22 00:50:06 +00002657 type = VisibilityAttr::ProtectedVisibility;
Chris Lattnerddee4232008-03-03 03:28:21 +00002658 else {
2659 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002660 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002661 return;
2662 }
2663
2664 d->addAttr(new VisibilityAttr(type));
2665}
2666
2667void Sema::HandleWeakAttribute(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 WeakAttr());
2676}
2677
2678void Sema::HandleDLLImportAttribute(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 DLLImportAttr());
2687}
2688
2689void Sema::HandleDLLExportAttribute(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 DLLExportAttr());
2698}
2699
Nate Begeman440b4562008-03-07 20:04:22 +00002700void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2701 // check the attribute arguments.
2702 if (rawAttr->getNumArgs() != 0) {
2703 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2704 std::string("0"));
2705 return;
2706 }
2707
2708 d->addAttr(new StdCallAttr());
2709}
2710
2711void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2712 // check the attribute arguments.
2713 if (rawAttr->getNumArgs() != 0) {
2714 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2715 std::string("0"));
2716 return;
2717 }
2718
2719 d->addAttr(new FastCallAttr());
2720}
2721
Chris Lattnerddee4232008-03-03 03:28:21 +00002722void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2723 // check the attribute arguments.
2724 if (rawAttr->getNumArgs() != 0) {
2725 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2726 std::string("0"));
2727 return;
2728 }
2729
2730 d->addAttr(new NoThrowAttr());
2731}
2732
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002733static const FunctionTypeProto *getFunctionProto(Decl *d) {
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002734 QualType Ty;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002735
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002736 if (ValueDecl *decl = dyn_cast<ValueDecl>(d))
2737 Ty = decl->getType();
2738 else if (FieldDecl *decl = dyn_cast<FieldDecl>(d))
2739 Ty = decl->getType();
Ted Kremenek72786e02008-05-09 17:36:24 +00002740 else if (TypedefDecl* decl = dyn_cast<TypedefDecl>(d))
2741 Ty = decl->getUnderlyingType();
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002742 else
2743 return 0;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002744
2745 if (Ty->isFunctionPointerType()) {
2746 const PointerType *PtrTy = Ty->getAsPointerType();
2747 Ty = PtrTy->getPointeeType();
2748 }
2749
2750 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2751 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2752
2753 return 0;
2754}
2755
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002756static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
2757 if (!T->isPointerType())
2758 return false;
2759
2760 T = T->getAsPointerType()->getPointeeType().getCanonicalType();
2761 ObjCInterfaceType* ClsT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
2762
2763 if (!ClsT)
2764 return false;
2765
2766 IdentifierInfo* ClsName = ClsT->getDecl()->getIdentifier();
2767
2768 // FIXME: Should we walk the chain of classes?
2769 return ClsName == &Ctx.Idents.get("NSString") ||
2770 ClsName == &Ctx.Idents.get("NSMutableString");
2771}
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002772
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002773/// Handle __attribute__((format(type,idx,firstarg))) attributes
2774/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002775void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2776
2777 if (!rawAttr->getParameterName()) {
2778 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2779 "format", std::string("1"));
2780 return;
2781 }
2782
2783 if (rawAttr->getNumArgs() != 2) {
2784 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2785 std::string("3"));
2786 return;
2787 }
2788
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002789 // GCC ignores the format attribute on K&R style function
2790 // prototypes, so we ignore it as well
2791 const FunctionTypeProto *proto = getFunctionProto(d);
2792
2793 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002794 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2795 "format", "function");
2796 return;
2797 }
2798
2799 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002800 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002801 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002802 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002803 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002804
2805 const char *Format = rawAttr->getParameterName()->getName();
2806 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2807
2808 // Normalize the argument, __foo__ becomes foo.
2809 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2810 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2811 Format += 2;
2812 FormatLen -= 4;
2813 }
2814
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002815 bool Supported = false;
2816 bool is_NSString = false;
2817 bool is_strftime = false;
2818
2819 switch (FormatLen) {
2820 default: break;
2821 case 5:
2822 Supported = !memcmp(Format, "scanf", 5);
2823 break;
2824 case 6:
2825 Supported = !memcmp(Format, "printf", 6);
2826 break;
2827 case 7:
2828 Supported = !memcmp(Format, "strfmon", 7);
2829 break;
2830 case 8:
2831 Supported = (is_strftime = !memcmp(Format, "strftime", 8)) ||
2832 (is_NSString = !memcmp(Format, "NSString", 8));
2833 break;
2834 }
2835
2836 if (!Supported) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002837 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2838 "format", rawAttr->getParameterName()->getName());
2839 return;
2840 }
2841
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002842 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002843 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002844 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002845 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2846 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2847 "format", std::string("2"), IdxExpr->getSourceRange());
2848 return;
2849 }
2850
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002851 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002852 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2853 "format", std::string("2"), IdxExpr->getSourceRange());
2854 return;
2855 }
2856
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002857 // FIXME: Do we need to bounds check?
2858 unsigned ArgIdx = Idx.getZExtValue() - 1;
2859
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002860 // make sure the format string is really a string
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002861 QualType Ty = proto->getArgType(ArgIdx);
2862
2863 if (is_NSString) {
2864 // FIXME: do we need to check if the type is NSString*? What are
2865 // the semantics?
2866 if (!isNSStringType(Ty, Context)) {
2867 // FIXME: Should highlight the actual expression that has the
2868 // wrong type.
2869 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_NSString,
2870 IdxExpr->getSourceRange());
2871 return;
2872 }
2873 }
2874 else if (!Ty->isPointerType() ||
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002875 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002876 // FIXME: Should highlight the actual expression that has the
2877 // wrong type.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002878 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2879 IdxExpr->getSourceRange());
2880 return;
2881 }
2882
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002883 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002884 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002885 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002886 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2887 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2888 "format", std::string("3"), FirstArgExpr->getSourceRange());
2889 return;
2890 }
2891
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002892 // check if the function is variadic if the 3rd argument non-zero
2893 if (FirstArg != 0) {
2894 if (proto->isVariadic()) {
2895 ++NumArgs; // +1 for ...
2896 } else {
2897 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2898 return;
2899 }
2900 }
2901
2902 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2903 // the input is just the current time + the format string
Ted Kremenekc5f551f2008-05-08 19:43:35 +00002904 if (is_strftime) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002905 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002906 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2907 FirstArgExpr->getSourceRange());
2908 return;
2909 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002910 // if 0 it disables parameter checking (to use with e.g. va_list)
2911 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002912 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2913 "format", std::string("3"), FirstArgExpr->getSourceRange());
2914 return;
2915 }
2916
2917 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2918 Idx.getZExtValue(), FirstArg.getZExtValue()));
2919}
2920
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002921void Sema::HandleTransparentUnionAttribute(Decl *d, AttributeList *rawAttr) {
2922 // check the attribute arguments.
2923 if (rawAttr->getNumArgs() != 0) {
2924 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2925 std::string("0"));
2926 return;
2927 }
2928
2929 TypeDecl *decl = dyn_cast<TypeDecl>(d);
2930
2931 if (!decl || !Context.getTypeDeclType(decl)->isUnionType()) {
2932 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2933 "transparent_union", "union");
2934 return;
2935 }
2936
Chris Lattner22624942008-04-30 16:04:01 +00002937 //QualType QTy = Context.getTypeDeclType(decl);
2938 //const RecordType *Ty = QTy->getAsUnionType();
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002939
2940// FIXME
2941// Ty->addAttr(new TransparentUnionAttr());
2942}
2943
Nate Begemanc398f0b2008-02-21 19:30:49 +00002944void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2945 // check the attribute arguments.
2946 if (rawAttr->getNumArgs() != 1) {
2947 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2948 std::string("1"));
2949 return;
2950 }
2951 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2952 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002953
Nate Begemanc398f0b2008-02-21 19:30:49 +00002954 // Make sure that there is a string literal as the annotation's single
2955 // argument.
2956 if (!SE) {
2957 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2958 return;
2959 }
2960 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2961 SE->getByteLength())));
2962}
2963
Anders Carlsson78aaae92007-12-19 07:19:40 +00002964void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2965{
2966 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002967 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002968 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002969 std::string("1"));
2970 return;
2971 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002972
Anders Carlsson042c4e72008-02-16 19:51:27 +00002973 unsigned Align = 0;
2974
2975 if (rawAttr->getNumArgs() == 0) {
2976 // FIXME: This should be the target specific maximum alignment.
2977 // (For now we just use 128 bits which is the maximum on X86.
2978 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002979 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002980 } else {
2981 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2982 llvm::APSInt alignment(32);
2983 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002984 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002985 "aligned", alignmentExpr->getSourceRange());
2986 return;
2987 }
2988
2989 Align = alignment.getZExtValue() * 8;
2990 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002991
Anders Carlsson042c4e72008-02-16 19:51:27 +00002992 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002993}